#include <stdio.h>
#include <stdlib.h>
#define N 5
#define WEIGHT 10//背包容量
/*
2 6
2 3
6 5
5 4
4 6
测试用例
*/
void createPack(int *weight,int *value)
{
int i=0;
weight[0]=0;
value[0]=0;
printf("请输入背包的质量和价值:\n");
for(i=1;i<=N;i++)
{
scanf("%d%d",&weight[i],&value[i]);
}
}
int max(int a,int b)
{
return a>b ? a:b;
}
void knapsack(int *weight,int *value,int W,int c[N+1][WEIGHT+1])
{
int i,j;
for(i=0;i<=N;i++)
{
c[i][0]=0;
}
for(j=0;j<=W;j++)
{
c[0][j]=0;
}
for(i=1;i<=N;i++)
{
for(j=1;j<=W;j++)
{
if (j < weight[i])
{
c[i][j] = c[i-1][j];
}
else
{
c[i][j] = max(c[i-1][j],c[i-1][j-weight[i]] + value[i]);
}
}
}
}
void traceback(int C[N+1][WEIGHT+1],int weight[N+1])
{
int i=0,j=WEIGHT,x[N+1];
for(i=1;i<=N;i++)
{
x[i]=0;
}
for (i=N;i>=1;i--)
{
if (C[i][j] == C[i-1][j])
{
x[i] = 0 ;
}
else
{
x[i] = 1;
j -= weight[i];
}
}
printf("装入背包的方案为:\n将");
for(i=1;i<=N;i++)
{
if(x[i]==1)
{
printf("%d号 ",i);
}
}
printf("物品装入背包");
}
int main()
{
int weight[N+1];
int value[N+1];
int W=WEIGHT;
int c[N+1][W+1];
createPack(weight,value);
knapsack(weight,value,W,c);
printf("装入背包的物品的最大价值是%d\n",c[N][W]);
traceback(c,weight);
return 0;
}
0-1背包问题
最新推荐文章于 2022-05-08 19:08:01 发布