完全背包
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][100],value[100],weight[100],capacity;
memset(rad,0,sizeof(rad));
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);
for(i=1;i<=goods;i++){
for(j=0;j<=capacity;j++){
if(j==0){
rad[i][j]=0;
}
else if(j<weight[i]){
continue;
}
else{
rad[i][j]=max(rad[i][j-weight[i]]+value[i],rad[i-1][j]);
}
}
}
for(i=1;i<=goods;i++){
for(j=0;j<=capacity;j++){
printf("%d ",rad[i][j]);
}
printf("\n");
}
printf("%d\n",rad[goods][capacity]);
return 0;
}