礼物 | ||
[ Submit Code ] [ Top 20 Runs ] [ Runs Status ] | ||
Acceteped : 75 | Submit : 281 | |
Time Limit : 1000 MS | Memory Limit : 65536 KB | |
Description | ||
题目描述 马上要“六一”儿童节了,女儿吵着让爸爸买礼物。可女儿要买的东西实在太多了,爸爸手头上只有M元钱,觉得可能不能全部满足她,但是他又希望女儿尽量开开心心的。爸爸看了女儿的礼物单,上面有N件礼物,查到了所有礼物的价格,以及买给她会女儿开心度增加的值和不买给她开心度减少的值(每种礼物只能买1个)。他想知道开心度最大是多少,希望你能帮帮他。 输入 存在多组测试数据 输出 每个样例输出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