AOJ 2.Home Work

贪心算法

如果在类中定义自定义类型对应sort的比较函数,要注意再比较函数前加上static。说明该函数是静态函数,在内存中占用固定的内存。

 1 #include <cstdio>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 #define REP(n) for(int o=0;o<n;o++)
 6 
 7 
 8 class LOVE {
 9 private:
10     static const int maxn = 25;
11     int M, N;
12     struct node {
13         int T, V;
14         double p;
15     }paper[maxn];
16 
17     static bool compare_node(node a, node b) {
18         return a.p > b.p;
19     }
20 
21 public:
22     bool Do() {
23         scanf("%d%d", &M, &N);
24         if (M == 0 && N == 0)return false;
25         REP(M) {
26             int T, V;
27             scanf("%d%d", &T, &V);
28             paper[o].T = T;
29             paper[o].V = V;
30             paper[o].p = (double)V / (double)T;
31         }
32 
33         sort(paper, paper + M, compare_node);
34 
35         //REP(M)
36             //printf("T=%d V=%d p=%f\n", paper[o].T, paper[o].V, paper[o].p);
37 
38         double ans = 0;
39         for (int i = 0; i < M; i++) {
40             int temp = N - paper[i].T;
41             ans += paper[i].V;
42             if (temp < 0) {
43                 ans += temp*paper[i].p;
44                 break;
45             }
46             N = temp;
47         }
48 
49         printf("%.2f\n", ans);
50         return true;
51     }
52 };
53 
54 int main() {
55     LOVE LIVE;
56     while (LIVE.Do());
57     return 0;
58 }

 

posted @ 2016-03-05 13:30  OhYee  阅读(257)  评论(0编辑  收藏  举报