HDU1009(贪心)

水题~

按照性价比排序。

#include <bits/stdc++.h>
using namespace std;
#define maxn 1111

int n, m;
struct node {
    double val;
    int cnt;
    bool operator < (const node &a) const {
        return val/cnt > a.val/a.cnt;
    }
}a[maxn];
int tot;

int main () {
    //freopen ("in", "r", stdin);
    while (scanf ("%d%d", &m, &n) == 2) {
        if (n == -1 && m == -1)
            break;
        int sum = 0;
        tot = 0;
        for (int i = 0; i < n; i++) {
            scanf ("%lf%d", &a[i].val, &a[i].cnt);
        }
        sort (a, a+n);
        double ans = 0;
        for (int i = 0; i < n; i++) { 
            if (sum+a[i].cnt > m) {
                ans += a[i].val*(m-sum)/a[i].cnt;
                break;
            }
            else {
                ans += a[i].val;
                sum += a[i].cnt;
            }
        }
        printf ("%.3f\n", ans);
    }
    return 0;
}


你可能感兴趣的:(HDU1009(贪心))