首页 > 技术文章 > 饭卡 (01背包)

-Ackerman 2020-02-02 19:11 原文

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2546

 

问题描述:

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

 

 

解法:

首先明显知道每一次的决策都会对后面的结果造成影响,所以很容易想到这是一个 DP 问题

然后每个物品只能取一次 ,那么会往 01背包上去考虑

首先最大的那个物品我们肯定是希望可以直接减掉的(因为这样可以保证最小)

那么我们先进行排序

然后现在的问题就变成了:如何从前 n-1 个物品里面选出体积为m-5的最大价值 x

然后用m-x-a[n] 就是最后答案

 

#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <map>
#include <stack>
#include <set>
#include <queue>
#include <math.h>
#include <cstdio>
#include <iomanip>
#include <time.h>

#define LL long long
#define INF 0x3f3f3f3f
#define ls nod<<1
#define rs (nod<<1)+1
#define cin std::cin
#define cout std::cout
#define endl std::endl;

const int maxn = 1e5 + 10;

int n,m;
int dp[1010],w[1010];

int main() {
    while (cin >> n) {
        if (n == 0)
            break;
        for (int i = 1;i <= n;i++) {
            cin >> w[i];
        }
        cin >> m;
        if (m < 5) {
            cout << m << endl;
            continue;
        }
        memset(dp,0, sizeof(dp));
        std::sort(w+1,w+1+n);
        for (int i = 1;i < n;i++) {
            for (int j = m-5;j >= w[i];j--)
                dp[j] = std::max(dp[j],dp[j-w[i]]+w[i]);
        }
        printf("%d\n",m-dp[m-5]-w[n]);
    }
    return 0;
}

 

推荐阅读