Problem Description
E_star和von是中国赫赫有名的两位商人,俗话说的好无商不奸,最近E_star需要进一批苹果。可是他需要的苹果只有von才有,von的苹果都存在他的传说中很牛叉的仓库里,每个仓库都存了不同种类的苹果,而且每个仓库里的苹果的价钱不同。如果E_star想要买仓库i里的所有重量为f[i]的苹果他必须付m[i]的金钱。E_star开着他的传说中的毛驴车去拉苹果,而且他只带了N些金钱。E_star作为传说中的奸商希望用它所带的N金钱得到重量最多的苹果。你作为他最好的朋友,所以他向你求出帮助。希望你能帮忙计算出他能买到最多的苹果(这里指重量最大)。并输出最大重量。
提示:这里仅考虑仓库里苹果的重量,不考虑个数。
Input
第一行包括两个非负整数N,M(分别代表E_star带的金币数,von盛苹果的仓库数量,不超过50)。
接下来有有M行,每行包括两个数非负整数f[i]和m[i]分别表示第i仓库里存有重量为f[i]的苹果,如果将所有苹果买下要花费m[i]的金钱,E_star不必非要将每个仓库的苹果全部买下。
当M,N同时为-1是结束。
Output
E_star用N的金币所能买到的最大重量的苹果的重量。结果保留三位小数。
Example Input
5 3 7 2 4 3 5 2 20 3 25 18 24 15 15 10 -1 -1
Example Output
13.333 31.500
Hint
Author
E_star
代码如下
#include<stdio.h>
struct business
{
int weight;
int price;
double cost;
};
int main()
{
int n, m, i, j;
double sum;
struct business b[55], t;
scanf("%d%d", &n, &m);
while(n != -1&&m != -1)
{
sum = 0.0;
for(i = 0; i < m; i++)
{
scanf("%d%d", &b[i].weight, &b[i].price);
if(b[i].price!=0)
b[i].cost = 1.0*b[i].weight/b[i].price;
else
b[i].cost = 0;
}
for(i = 0; i < m; i++) //利用性价比进行一个排序,这样先买性价比高的
{
for(j = 0; j < m - 1; j++)
{
if(b[j].cost < b[j+1].cost)
{
t = b[j];
b[j] = b[j+1];
b[j+1] = t;
}
}
}
for(i = 0; i < m; i++)
{
if(b[i].cost == 0) //其实很想吐槽明明是狡猾奸诈的商人为毛会有价格为0的商品
{
sum += b[i].weight;
}
}
for(i = 0;i < m;i++)
{
if(n > b[i].price)
{
n = n - b[i].price;
sum += b[i].weight;
}
else if(n <= b[i].price)
{
sum += b[i].cost * n;
n = 0;
}
else
i = m;
}
printf("%.3lf\n", sum);
scanf("%d%d", &n, &m);
}
}
今日心得:往往有序会使很多问题更简单