简单贪心。用结构体数组存储数据。注意:1、qsort给double类型数据排序时注意要用

return (*((struct node *)b1)).r > (*((struct node *)a1)).r? 1 : -1;

用return (*((struct node *)b1)).r - (*((struct node *)a1)).r;话会报错的。

CODE:

  1 #include <stdio.h>

 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <math.h>
 5 
 6 
 7 const int size = 1010;
 8 int N , M;
 9 double sum;
10 struct node
11 {
12     double f;
13     double j;
14     double r;
15 }a[size];
16 
17 
18 int cmp(const void *a1 , const void *b1)
19 {
20     return (*((struct node *)b1)).r > (*((struct node *)a1)).r? 1 : -1;
21 }
22 
23 
24 double Greedy()
25 {
26     int i , j;
27     
28     for(i = 0 ; i < N ; i++)
29     {
30         scanf("%lf%lf", &a[i].j, &a[i].f);
31         a[i].r = a[i].j / a[i].f;
32     }
33     
34     qsort(a , N , sizeof(a[0]) , cmp);
35     
36     for(i = 0 ;i < N; i++)        // x = select
37     {
38         if(M >= a[i].f)               //feasible(S,x);
39         {
40             sum += a[i].j;
41             M -= a[i].f;
42         }
43         else
44         {
45             sum += (a[i].j / a[i].f) * M;
46             break;
47         }
48     }
49     return sum;    
50 }
51 
52 int main()
53 {
54     while(~scanf("%d%d", &M, &N))
55     {
56         int i , j;
57         if(N == -1 && M == -1)
58         {
59             break;
60         }
61         memset(a , 0 ,sizeof(a));
62         sum = 0;
63         Greedy();
64         printf("%.3lf\n", sum);
65     }
66     return 0;
67 }
posted on 2012-06-02 20:01  有间博客  阅读(226)  评论(0编辑  收藏  举报