问题描述
我是 C++ 新手,刚从 python 转过来并尝试动态编程。 写了一段基本的“0-1背包”问题的代码,测试一下我对动态规划的基本理解。
我想我的算法是正确的,但是由于某种原因,当我要求用户输入两个数组的输入时,我得到了错误的答案,但是当我在代码中输入这些数组的值时,我每次都能得到正确答案。
出了什么问题/出了什么问题?
编辑:dp 是一个填充 -1 的 1001*10001 二维向量
我的求解器功能:
int knap(int n,int wt[],int price[],int W){ // n = number of items; size of array,w = wt available in knapsack
// wt stores weight if items,price:price
if(dp[n][W] != -1){
return dp[n][W];
}
else{
// base case
if(n == 0 || W == 0){
return 0;
}
if(wt[n-1] <= W){ // condition for adding item to knapsack (wt of item must be less than space remaining in knapsack)
return dp[n][W] = max((price[n-1] + knap(n-1,wt,price,W - wt[n-1])),knap(n-1,W)) ; // max wrt recursion from prevIoUs element
}
else{
return dp[n][W] = knap(n-1,W);
}
}
}
我的主要功能:
int main(){
int n,W;
cin>>n>>W;
/*int b[n],b[n];
for(int i = 0; i<n; i++)
cin>>a[i];
for(int j = 0; j<n; j++)
cin>>b[j];
*/
int a[] = { 1,2,10,6,5,1,7,4,4},b[] = { 6,3,8,6};
cout<<knap(n,a,b,W);
}
答案应该是 21,这是我在定义 a[] 和 b[] 时得到的,但是当我让用户输入 a[] 和 b[](如代码的注释区域中所写) ) 值,我得到了错误的答案。
示例输入测试用例及其输出:
Input:
10 10
1 2 10 6 5 1 7 4 10 4
6 3 8 1 7 3 8 6 5 6
output:
21
Input:
4 10
4 8 5 3
5 12 8 1
Output:
13
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)