xtuoj 1436 礼物(01背包板子题

礼物

Submit Code ] [ Top 20 Runs ] [ Runs Status ]
Acceteped : 75Submit : 281
Time Limit : 1000 MSMemory Limit : 65536 KB

Description

题目描述

马上要“六一”儿童节了,女儿吵着让爸爸买礼物。可女儿要买的东西实在太多了,爸爸手头上只有M元钱,觉得可能不能全部满足她,但是他又希望女儿尽量开开心心的。爸爸看了女儿的礼物单,上面有N件礼物,查到了所有礼物的价格,以及买给她会女儿开心度增加的值和不买给她开心度减少的值(每种礼物只能买1个)。他想知道开心度最大是多少,希望你能帮帮他。

输入

存在多组测试数据
每组数据的第一行是两个整数N(1 ≤ N ≤ 16),M(1 ≤ M ≤ 1,000)。如果N和M为0,表示输入结束。
以后的N行,每行为一个礼物的价格P(1 ≤ P ≤ 200),买增加的开心度I(1 ≤ I ≤ 50),不买减少的开心度D(1 ≤ D ≤ 50)。

输出

每个样例输出1行,为最大的开心度。

样例输入

3 100
30 10 5
80 20 16
60 15 7
3 100
30 10 5
70 20 16
60 15 6
0 0

样例输出

9
24

01背包板子题 

#include<iostream>
#include<string.h>
using namespace std;
typedef struct {
	int price;
	int happy;
	int unhappy;
} giftunit;
int dp[18][1005];
giftunit gifts[19];
int main() {
	int m, n, i, j, ans;
	while (cin >> n >> m && (n || m)) {
		ans = -0x3f3f3f3f;//注意有可能什么也买不起,非常不满意!!!
		for (i = 1; i <= n; i++) {
			cin >> gifts[i].price >> gifts[i].happy >> gifts[i].unhappy;
		}
		for (i = 1; i <= n; i++) {
			for (j = 0; j <= m; j++) {
				if (j < gifts[i].price) dp[i][j] = dp[i - 1][j] - gifts[i].unhappy;
				else dp[i][j] = max(dp[i - 1][j - gifts[i].price] + gifts[i].happy, dp[i - 1][j] - gifts[i].unhappy);
			}
		}
		for (i = 0; i <= m; i++) {
			ans = max(ans, dp[n][i]);
		}
		cout << ans <<  endl;
		memset(dp, 0, sizeof dp);
		memset(gifts, 0, sizeof gifts);
	}
}

应室友要求加了一个深搜

#include<iostream>
using namespace std;
int maxhappy, n, price[17], hap[17], unhap[17], money;
void dfs(int deep, int happy, int cost) {
	if (cost > money) return;
	if (deep == n) {
		maxhappy = (maxhappy > happy) ? maxhappy : happy;
	} else {
		dfs(deep + 1, happy + hap[deep], cost + price[deep]);
		dfs(deep + 1, happy - unhap[deep], cost);
	}
}
int main() {
	cin.tie(0);
	cout.tie(0);
	ios::sync_with_stdio(false);
	int i;
	while (	cin >> n >> money && (n || money)) {

		for (i = 0; i < n; i++) {
			cin >> price[i] >> hap[i] >> unhap[i];
		}
		maxhappy = -0x3f3f3f3f;
		dfs(0, 0, 0);
		cout << maxhappy << endl;
	}
}//Accepted	1508 KB	108 MS

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值