题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1009
题目大意:Fatmouse有M puonds猫粮,想要和猫换取食物,猫看管着N间仓库,没见仓库里有J[i]pounds食物,需要用F[i]pounds猫粮才能换取,没见仓库的食物不用全部换取, J[i] * a% = F[i] * a%, 问Fatmouse最多可以换取多少食物。
分析:很经典的贪心算法,利用结构体,根据换取利率排序,然后将数组跑一遍。需要注意数据的精度,float过不了,需要用double
ac代码
#include<cstdio>
#include<algorithm>
#define Max 1005
using namespace std;
struct mouse
{
int x, y;
double z;
}a[Max];
bool cmp(const mouse &A, const mouse &B)
{
if(A.z < B.z)return true;
else return false;
}
int main()
{
int M, N;
while(scanf("%d %d", &M, &N))
{
if(M == -1 && N == -1)break;
for(int i = 0; i < N; i++)
{
scanf("%d %d", &a[i].x, &a[i].y);
a[i].z = (double)a[i].x / a[i].y;
}
sort(a, a + N, cmp);
//for(int i = 0; i < N; i++)
//printf("%d %d\n", a[i].x, a[i].y);
double ans = 0, sum = 0;
int t;
for(t = N - 1; t >= 0; t--)
{
if(ans + a[t].y <= M)
{
ans = ans + a[t].y;
sum = sum + a[t].x;
//printf("flag\n");
}
else break;
}
//printf("ans = %.3f\n", ans);
sum = sum + a[t].z * (M - ans);
printf("%.3lf\n", sum);
}
return 0;
}