水题一条,用贪心就可以解决。以每个房间的Java Beans / Food作为标准排序,最后无法全部交换的需要算百分比换算成JavaBeans;
#include<iostream>
#include<vector>
#include<cstdio>
#include<algorithm>
using namespace std;
struct Trade
{
int J;
int F;
double per;
}no[1001];
bool cmp(Trade a,Trade b)
{
return a.per > b.per;
}
int main()
{
int n,i,m;
double sum;
while(cin>>m>>n && m!=-1&&n!=-1)
{ sum = 0.0;
for(i=0;i<n;i++)
{cin>>no[i].J>>no[i].F;
no[i].per = no[i].J * 1.0 / no[i].F;
}
sort(no,no+n,cmp);
for(i=0;i<n;i++)
{ if(m - no[i].F>= 0)
{sum += no[i].J;
m -= no[i].F;
}
else
{
sum += m * no[i].per;
m = 0;
break;
}
}
printf("%.3f\n",sum);
}
return 0;
}