Main topic:
The rat wanted to eat coffee beans, which were guarded by a cat, and it needed to be replaced with some cat food.
Read two integers m,n the total number of cat food in the mouse, and the number of rooms with coffee beans. Next n lines, two numbers per line J[i],f[i], representing the total number of coffee beans in the room and the number of cat food needed, to find out when the mouse can obtain the largest number of cat food, know to receive -1,-1 end processing.
Problem Solving Ideas:
The problem of fractional knapsack in a typical greedy problem. Because you can get any part of the coffee beans in the room, so converted to a fractional backpack for the problem, to find the price per room of coffee beans, I was to find the unit weight of cat food can be exchanged for coffee beans, so I think can be conveniently calculated, This amount is then sorted in descending order (the maximum number of coffee beans that can be exchanged for the unit weight is preferred).
The code is as follows:
# include <iostream># include <algorithm>using namespace std;struct node{int a,b;double price;} List[1001];bool CMP (node X,node y) {return x.price>y.price;} int main () {freopen ("Input.txt", "R", stdin), int m,n;while (scanf ("%d%d", &m,&n)!=eof && M!=-1 & & N!=-1) {memset (list,0,sizeof (List)); int I,j;for (i=0;i<n;i++) {scanf ("%d%d", &list[i].a,&list[i].b) ; List[i].price= (double) list[i].a/list[i].b;} Sort (list,list+n,cmp);d ouble maxs=0;for (i=0;i<n;i++) {if (m>=list[i].b) {maxs=maxs+list[i].a;m=m-list[i].b;} Else{maxs=maxs+m*list[i].price;m=0;break;}} printf ("%.3lf\n", Maxs);} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
HDU1009 Fatmouse ' Trade