原题链接:https://vjudge.net/problem/UVA-12099
分类:动态规划
备注:状态优化,类似0-1背包
#include <bits/stdc++.h>
using namespace std;
const int N = 70 + 5;
const int INF = 0x3f3f3f3f;
int t, n, d[N * 30][N * 30], sum[N];
struct Book {
int h, t;
bool operator < (const Book& rhs) const {
return h > rhs.h;
}
}b[N];
int f(int a, int b) {
return a == 0 ? b : 0;
}
int main(void) {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d%d", &b[i].h, &b[i].t);
sum[i] = sum[i - 1] + b[i].t;
}
int m = sum[n];
sort(b + 1, b + 1 + n);
int ans = INF;
for (int j = 0; j <= m; j++)
for (int k = 0; k + j <= m; k++)
d[j][k] = INF;
d[0][0] = 0;
for (int i = 2; i <= n; i++) {
for (int j = min(sum[i - 1] + 30, m); j >= 0; j--) {
for (int k = min(m - j, j + 30); k >= 0; k--) {
if ((j > b[i].t || (j == b[i].t && k == 0)) && d[j - b[i].t][k] != INF)
d[j][k] = min(d[j][k], d[j - b[i].t][k] + f(j - b[i].t, b[i].h));
if (j > 0 && k >= b[i].t && d[j][k - b[i].t] != INF)
d[j][k] = min(d[j][k], d[j][k - b[i].t] + f(k - b[i].t, b[i].h));
}
}
}
for (int j = 1; j <= m; j++)
for (int k = 1; k + j <= m; k++)
if (d[j][k] != INF)
ans = min(ans, max(m - j - k, max(j, k)) * (b[1].h + d[j][k]));
printf("%d\n", ans);
}
return 0;
}