http://acm.hdu.edu.cn/showproblem.php?pid=1009
dp算法,最主要是 结构体,比例从大到小。
贪心算法HDU1009 FatMouse' Trade
题目大意:
老鼠有M磅猫食。有N个房间,每个房间前有一只猫,房间里有老鼠最喜欢的食品JavaBean,J[i]。若要引开猫,必须付出相应的猫食F[i]。当然这只老鼠没必要每次都付出所有的F[i]。若它付出F[i]的a%,则得到J[i]的a%。求老鼠能吃到的做多的JavaBean。
解题思路:
老鼠要获得最多的食品,就要用最小的猫食换取最多的猫食,这就要求J[i]/F[i]的比例要大。J[i]/F[i]的比例越大,证明在这个房间,小鼠付出得到的收获最有价值。于是我们将设置结构体,结构体里设置percent放置J[i]/F[i]。然后对结构体数组进行排序。依次按比例排序的付出猫食,即可。
例子:
输入
5 3
7 2
4 3
5 2
按J[i]/F[i]排序后:
7 2
5 2
4 3
在第一排数据上,小鼠付出2个猫食换得7个JavaBean。
在第二排数据上,小鼠付出2个猫食换得5个JavaBean。
在第三排数据上,小鼠只剩下1个猫食,便用这一个猫食换取1/3*4个JavaBean。
所以,总共换得13.333个JavaBan。
FatMouse' Trade
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 37762 Accepted Submission(s): 12490
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
#include<iostream> #include<algorithm> using namespace std; struct Trade { int j,f; double percent; }mouse[3001]; bool cmp(Trade a,Trade b) { return a.percent>b.percent; } int main() { int m,n,i,sum,ans,temp; double cnt; while(~scanf("%d%d",&m,&n)) { sum=0;ans=0;temp=0; if(m==-1&&n==-1) break; for(i=0;i<n;i++) { scanf("%d%d",&mouse[i].j,&mouse[i].f); mouse[i].percent=(double)mouse[i].j/mouse[i].f; } sort(mouse,mouse+n,cmp); for(i=0;i<n;i++) { sum+=mouse[i].f; if(sum<=m) { ans+=mouse[i].j; temp+=mouse[i].f; } else { sum=m-temp; break; } } cnt=(double)mouse[i].j*((double)sum/mouse[i].f); printf("%.3lf ",cnt+ans); } return 0; }