HDU-1009FatMouse' Trade
FatMouse' Trade
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
题目链接
http://acm.hdu.edu.cn/showproblem.php?pid=1009
Problem Description
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 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
5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1
Sample Output
13.333
31.50
总结
初步了解了贪心算法,是选择价值比最大的东西来拿(由于可以切开拿,不是必须整体),接下来就好多了。
遇到的问题主要是浮点数的误差,只能用价值比(浮点数)比较大小,后面的运算求和时不能用它相乘来计算,拿样例来说,结果是13.333,而我没改进前,算出来是12.444.可见是误差。
第二个就是网上其他人使用结构体来储存,这样排序时其他变量能一起移动,但我开了3个数组,而且也不能用sort来排序了,只能自己写了选排。
#include<iostream>
#include<cstdio>
using namespace std;
double price[1005];
int num1[1005],num2[1005];
void sort1(double* a,int x)
{
int b;
double c;
for(int i=0;i<x;i++){
for(int j=i+1;j<x;j++){
if(a[i]<a[j]){
c=a[i];
a[i]=a[j];
a[j]=c;
b=num1[i];
num1[i]=num1[j];
num1[j]=b;
b=num2[i];
num2[i]=num2[j];
num2[j]=b;
}
}
}
}
int main()
{
int m,n,j;
while(scanf("%d %d",&m,&n)==2){
if(m==-1&&n==-1) break;
for(int i=0;i<n;i++){
scanf("%d %d",&num2[i],&num1[i]);
price[i]=(double)num2[i]/num1[i];
}
sort1(price,n);
//for(int i=0;i<n;i++) cout <<price[i]<<num[i]<<endl;
double sum=0;
for(int i=0;i<n;i++){
if(m<=0) break;
if(m>=num1[i]){
sum+=num2[i];
m-=num1[i];
}
else {
sum+=(double)m/num1[i]*num2[i];
m=0;
}
}
printf("%.3lf\n",sum);
}
return 0;
}