HDU 2546 饭卡

来源:互联网 发布:个人博客 php 源码 编辑:程序博客网 时间:2024/06/05 20:57

http://acm.hdu.edu.cn/showproblem.php?pid=2546

题意:

如果购买一个商品之前,卡上的剩余金额大于或等于5元,就一定可以购买成功(即使购买后卡上余额为负),否则无法购买(即使金额足够)。所以大家都希望尽量使卡上的余额最少。某天,食堂中有n种菜出售,每种菜可购买一次。已知每种菜的价格以及卡上的余额,问最少可使卡上的余额为多少。

分析:

要使卡上的余额最少,相当于用有限的金额去买最多的菜。而题目多了一个限制条件,就是“卡上的剩余金额大于或等于5元,就一定可以购买成功(即使购买后卡上余额为负),否则无法购买(即使金额足够)”,也是就是说,当卡上的金额大于等于5时,可以用5元去买任意价格的菜,所以当然是用这5元去买最贵的菜了,剩下的问题就是,求剩下的m-5元能买到的最高的价值总量,也就是一个单纯的01背包问题了。

#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;const int Max = 1010;int N,p[Max],dp[Max],V;int main(){//    freopen("in.txt", "r", stdin);    while(scanf("%d",&N) != EOF && N){        for(int i=0; i<N; i++)            scanf("%d",&p[i]);        scanf("%d",&V);        if(V < 5){            printf("%d\n",V);            continue;        }        V -= 5;        sort(p, p+N);        memset(dp, 0, sizeof(dp));        for(int i=0; i<N-1; i++){            for(int j=V; j>=p[i]; j--){                dp[j] = max(dp[j - p[i]] + p[i], dp[j]);            }        }        printf("%d\n",V + 5 - p[N-1] - dp[V]);    }    return 0;}


0 0
原创粉丝点击