LuoguP2224 产品加工
johnsmith0x3f · · 题解
0x01
考虑 DP,朴素的想法是设
但这种做法的时间复杂度是
注意到
时空复杂度均为
0x02
然而提交后我们发现 TLE on test 7,考虑进一步优化时间。
注意到
又注意到随着
最后,转移时的 if 运算可以改成三目运算符,效率更高,详见这篇博客。
0x03 Code
#include <bits/stdc++.h>
using namespace std;
inline int read(){
int x = 0, f = 1; char c = getchar();
while(isdigit(c)^1) f &= (c!=45), c = getchar();
while(isdigit(c)) x = (x<<1) + (x<<3) + (c^48), c = getchar();
return f ? x : -x;
}
const int inf = 0x3f3f3f3f;
int n, ans = inf, sum, down, f[2][30005];
int main(){
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
#endif
n = read(), memset(f, 0x3f, sizeof(f)), f[0][0] = 0;
for(int i=1, x, y, z, las=0, now=1; i<=n; ++i, las^=1, now^=1){
x = read(), y = read(), z = read(), sum += max(max(x, y), z), memset(f[now], 0x3f, sizeof(f[now]));
for(int j=down; j<=sum; ++j)
f[now][j] = min(min(min(f[now][j], y?(f[las][j]+y):inf), (x && j>=x)?f[las][j-x]:inf), (z && j>=z)?(f[las][j-z]+z):inf);
while(f[now][down]>=inf) ++down;
}
for(int i=0; i<=sum; ++i) ans = min(ans, max(f[n&1][i], i));
printf("%d\n", ans);
return 0;
}