//举例:4个物品,背包容量为5,每个物品属性(2,3) (1,2)(3,4)(2,2)
//输入示例:4 5 2 3 1 2 3 4 2 2
//输出结果为7
#include <iostream>
#include <vector>
using namespace std;
int max(int a, int b)
{
if (a > b)
{
return a;
}
return b;
}
int main()
{
int n, m, i0,i1, i2;
cin >> n >> m;
vector<vector<int> > actor(n);
vector<vector<int> > money(n);
for (int i = 0; i < n; i++)
{
actor[i].resize(2);
money[i].resize(m+1);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
cin >> actor[i][j];
}
}
for (int i = 0; i <=m; i++)
{
if (actor[0][0] <= i)
{
money[0][i] = actor[0][1];
}
else
{
money[0][i] = 0;
}
}
for (int i = 1; i < n; i++)
{
for (int j = 0; j <= m; j++)
{
if (actor[i][0] <= j)
{
i0=j - actor[i][0];
if(i0>=0)
{
i1 = actor[i][1] + money[i - 1][j - actor[i][0]];
i2 = money[i - 1][j];
money[i][j] = max(i1, i2);
}
else
{
money[i][j] =money[i - 1][j];
}
}
else
{
money[i][j] = money[i - 1][j];
}
}
}
cout<<money[n-1][m];
return 0;
}
dp背包问题:将n个物品放进背包里,背包容量为m,物品具有重量和价值两个属性,要求背包所放物品的价值最大,物品不可被切割
最新推荐文章于 2024-09-18 22:01:06 发布