# 分组背包问题：不超过N元钱

https://nanti.jisuanke.com/t/256

#### 样例输入

1000 5
800 2 0
400 5 1
300 5 1
400 3 0
500 2 0


#### 样例输出

2200

struct Item
{
int cost;
int impo;
int mid;
int plu1 = 0;
int plu2 = 0;
};

1、只购买主件，花费为a[i].cost

2、购买主件和附件1，花费为a[i].cost+a[a[i].plu1].cost

3、购买主件和附件2，花费为a[i].cost+a[a[i].plu2].cost

4、购买主件和附件1、2，花费为a[i].cost+a[a[i].plu1].cost+a[a[i].plu2].cost

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Item
{
int cost;
int impo;
int mid;
int plu1 = 0;
int plu2 = 0;
};

int main()
{
int i, j, n, m, id, p1, p2, cost, p1cost, p2cost, val, p1val, p2val;
cin >> n >> m;
vector<Item> a(m + 1);
vector<int> dp(n + 1, 0);
//处理输入
for (i = 1; i <= m; ++i)
{
cin >> a[i].cost >> a[i].impo >> a[i].mid;
id = a[i].mid;
if (id > 0)
{
a[id].plu2 = a[id].plu1;
a[id].plu1 = i;
}
}
for (i = 1; i <= m; ++i)
{
cost = a[i].cost;
val = a[i].impo*cost;

for (j = n; j >= cost; --j)
{
if (a[i].mid > 0)
break;

//附件信息
p1 = a[i].plu1;
p1cost = a[p1].cost;
p1val = p1cost*a[p1].impo;
p2 = a[i].plu2;
p2cost = a[p2].cost;
p2val = p2cost*a[p2].impo;

//主件
dp[j] = max(dp[j], dp[j - cost] + val);

//附件1
if (p1 > 0 && j - cost - p1cost >= 0)
dp[j] = max(dp[j], dp[j - cost - p1cost] + val + p1val);

//附件2
if (p2 > 0 && j - cost - p2cost >= 0)
dp[j] = max(dp[j], dp[j - cost - p2cost] + val + p2val);

//附件1+2
if (p1*p2 > 0 && j - cost - p1cost - p2cost >= 0)
dp[j] = max(dp[j], dp[j - cost - p1cost - p2cost] + val + p1val + p2val);
}
}
cout << dp[n] << endl;
return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：分组背包问题：不超过N元钱 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)