#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;
}
我现在还没有学算法数据结构什么的,想问一下博园里的大牛们就现在的代码怎么改一下可以Ac?
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 7Sample Output
23#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; }
谢谢你回答我的问题,在学校的服务器运行老是错误,在poj上直接都编译不了。。。可能因为这个吧 struct abc k[n]; 我用的别的方法做了,不过还是感谢你
我知道错误的原因了,如下
(3)贪心策略:选取单位重量价值最大的物品。反例: