完全背包
Goods | capacity | weight |
A | 2 | 3 |
B | 1 | 2 |
C | 3 | 4 |
D | 2 | 2 |
问题:有n种物品,每种物品有无限个,每个物品的重量为weight[i],每个物品的价值为value[i].现在有一个背包,他所能容纳的重量为total,问:当你面对这么多有价值的物品时,你的背包所能带走的最大价值是多少?
| 0 | 1 | 2 | 3 | 4 | 5 |
A | 0 | 0 | 3 | 3 | 6 | 6 |
B | 0 | 2 | 4 | 6 | 8 | 10 |
C | 0 | 0 | 0 | 6 | 8 | 10 |
D | 0 | 0 | 2 | 6 | 8 | 10 |
改进代码:
使用一维数组:
#include <stdio.h>
#include <string.h>
int max(int a,int b){
if(a>b){
return a;
}
else{
return b;
}
}
int main(){
int goods,i,j,rad[100],value[100],weight[100],capacity,n;
printf("please imput the number of goods: \n");
scanf("%d",&goods);
printf("please imput the value and weight of each goods:\n");
for(i=1;i<=goods;i++){
scanf("%d%d",&weight[i],&value[i]);
}
scanf("%d",&capacity);
memset(rad,0,sizeof(rad));
for(j=1;j<=4;j++){
for(i=0;i<=capacity;i++){
if(i==0){
rad[i]=0;
printf("%d ",rad[i]);
}
else if(i<weight[j]){
printf("%d ",rad[i]);
}
else{
rad[i]=max(rad[i-weight[j]]+value[j],rad[i]);
printf("%d ",rad[i]);
}
}
printf("\n");
}
printf("%d\n",rad[capacity]);
return 0;
}