HDUOJ 悼念512汶川大地震遇难同胞——老人是真饿了

贪心算法~

#include<iostream>
#include<stdio.h>
#include<algorithm> 
#include<string.h>
#include <iomanip>
using namespace std;

struct rice {
    int price;
    int weight;
}r[1001];

bool cmp(rice a, rice b) {
    return a.price < b.price;
}

int main() {
    int c = 0;
    while (cin >> c) {
        while (c--) {
            int m, n = 0;
            int k = 0;
            double sum = 0;
            cin >> n >> m;
            double money = (double)n;
            for (int i = 0; i < m; i++) {
                cin >> r[i].price >> r[i].weight;
            }
            sort(r, r + m, cmp);
            while (money > 0.0) {
                if ((double)r[k].price*r[k].weight >= money)
                {
                    sum += money / (double)r[k].price;
                    money = 0.0;
                }
                else {
                    sum += (double)r[k].weight;
                    money -= (double)(r[k].price * r[k].weight);
                    k++;
                }
            }
            cout << setprecision(2) << fixed << sum << endl;
        }
    }
}

 

posted @ 2018-09-15 10:12  图袋鼠  阅读(342)  评论(0编辑  收藏  举报