C++ 我如何动态地思考这个任务?

C++ 我如何动态地思考这个任务?,c++,dynamic-programming,C++,Dynamic Programming,我认为这个问题是一个很好的初学者问题,可以用表格的方式来思考。我想我已经设法弄明白了要点,但仍然不是很清楚。我的代码似乎不起作用。以下是: 问题是最大限度地增加碎片数量,使总长度等于N Sample input: 5(total length) 5 3 2(individual pieces length) output: The answer could be 1(if you select 5) or 2(in the case of 3+2) 经过一番思考,我想到了这个: #includ

我认为这个问题是一个很好的初学者问题,可以用表格的方式来思考。我想我已经设法弄明白了要点,但仍然不是很清楚。我的代码似乎不起作用。以下是:

问题是最大限度地增加碎片数量,使总长度等于N

Sample input:
5(total length) 5 3 2(individual pieces length)
output:
The answer could be 1(if you select 5) or 2(in the case of 3+2)
经过一番思考,我想到了这个:

#include<iostream>
#include<algorithm>
using namespace std;


int main()
{
    int total_length, individual_lengths[3];
    cin >> total_length;
    for(int i=1;i<=3;i++)
        cin >> individual_lengths[i];


    int dp[total_length+1];
    dp[0]=0;

    for(int i=1;i<=total_length;i++)
    {
        for(int k=1;k<=3;k++)
            if(individual_lengths[k]<=i)
                dp[i]=max(dp[i-1], dp[i-individual_lengths[k]]+1);
    }
    cout << dp[total_length];
}
#包括
#包括
使用名称空间std;
int main()
{
int总长度,单个长度[3];
cin>>总长度;
对于(int i=1;i>单个_长度[i];
int dp[总长度+1];
dp[0]=0;
对于(inti=1;iEDIT**

假设len=13,a=2,b=4,c=5

for(int i=1;i<=len;i++)
{
    for(int k=1;k<=3;k++)
        if(a[k]<=i)
            dp[i]=max(dp[i-1], dp[i-a[k]]+1);
}
//i=1,k=1,2,3->skip
//i=2,k=1->dp[2]=max(dp[i-1],dp[i-a[k]+1])
//here is an issue!  dp[i-1] or dp[2-1] has not been assigned!

//so lets try if all dp values are initialized as 0, continueing from before
//i=2,k=1->dp[2]=max(0,0) //because dp[/*i-1*//*2-1*/1] = 0, and dp[/*1+i-a[k]*//*1+2-a[1]*//*3-2*/1] = 0
//i=2,k=2,3->skip
//i=3,k=1->.......
for(inti=1;idp[2]=max(0,0)//因为dp[/*i-1*/*2-1*/1]=0,而dp[/*1+i-a[k]*/*1+2-a[1]*/*3-2*/1]=0
//i=2,k=2,3->跳过
//i=3,k=1->。。。。。。。
从本质上讲,我可以告诉你,你只是在比较0。 ** 我会的

int count = static_cast<int>(len/a);
len%=a;
for (int sum = count*a; sum != len; sum-=a)
{
   if (!(sum+c<len || sum+b<len))
      count--;
   sum+=sum+c<len?c:sum+b<len?b:0;
}
int count=static\u cast(len/a);
len%=a;
对于(int sum=count*a;sum!=len;sum-=a)
{

如果(!(sum+cDid)您已经使用调试器了?哦,不!是因为匆忙键入而被否决了键入错误:/What's you's have have have not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not not但我的代码会打印垃圾值没有告诉我们你的程序是如何返回的。你的整个问题都被这些问题的模糊解释所淹没。你也应该真正考虑变量名。很难理解你所做的是因为通用变量名。@保尔克切尔,这无疑给了我一个教训,提高了问题I的质量。k、 谢谢..由于if条件,它将无法访问dp[-2]。我只选择在所考虑的长度小于或等于总长度时进行选择。你是对的;我的错!^^^我编辑了我的帖子以反映你的更正。谢谢你跟踪它。不过我需要一段时间来掌握你的代码。再次感谢!