#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
#define N 100
#define M 1000
int T,n;
int w[N], v[N];
int f[N][M];
int path[N][M];
int main()
{
printf("Please input the volunme T of the bag and the number of things n\n");
printf("T = ");scanf("%d", &T);
printf("n = ");scanf("%d", &n);
printf("For each line, please input the volunme w_i and the value v_i of each things\n");
for (int i=1;i<=n;i++)
scanf("%d%d", &w[i], &v[i]);
for (int i=1;i<=n;i++)
for (int j=0;j<=T;j++)
{
f[i][j] = f[i-1][j];//不选第i件物品
if (j >= w[i] && f[i][j] < f[i-1][j-w[i]] + v[i])//如果第i件物品可以放入当前大小的背包,并且使得总价值更优
{
f[i][j] = f[i-1][j-w[i]] + v[i];//更新当前状态
path[i][j] = 1;//记录决策
}
}
printf("The exact optimal solution is: %d\n", f[n][T]);
printf("The solution is No.");
int i = n, j = T;
while (i > 0 && j > 0)
{
if (path[i][j])
{
printf("%d ", i);//输出决策
j -= w[i];
}
i--;
}
return 0;
}
01背包
最新推荐文章于 2024-01-01 19:23:13 发布