0/1背包问题的c语言实现,附上测试数据 /* *时间:2010-05-13 *作者:heroyan *邮箱:zndxysf@126.com *QQ:357351104 *功能:求0/1背包问题,求得最大值和其对应的物品列表 */ /* in 100 5 77 92 22 22 29 87 50 46 99 90 out 133 200 8 79 83 58 14 86 54 11 79 28 72 62 52 15 48 68 62 out 334 */ #include "stdio.h" int n = 8;//物品数量 int w[] = {0,79,58,86,11,28,62,15,68};//物品重量 int p[] = {0,83,14,54,79,72,52,48,62};//物品价格 int m = 200;//背包容量 int cost[201][201]; void init(); void package() { int i,j; init(); for(i = 1; i <= n; ++i) { for(j = 1; j <= m; ++j) { if(w[i] > j) { cost[i][j] = cost[i-1][j]; } else { if(cost[i-1][j] < cost[i-1][j-w[i]] + p[i]) { cost[i][j] = cost[i-1][j-w[i]] + p[i]; } else { cost[i][j] = cost[i-1][j]; } } } } } void init() { int i; for(i = 0; i <= n; ++i) { cost[i][0] = 0; } for(i = 0; i <= m; ++i) { cost[0][m] = 0; } } //打印结果 void print() { int i,ii; printf("%d/nList:",cost[n][m]); ii = m; for(i = n; i > 0; --i) { if(cost[i][ii] > cost[i-1][ii]) { printf("%d ", i); ii -= w[i]; } } } void main() { package(); print(); }