POJ 2392题目大意如下:
FJ的牛想上天,但是要借助梯子,现在有K种梯子,由于会收到宇宙射线的影响,所以每种梯子限定了能够到达的最大高度。给出K种梯子的单位长度、数量、以及允许到达的最大高度。现在要求给出一个最优方案,使得使用这K种梯子到达最大高度。
还是DP,定义dp[i][j]:表示使用前i+1种梯子是否能够到达高度j。
之前自己都没有意识到这是一个多重背包问题,所以写了个比较烂的方法,也就是每次对第i种梯子的考虑都要考虑之前的所有情况,代码如下:Accept 728K / 532MS
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int max1 = 401;
const int max2 = 40001;
struct Dat{
int h, a, c;
}Lift[max1];
int K;
bool dp[max2];
bool camp(const Dat& lhs, const Dat& rhs) {
return lhs.a < rhs.a;
}
void solve() {
int ans = 0;
sort(Lift, Lift + K, camp);
for (int i = 0; i <= Lift[0].c; i++) {
if (i*Lift[0].h > Lift[0].a) break;
dp[i*Lift[0].h] = true;
ans = i*Lift[0].h;
}
for (int i = 1; i < K; i++) {
int temp = ans, j = Lift[i].c, H = Lift[i].h, M = Lift[i].a;
while (temp >= 0) {
if (dp[temp]) {
int cur = temp;
for (int k = 0; k <= j; k++) {
if (cur > M) break;
dp[cur] = true;
ans = max(ans, cur);
cur += H;
}
}
temp--;
}
}
printf("%d\n", ans);
}
int main() {
scanf("%d", &K);
for (int i = 0; i < K; i++) scanf("%d %d %d", &Lift[i].h, &Lift[i].a, &Lift[i].c);
solve();
return 0;
}
发现是多重背包问题,发现第一次提交的代码中的k其实可以不需要,直接用:
if (!dp[i - 1][j] && dp[i - 1][j - h[i]] && use < total[i]) {
dp[i][j] = true;
use++;
ans = max(ans, j);
}
代码如下: Accept 884K / 94MS
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
const int max1 = 401;
const int max2 = 40001;
struct Dat{
int h, a, c;
}Lift[max1];
int K;
int sum[max2];
bool dp[max2];
bool camp(const Dat& lhs, const Dat& rhs) {
return lhs.a < rhs.a;
}
void solve() {
int ans = 0;
dp[0] = true;
sort(Lift, Lift + K, camp);
for (int i = 0; i < K; i++) {
int H = Lift[i].h, M = Lift[i].a, C = Lift[i].c;
memset(sum, 0, sizeof(sum));
for (int j = H; j <= M; j++) {
if (!dp[j] && dp[j - H] && sum[j - H] < C) {
dp[j] = true;
sum[j] = sum[j - H] + 1;
ans = max(ans, j);
}
}
}
printf("%d\n", ans);
}
int main() {
scanf("%d", &K);
for (int i = 0; i < K; i++) scanf("%d %d %d", &Lift[i].h, &Lift[i].a, &Lift[i].c);
solve();
return 0;
}
倒也着实体验了一把没有优化和优化在时间上的差别。