贪心法:部分背包问题

每个物品都可以拿走一部分,要在不超重的情况下总价值最高,这应该是最简单的一类贪心问题了,思路很明显,考虑性价比即可,安装性价比排序,从高到低开始拿,除了最后一个物品之外,要么不拿,要么拿走全部,具体实现如下。请注意结果的细节,对最后一个物品的处理。

 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 const int maxn=1005;
 5 int n;
 6 int C;
 7 int ans=0; 
 8 struct Object
 9 {
10     int w;  //weight
11     int v;  //value
12     double re;
13 }a[maxn];
14 bool cmp(Object x,Object y)
15 {
16     return x.re>y.re;
17 }
18 int main()
19 {
20     cin>>n;
21     for(int i=1;i<=n;i++)
22     {
23         cin>>a[i].w>>a[i].v;
24         a[i].re=a[i].v*1.0/a[i].w;
25     }
26     cin>>C;
27     sort(a+1,a+n+1,cmp);
28     int tmp=0;
29     for(int i=1;i<=n;i++)
30     {
31         tmp+=a[i].w;
32         if(tmp<=C)
33             ans++;
34         else
35             break;
36     }
37     cout<<ans<<endl;
38     return 0;
39 }
原文地址:https://www.cnblogs.com/aininot260/p/9272908.html