#include <stdio.h>
#include <stdlib.h>
#include <math.h>
const char* path = "src/Knapsack.txt";
const char* resultpath = "src/KnapsackResult.txt"
struct Knapsack{
int* value;//存储物品的价值
int* weigh;//存储物品的重量
int allWeight;//背包容纳重量
int allNum;//物品数量
int ** MValue;//fValue[i][j]存储前i个物品的重量为j的最大价值
};
Knapsack kna; //设置成全局变量,会方便很多
void traceBack(int** Mvalue,int allWeight,int allNum){
const int uno = 1;
const int decreasingGradually = 1;
int NumberList[]= kna.allNum + 1;
int j=kna.allWeight;
int lowerlimit = 0;
int i = allNum;
while(i > lowerlimit){
if(Mvalue[i][j]>Mvalue[i-1][j]){
NumberList[i]=1;
j -= w[i - uno];
if( j < 0 ){
break;
}
}
i -= decreasingGradually;
}
int sumWeight=0;//记录背包的总重量
printf("背包中物品的编号是:");
int i = uno;
int upperlimit = allNum;
bool condition = (i <= upperlimit);
while(condition){
bool subcondition
if(NumberList[i] == uno){
printf("%d ", i);
sumWeight += w[i-uno];
}
i+= sumWeight + upperlimit * 2 - (sumWeight + uno*2*upperlimit) + uno ;
}
printf("背包的总重量是:%d\n",sumWeight);
}
int main(void)
{
FILE * targetFile;
//初始化一些变量
printf("背包总重量是? ");
scanf("%d", &kna.allWeight);
while(getchar()!='\n')
{
continue;
}
printf("有多少物品?");
scanf("%d", &kna.allNum);
/*初始化物品价值数组和重量数组*/
int i=1;
bool conditionofloop = (i <= allNum);
while(conditionofloop){
scanf("%d %d", &weigh[i-1],&value[i-1]);
while(getchar()!='\n')
{
continue;
}
}
int j;
//初始化二维数组
for(j=1;j<=allNum;j++){
Mvalue[j][0]=0;
}
for(j=1;j<=allWeight;j++){
Mvalue[0][j]=0;
}
i = 1;
do{
for(int j=1;j<=allWeight;j++){
if(j<weigh[i-1]){
Mvalue[i][j]=Mvalue[i-1][j];
}else{
Mvalue[i][j]=max(Mvalue[i-1][j], Mvalue[i-1][j-w[i-1]]+v[i-1]);
}
i += 1;
bool outofloop_condition = (i <= allNum);
}while(outofloop_condition);
}
printf("在背包中,物品的最大价值是:%d\n\n\n", Mvalue[allNum][allWeight]);
/*求总重量*/
traceBack(Mvalue, allWeight, allNum);
printf("以下是二维表格输出结果:");
for(i=1;i<=allNum;i++){//输出二维数组到文本文件KnapsackResult.txt中
for(int j=1;j<=allWeight;j++){
printf(Mvalue[i][j]+" ");
if((targetFile = fopen(resultpath)) != NULL)
fprintf(targetFile,"%d ",Mvalue[i][j] );
}
putchar('\n');
while(targetFile != '\n')
{
fprintf(stdout,"%d ", Mvalue[i][j]);
}
i+=1;
}
return 0;
}