题解|#FatMouse's Trade#(简单贪心)
FatMouse's Tradehttps://oj.youdao.com/problem/658?from=problems
题目描述
FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.
输入描述
The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J[i] and F[i] respectively. The last test case is followed by two -1's. All integers are not greater than 1000.
输出描述
For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of JavaBeans that FatMouse can obtain.
#include<iostream>
#include<algorithm>
using namespace std;
struct javabean{
int weight;
int cost;
};
javabean s[10010];
bool compare(javabean a,javabean b){
return (1.0*a.weight/a.cost>1.0*b.weight/b.cost);
}
int main(){
int M,N;
while(scanf("%d %d",&M,&N)!=EOF){
if(M<0&&N<0)break;
for(int i=0;i<N;i++)scanf("%d %d",&s[i].weight,&s[i].cost);
sort(s,s+N,compare);
double sum=0;
for(int i=0;i<N;i++){
if(M>=s[i].cost){
sum+=s[i].weight;
M-=s[i].cost;
}
else {
sum+=M*1.0/s[i].cost*s[i].weight;
break;
}
}
printf("%.3lf\n",sum);
}
return 0;
}
外源题解补充
SHEIN希音公司福利 222人发布
查看12道真题和解析
