HDU Problem 2546 饭卡【01背包】

饭卡

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 23257    Accepted Submission(s): 8171

Problem Description
电子科大本部食堂的饭卡有一种很诡异的设计,即在购买之前判断余额。如果购买一个商品之前,卡上的剩余金额大于或等于5元,就一定可以购买成功(即使购买后卡上余额为负),否则无法购买(即使金额足够)。所以大家都希望尽量使卡上的余额最少。
某天,食堂中有n种菜出售,每种菜可购买一次。已知每种菜的价格以及卡上的余额,问最少可使卡上的余额为多少。
 
Input
多组数据。对于每组数据:
第一行为正整数n,表示菜的数量。n<=1000。
第二行包括n个正整数,表示每种菜的价格。价格不超过50。
第三行包括一个正整数m,表示卡上的余额。m<=1000。

n=0表示数据结束。
 
Output
对于每组输入,输出一行,包含一个整数,表示卡上可能的最小余额。
 
Sample Input
1 50 5 10 1 2 3 2 1 1 2 3 2 1 50 0
 
Sample Output
-45 32
 
Source
 
Recommend
lcy   |   We have carefully selected several similar problems for you:  2955 1203 2159 2191 1114 
 
思路:
我们可以先在金额中减去5元,让它用来买最贵的菜。剩下的就变成了01背包问题了,就是用一定的金额购买最大的价值。因为剩下的5元购买最大值,这样也就避免了出现负值的情况。 dp[i]中存放的是已经花掉的价值,i表示剩下的价值。状态转移方程为dp[j] = max(dp[j - ar[i]] + ar[i], dp[j])。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 2000 + 10;
const int INF = 0x3f3f3f3f;
int M, n, dp[MAXN], price[MAXN];
int main() {
    while (scanf("%d", &n), n) {
        int maxx = 0, pos;
        for (int i = 1; i <= n; i++) {
            scanf("%d", &price[i]);
            if (maxx < price[i]) {
                maxx = price[i]; pos = i;
            }
        }
        scanf("%d", &M); M -= 5;
        if (M < 0) {printf("%d
", M + 5); continue;}
        memset(dp, 0, sizeof(dp));
        for (int i = 1; i <= n; i++) {
            if (pos == i) continue;
            for (int j = M; j >= price[i]; j--) {
                dp[j] = max(dp[j - price[i]] + price[i], dp[j]);
            }
        }
        printf("%d
", M  + 5 - dp[M] - maxx);
    }
    return 0;
}
 
 
原文地址:https://www.cnblogs.com/cniwoq/p/6770829.html