HDU1009 Fatmouse ' Trade

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.