这题可以想到用 01 背包,但是如果是 01 背包的话无法保证方案最优因为加入某一个元素是不能知道放在已有箱子的哪里是最优的。那么我们就可以先找出最优的从上往下顺序后再 01 背包。
因为交换相邻两个箱子只有对自身产生影响,所以可以贪心地考虑这两个箱子如何摆最优,而又因为本身上面的总重量不变,所以只用考虑这两个箱子的限制:一上一下的 , 在上面还可放 , 在上可放 ,显然若 则 在上,否则 在上,移项一下得 则 在上,于是按 升序排序,然后每次都把箱子放在最下方即可。
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1005;
const int M = 1e5 + 5;
struct node {
int w, v, s;
}a[N];
//s[x] - w[y] < s[y] - w[x]
//s[x] + w[x] < s[y] + w[y]
bool cmp(node x, node y) {
return x.s + x.w < y.s + y.w;
}
int dp[M];
signed main() {
int n, cnt = 0;
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i].w >> a[i].s >> a[i].v;
sort(a + 1, a + 1 + n, cmp);
for (int i = 1; i <= n; i++)
for (int j = a[i].w + a[i].s; j >= a[i].w; j--)
dp[j] = max(dp[j], dp[j - a[i].w] + a[i].v);
int ans = 0;
for (int i = 0; i < M; i++)
ans = max(ans, dp[i]);
cout << ans;
return 0;
}
``