Saving HDU HDU - 2111

原题链接

考察:贪心

思路:

       贪心策略:从价值高的开始取,直到背包体积不够用.

       乍一看很像背包问题,但是这里给的是单价,而背包问题是总体价值且不能分割.

 1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4 #include <cstdio>
 5 using namespace std;
 6 const int N = 110;
 7 typedef pair<int,int> PII;
 8 PII p[N];
 9 int main() 
10 {
11     int n,v;
12     while(scanf("%d%d",&v,&n)!=EOF&&v!=0)
13     {
14         int ans = 0;
15         for(int i=1;i<=n;i++) scanf("%d%d",&p[i].first,&p[i].second);
16         sort(p+1,p+n+1);
17         for(int i=n;i>=1;i--) 
18         {
19             int sum = p[i].second,val = p[i].first,t = min(sum,v);
20             v-=t;
21             ans+=t*val;
22             if(!v) break;
23         }
24         printf("%d\n",ans);
25     }
26     return 0;
27 }

 

posted @ 2021-02-20 22:24  acmloser  阅读(35)  评论(0编辑  收藏  举报