# 关于一个背包问题。

0

#include<iostream>
#include<algorithm>
using namespace std;
struct abc
{
float a;
float b;
float c;
};
bool comp(const abc e, const abc f)
{
return (e.a)<(f.a);
}
int main()
{
int n,i,sum1=0,sum2=0;
float m,w,d;
while(cin>>n>>m)
{
sum1=0;sum2=0;
struct abc k[n];
for(i=0;i<n;i++)
{
cin>>w>>d;
k[i].c=w;
k[i].b=d;
k[i].a=d/w;
}
sort(k,k+n,comp);
for(i=n-1;i>=0;i--)
{
sum1+=k[i].c;
if(sum1<=m)
sum2+=k[i].b;
}
cout<<sum2<<endl;
}
return 0;
}

Description

Bessie has gone to the mall's jewelry store and spies a charm bracelet. Of course, she'd like to fill it with the best charms possible from the N (1 ≤ N ≤ 3,402) available charms. Each charm i in the supplied list has a weight Wi (1 ≤ Wi ≤ 400), a 'desirability' factor Di (1 ≤ Di ≤ 100), and can be used at most once. Bessie can only support a charm bracelet whose weight is no more than M (1 ≤ M ≤ 12,880).

Given that weight limit as a constraint and a list of the charms with their weights and desirability rating, deduce the maximum possible sum of ratings.

Input

* Line 1: Two space-separated integers: N and M * Lines 2..N+1: Line i+1 describes charm i with two space-separated integers: Wi and Di

Output

* Line 1: A single integer that is the greatest sum of charm desirabilities that can be achieved given the weight constraints

Sample Input

4 6 1 4 2 6 3 12 2 7

Sample Output

23

0
```#include<iostream>
#include<algorithm>
using namespace std;
struct abc
{
float a;
float b;
float c;
};
bool comp(const abc e, const abc f)
{
if(e.a!=f.a)
return e.a<f.a;
else         // 考虑如果权重相等的时候，优先选择重量大的
return e.c>f.c;
}
int main()
{
int n,i,sum1=0,sum2=0;
float m,w,d;
while(cin>>n>>m)
{
sum2=0;
struct abc k[n];
for(i=0;i<n;i++)
{
cin>>w>>d;
k[i].c=w;
k[i].b=d;
k[i].a=d/w;
}
sort(k,k+n,comp);
i=n-1;
while(m-k[i].c>=0)  //贪心选择
{
sum2+=(int)k[i].b;
m-=k[i].c;
i--;
}
cout<<sum2<<endl;
}
return 0;
}```

Double_win | 菜鸟二级 |园豆：244 | 2014-04-24 17:34

（3）贪心策略：选取单位重量价值最大的物品。反例：

W=30
物品：A B C
重量：28 20 10
价值：28 20 10
根据策略，三种物品单位重量价值一样，程序无法依据现有策略作出判断，如果选择A，则答案错误。

您需要登录以后才能回答，未注册用户请先注册