4110: Santa Claus gift -Santa Clau's Gifts (greedy algorithm)

 

Total time limit: 
1000ms
 
Memory Limit: 
65536kB
description

Christmas is coming, in the city of Santa A candy ready for distribution, now how different box of candy, box of candy has its own value and weight, each box of candy can be split into any bulk composition away. Santa's reindeer can only withstand up to a certain weight of candy, Santa Claus can take up to ask how much the value of the candy.

Entry
The first line consists of two parts, respectively a positive integer number confectionery boxes n (1 <= n <= 100), reindeer can withstand the maximum positive integer weight w (0 <w <10000), the two numbers separated by a space open. Remaining n lines each corresponding to a box of candy, it consists of two parts, namely a value of a positive integer candy box wt positive integers and v w, separated by a space.
Export
Santa Claus can take the maximum output of the total value of candy, reserved a decimal. Output as one line, terminated by a newline.
Sample input
4 15
100 4
412 8
266 7
591 2
Sample Output
1193.0

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 struct T {
 4     int v,w;
 5     double p;
 6 };
 7 bool cmp(T a,T b) {
 8     return a.p>b.p;
 9 }
10 
11 int main() {
12     int n,m;
13     double ans=0;
14     cin>>n>>m;
15     T t[n];
16     for(int i=0; i<n; i++) {
17         cin>>t[i].v>>t[i].w;
18         t[i].p=t[i].v/t[i].w;
19     }
20     sort(t,t+n,cmp);
21     int i=0;
22     while(m>0) {
23         if(m-t[i].w>0) {
24             ans+=t[i].v;
25             m-=t[i].w;
26             i++;
27         }
28         else{
29             ans+=t[i].p*m;
30             m=0; 
31         }
32     }
33     printf("%.1lf\n",ans);
34     return 0;
35 }

 

Guess you like

Origin www.cnblogs.com/aiqinger/p/12584306.html