for(j=1;j
{
//w[i]>j,第i个物品不装入背包
value[i][j]=value[i-1][j];
//w[i]<=j,且第i个物品装入背包后的价值>value[i-1][j],则记录当前最大价值
int temp=value[i-1][j-w[i]]+v[i];
if(w[i]<=j && temp>value[i][j])
value[i][j]=temp;
}
}
//逆推求装入的物品
j=m;
for(i=row-1;i>0;i--)
{
if(value[i][j]>value[i-1][j])
{
c[i]=1;
j-=w[i];
}
}
//记录最大价值
int nMaxVlaue=value[row-1][col-1];
//释放该二维数组
for(i=0;i
{
delete [col]value[i];
value[i]=NULL;
}
delete[] value;
value=NULL;
return nMaxVlaue;
}
int CBeibao::GetMaxValue()
{
int nValue=GetMaxValue(m_nNumber,m_nMaxWeight,m_pWeight,m_pValue,m_pCount);
m_nMaxValue=nValue;
return nValue;
}
//显示结果
void CBeibao::Display(int nMaxValue)
{
printf(" %d ",nMaxValue);
for(int i=1;i<=m_nNumber;i++)
{
if(m_pCount[i])
printf(" %d %d ",i,m_pCount[i]);
}
printf(" ");
}
void CBeibao::Display(int nMaxValue,const char *filename)
{
FILE *fp=fopen(filename,"w");
if(fp==NULL)
{
printf("can not write file!");
return; //exit(0);
}
fprintf(fp,"%d ",nMaxValue);
for(int i=1;i<=m_nNumber;i++)
{
if(m_pCount[i])
fprintf(fp,"%d %d ",i,m_pCount[i]);
}
fclose(fp);
}
//显示菜单
void show_menu()
{
printf("--------------------------------------------- ");
printf("input command to test the program ");
printf(" i or I : input filename to test ");
printf(" q or Q : quit ");
printf("--------------------------------------------- ");
printf("$ input command >");
}
void main()
{
char sinput[10];
char sfilename[FILENAMELENGTH];
show_menu();
scanf("%s",sinput);
while(stricmp(sinput,"q")!=0)
{
if(stricmp(sinput,"i")==0)
{
printf(" please input a filename:");
scanf("%s",sfilename);
//获取满足最大载重量的最大价值
CBeibao beibao(sfilename);
int nMaxValue=beibao.GetMaxValue();
if(nMaxValue)
{
beibao.Display(nMaxValue);
int nlen=strlen(sfilename);
strcpy(sfilename+nlen-4,"_result.txt");
beibao.Display(nMaxValue,sfilename);
}
else
printf(" error! please check the input data! ");
}
//输入命令
printf("$ input command >");
scanf("%s",sinput);
}
}
5. 运行结果如下
文件中的内容如下:
1. input.txt
4 10
2 3 4 7
1 3 5 9
input_result.txt
12
2 1
4 1
2. input1.txt
5 10
2 2 6 5 4
6 3 5 4 6
input1_result.txt
15
1 1
2 1
5 1
3. input2.txt
5 15
2 6 4 7 9
1 6 5 9 4
input2_result.txt
16
1 1
2 1
4 1
4. input3.txt
10 105
12 16 24 7 29 32 5 43 31 1
11 16 15 9 24 25 3 32 41 7
input3_result.txt
112
1 1
2 1
4 1
6 1
7 1
9 1
10 1