HDU 2546 饭卡 动态规划01背包

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

题意:

  给你一些饭菜的价格,和你饭卡的余额,余额大于等于5元时可以刷任何价格的菜,算出你买了这些菜之后饭卡中最少的一组解(余额可以为负)。

 

坑爹:

  这道题中,他的价格也就是背包中的容量,也是背包中的价值,总余额如果超出5元要将总余额减去5元的钱尽量用掉。

 

解法

  用到了一点贪心的思想,用一个sort排序,将便宜的菜买了,尽量将饭卡里的余额靠近5元,然后在买一个最贵的菜,这样就会让饭卡里的余额最少了。

 

 

View Code
 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 
 5 const int maxn =1000 + 10;
 6 int f[maxn];
 7 int more;
 8 
 9 int max(int a,int b)
10 {
11     return a>b?a:b;
12 }
13 
14 
15 void ZeroOnePack(int cost,int weight)
16 {
17     int j;
18     for(j=more;j>=cost;j--)
19     {
20         f[j]=max(f[j],f[j-cost]+weight);
21     }
22 }
23 
24 int main()
25 {
26     int n;
27     while(cin>>n,n)
28     {
29         int i;
30         int num[maxn];
31         int money;
32         int exp;
33         int sum=0;
34         memset(f,0,sizeof(f));
35         for(i=0; i<n; i++)
36         {
37             cin>>num[i];
38             sum+=num[i];
39         }
40         sort(num,num+n);
41         exp=num[n-1];
42         cin>>money;
43         if(money<5)
44         {
45             cout<<money<<endl;
46             continue;
47         }
48         more=money-5;
49         for(i=0; i<n-1; i++)
50         {
51             ZeroOnePack(num[i],num[i]);
52         }
53     
54         cout<<money-f[more]-exp<<endl;
55     }
56     return 0;
57 } 

 

posted @ 2012-09-05 20:57  pc....  阅读(198)  评论(0)    收藏  举报