天天看點

HDU 1009 貪心問題FatMouse' Trade

FatMouse' Trade

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 46205 Accepted Submission(s): 15482

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.

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.500
        

Author CHEN, Yue

Source

ZJCPC2004  

這道題是道貪心的題目,就是題目有點難懂,很早之前就想做這題了,奈何題目一直看不懂,花了很大功夫了解了題目。然後今天終于做出來了。。題意:老鼠有m克的貓糧,想去跟貓兌換食物,但是老鼠喜歡的食物在倉庫的不同層,每層的兌換率都不一樣。求的是最多能兌換到多少食物。

5 3

7 2

4 3

5 2

這個案例代表有老鼠有5克貓糧 ,食物一共放在不同的三層 ,第一層有7克食物,需要2克貓糧兌換,兌換率為7/2;第二層第三層類似。

是以要貪心的話,就要先選出兌換率最大的一層開始兌換。上代碼上解析。

#include <stdio.h>
#define wbx 50000
int a[wbx]; //wbx代表第wbx層,a[wbx]代表第wbx層的食物。
int b[wbx]; //b[wbx]第wbx層的貓糧。
double p[wbx];// p代表第wbx層的兌換率。
#include <string.h>
#include <algorithm>
using namespace std;
void solve()
{
	int m,n;
	while(scanf("%d%d",&m,&n)&&m!=-1 &&n!=1)
	{
		int i,k;
		double sum=0;
		for(i=1;i<=n;i++)
		{
			scanf("%d%d",&a[i],&b[i]);//輸入每層的食物和貓糧
			p[i]=double(a[i]*1.0/b[i]);  //算出每層的兌換率
		} 
		while(m!=0 &&n!=0)  //m=0或者n=0代表着結束,跳出循環。
		{
			double max=-999;
			for(i=1;i<=n;i++)
			{
				if(p[i]>max)
				{
					max=p[i];//每次都先找出每層兌換率最大的。
					k=i;//把值賦給k。
				}
			}
			if(m-b[k]>=0)// 如果貓糧大于等于這層的貓糧
			{
				m-=b[k];//  減去這層的貓糧。
				sum+=a[k];// 得到這層所有食物。
				p[k]=0;// 這層兌換完了,讓它的兌換率為0。
			}
			else
			{
				sum+=m*p[k];// 如果剩餘貓糧已經小于想兌換的這層的貓糧,那就用剩下的貓糧兌換所有的食物。
				m=0;//貓糧為0,跳出循環。
			}
		}
		sum=double(sum);
		printf("%.3lf\n",sum);//sum就是最優解。。
	}
}
int main()
{
	solve();//問題解決。。
	return 0;
}