AcWing 7. 混合背包问题
原题链接
中等
作者:
yxc的小迷妹
,
2023-07-17 09:49:02
,
所有人可见
,
阅读 263
#include <iostream>
#include <cstring>
using namespace std;
const int N = 20010;
int n, m;
int f[N], g[N], q[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++)
{
int v, w, s;
cin >> v >> w >> s;
if (s == -1) s = 1;
if (s == 0) s = 1e6;
memcpy(g, f, sizeof f);
for (int j = 0; j < v; j ++)
{
int hh = 0, tt = -1;
for (int k = j; k <= m; k += v)
{
if (hh <= tt && q[hh] < k - s * v) hh ++ ;
if (hh <= tt) f[k] = max(f[k], g[q[hh]] + (k - q[hh]) / v * w);
while (hh <= tt && g[q[tt]] - (q[tt] - j) / v * w <= g[k] - (k - j) / v * w) tt -- ;
q[ ++ tt] = k;
}
}
}
cout << f[m] << '\n';
return 0;
}
#include <iostream>
using namespace std;
const int N = 1010;
int f[N];
int main()
{
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i ++)
{
int v, w, s;
cin >> v >> w >> s;
if (!s)
{
for (int j = v; j <= m; j ++)
f[j] = max(f[j], f[j - v] + w);
}
else
{
s = abs(s);
for (int k = 1; k <= s; k <<= 1)
{
for (int j = m; j >= v * k; j --)
f[j] = max(f[j], f[j - k * v] + k * w);
s -= k;
}
if (s)
for (int j = m; j >= v * s; j --)
f[j] = max(f[j], f[j - s * v] + s * w);
}
}
cout << f[m];
return 0;
}