Rav*_*rma 2 c arrays dynamic knapsack-problem
该代码是针对 0/1 背包问题的递归动态规划。所以让我首先说代码似乎是正确的,因为当我运行它时,它会显示结果,但前提是我取消注释该printf行(请参阅突出显示的部分)并且它与解决方案无关(我仅将其用于测试目的),我觉得这很奇怪。有人可以告诉我为什么会这样。
int main() {
int DP_Recursive(int W, static int wt[], static int val[], int n, static int dp[][]);
static int wt[5] = { 5, 10, 20, 30 };
static int val[5] = { 50, 60, 100, 120 };
static int dp[5][60]; //marker 2-D array
for (int i = 0; i <= 5; i++) {
for (int w = 0; w <= 50; w++) {
dp[i][w] = -1;
}
}
printf("The total loot is %d$.", DP_Recursive(50, wt, val, 2, dp));
}
//Recursive D.P. solution
int DP_Recursive(int W, static int wt[], static int val[], int n, static int dp[5][60]) {
//-------**HIGHLIGHTED PART**-----------
printf("%d", dp[2][30]);
//--------------------------
//Base case
if (n == 0 || W == 0)
return 0;
if (dp[n][W] != -1)
return dp[n][W];
if (wt[n-1] > W) {
dp[n][W] = DP_Recursive(W, wt, val, n - 1, dp);
return dp[n][W];
} else {
dp[n][W] = max(val[n-1] + DP_Recursive(W - wt[n-1], wt, val, n-1, dp),
DP_Recursive(W, wt, val, n-1, dp));
}
return dp[n][W];
}
Run Code Online (Sandbox Code Playgroud)
代码中有多个问题:
[主要] for 的原型DP_recursive不正确:用于int DP_Recursive(int W, int wt[], int val[], int n, static int dp[5][60])函数之前的main()函数声明(在 的主体之外main)和函数定义本身。
[次要] 中的数组main()不需要声明static。
[主要]初始化循环跑得太远了:for (int i = 0; i <= 5; i++)迭代 6 次,i范围从0到5包含。您应该在两个循环中使用<而不是<=。根据经验,在使用之前总是检查两次<=,并且总是喜欢排除的上限。
[主要]内部初始化循环使用50而不是60作为上限,导致数组被部分初始化并导致不正确(未定义的行为)而不是110。最好使用countof宏来获取数组中的元素数。
[次要]您应该以换行符 ( \n)结束输出
[未成年人] main()应0在成功终止后返回。
您没有发布 的定义max,建议将其定义为函数。
包含文件<stdio.h>也丢失了。
这是一个修改后的版本:
#include <stdio.h>
int DP_Recursive(int W, int wt[], int val[], int n, int dp[5][60]);
int max(int a, int b) {
return a < b ? b : a;
}
#define countof(a) (sizeof(a) / sizeof((a)[0])) // number of elements in an array
int main() {
int wt[5] = { 5, 10, 20, 30 };
int val[5] = { 50, 60, 100, 120 };
int dp[5][60]; //marker 2-D array
for (size_t i = 0; i < countof(dp); i++) {
for (size_t w = 0; w < countof(dp[i]); w++) {
dp[i][w] = -1;
}
}
printf("The total loot is %d$.\n", DP_Recursive(50, wt, val, 2, dp));
return 0;
}
//Recursive D.P. solution
int DP_Recursive(int W, int wt[], int val[], int n, int dp[5][60]) {
//-------**HIGHLIGHTED PART**-----------
printf("%d ", dp[2][30]);
//--------------------------
//Base case
if (n == 0 || W == 0)
return 0;
if (dp[n][W] != -1)
return dp[n][W];
if (wt[n-1] > W) {
dp[n][W] = DP_Recursive(W, wt, val, n - 1, dp);
return dp[n][W];
} else {
dp[n][W] = max(val[n-1] + DP_Recursive(W - wt[n-1], wt, val, n-1, dp),
DP_Recursive(W, wt, val, n-1, dp));
}
return dp[n][W];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |