多重背包-POJ 2392 Space Elevator

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;
}

倒也着实体验了一把没有优化和优化在时间上的差别。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值