最后贴上代码吧,还是要多学习其他大神的代码,我的程序总是显得较为臃肿,当然啦,现在不是需要程序写的思路清晰嘛,希望我的程序让人看起来能够更好的理解。
#include<stdio.h>
#define NUM 120
enum Status{
IN,OUT
};
struct treasure{
int weight;
int value;
};
void PrintPath(enum Status flag[NUM][NUM],struct treasure trea[NUM],int graph[NUM][NUM] , int num , int bagWeight)
{
int i = num;//物品数目
int j = bagWeight;
int max = 0;
//找到最大价值
while(j > 0)
{
if(graph[num][max] < graph[num][j])
max= j;
j--;
}
printf("the max is %d\n",graph[num][max]);
j = max;
while(i> 0)
{
if(flag[i][j] == IN)
{
j-= trea[i].weight;
printf("theNO.%d is in\n",i);
}
--i;
}
}
void Start(struct treasure trea[NUM],int num)
{
int bagWeight;
int i,j,max;
int graph[NUM][NUM];
enum Status graph_stat[NUM][NUM];
printf("plsinput the bag weight\n");
scanf("%d",&bagWeight);
for(i = 0;i <= num;++ i)
for(j = 0;j <= bagWeight;++ j)
graph_stat[i][j]= OUT;
for(i = 0;i <= num;++i)
graph[i][0]= 0;
for(i = 0;i <= bagWeight;++ i)
graph[0][i]= 0;
for(i = 1;i <= num; ++i) //treasure
{
for(j = 1;j <= bagWeight; ++j) //bag
{
if((trea[i].weight <= j)&&(graph[i-1][j] <= graph[i-1][j -trea[i].weight] + trea[i].value))
{
graph[i][j]= graph[i - 1][j - trea[i].weight] + trea[i].value;
graph_stat[i][j]= IN;
}
else
{
graph[i][j]= graph[i-1][j];
graph_stat[i][j]= OUT;
}
}
}
PrintPath(graph_stat,trea,graph,num,bagWeight);
}
int main()
{
int n = 0;
struct treasure trearr[NUM];
printf("pls input the weight and value until all the content in\n");
for(n = 1;scanf("%d%d",&trearr[n].weight,&trearr[n].value) != EOF;++ n);
Start(trearr,--n);
return 0;
}