1.题目描述
FatMouse's Trade:
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.
Input:
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.
Output:
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.
Sample Input:
4 2
4 7
1 3
5 5
4 8
3 8
1 2
2 5
2 4
-1 -1
Sample Output:
2.286
2.500
2. 代码示例及讲解
这个题目我们可以简单理解为,在 n 个房间中,要用一定的食物和猫换取一定的豆子,且每一个房间的交换比都不同,开始会给出 m 拥有的食物数,你要如何交换才能得到更多豆子。当 n 和 m 有一个等于 -1 时,那么程序就结束。
#include<stdio.h>
void swapDouble( double *a, double *b)
{
double t = *a;
*a = *b;
*b = t;
}
void swapInt( int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
int main()
{
while( 1 )
{
int m, n;
scanf("%d%d", &m, &n);
// 如果拥有食物数和房间数为-1,则结束程序
if( m == -1 || n == -1 )
{
break;
}
// 用一个二维数组来存储用多少猫食交换多少豆子
int exchange[n][2], i;
// 用一个一维数组来存储交换的性价比(豆子数 / 食物数)
double costPerformance[n];
for( i = 0; i < n; i++)
{
scanf("%d%d", &exchange[i][0], &exchange[i][1]);
// 如果不需要食物就能换豆子,那么性价比是最高的,这里我们以1000为最高性价比
if( exchange[i][1] == 0 )
{
costPerformance[i] = 1000.0;
continue;
}
costPerformance[i] = 1.0 * exchange[i][0] / exchange[i][1];
}
double count = 0.0;
// 用冒泡排序将二维数组和一维数组按性价比高低排好序,高在前
for( i = 0; i < n - 1; i++)
{
for( int j = 0; j < n - 1 - i; j++)
{
if( costPerformance[j] < costPerformance[j+1] )
{
swapDouble(&costPerformance[j], &costPerformance[j+1]);
swapInt(&exchange[j][0], &exchange[j+1][0]);
swapInt(&exchange[j][1], &exchange[j+1][1]);
}
}
}
for( i = 0; i < n; i++)
{
// 当性价比最大时,就直接获取房间里面的豆子 ,且不需要消耗食物
if( costPerformance[i] == 1000 )
{
count += exchange[i][0];
}
else if( exchange[i][1] >= m )
{
count += m * costPerformance[i];
break;
}
else if( exchange[i][1] < m )
{
count += exchange[i][0];
m -= exchange[i][1];
}
}
printf("%.3lf\n", count);
}
return 0;
}