题目描述】
某天KID利用飞行器飞到了一个金银岛上,上面有许多珍贵的金属,KID虽然更喜欢各种宝石的艺术品,可是也不拒绝这样珍贵的金属。但是他只带着一个口袋,口袋至多只能装重量为w的物品。岛上金属有KID想一次带走价值尽可能多的金属,问他最多能带走价值多少的金属。注意到金属是可以被任意分割的,并且金属的价值和其重量成正比。
【输入】
第1行是测试数据的组数k组输入。
每组测试数据占3行,第1行是一个正整数
【输出】
2位。
【输入样例】
2 50 4 10 100 50 30 7 34 87 100 10000 5 1 43 43 323 35 45 43 54 87 43
【输出样例】
171.93 508.00
贪心经典问题:
按照价值从大到小排序然后就ok了,注意多组数据要输出换行,坑了我一次
#include<iostream> #include<cstdio> #include<algorithm> #include<cmath> #include<queue> #include<stack> #include<vector> #include<map> #include<string> #include<cstring> using namespace std; const int maxn=999999999; const int minn=-999999999; inline int read() { char c = getchar(); int x = 0, f = 1; while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar(); } while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar(); return x * f; } struct node { int w; int c; double g; } a[1005]; int my_comp(node ggg,node ggggg) { return ggg.g>ggggg.g; } int main() { int kkk,W,M; cin>>kkk; while(kkk--) { double cnt=0; cin>>W>>M; for(int i=1; i<=M; i++) { cin>>a[i].w>>a[i].c; a[i].g=a[i].c*1.0/a[i].w;//处理价值 } sort(a+1,a+1+M,my_comp);//按价值排序 for(int i=1; i<=M; ++i) { if(W>=a[i].w) { cnt+=a[i].c; W-=a[i].w; } else { cnt+=a[i].g*W; break; } } printf("%.2lf\n",cnt); } return 0; }