贪心一般就是按照某种贪心规则排序好之后从最贪心的方式开始选择,某种贪心规则一般用sort一起使用,以下是喝饮料的例子:
#include <iostream>
#include <algorithm>
using namespace std;
struct yinliao{
double price;
double weight;
}yin[1000];
bool cmp(yinliao a,yinliao b){
return a.price/a.weight < b.price/b.weight;
}
int main(){
int x;
int n;
while (scanf("%d%d",&x,&n) != EOF){
if(x == -1 && n == -1)
break;
for(int i = 0;i < n;i++){
scanf("%lf%lf",&yin[i].weight,&yin[i].price);
}
sort(yin,yin+n,cmp);
double ans = 0;
for(int i = 0;i < n;i++){
if(x >= yin[i].price){
x -= yin[i].price;
ans += yin[i].weight;
}else{
ans += x * yin[i].weight / yin[i].price;
//记得没钱就跳出
break;
}
}
printf("%.3lf\n",ans);
}
return 0;
}
网友评论