1. 程式人生 > >HDU 3979【貪心】

HDU 3979【貪心】

時有 print %d algorithm void string time urn LG

這題剛開始想當然的直接按g值排序了。
正確做法是,由於要失去的血量最小,則若此時有兩個monster A,B
先A後B失去的血量為 (timeA+timeB)gB+timeAgA
先B後A失去的血量為(timeA+timeB)gA+timeBgB
按這個排序即可
!註意這裏有個精度問題,long long才能過

#include <iostream>
#include <queue>
#include <algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
#define MAX 10000+10
int n, m;
struct M {
    int hp, g;
    double t;
}monster[MAX];

int cmp(const M&a, const M&b) {
    return  a.t*b.g < b.t*a.g;
}

int main(void) {
    int t;
    int Kase = 0;
    scanf("%d", &t);
    int Time;

    while (t--) {
        long long ans = 0;
        Time = 0;
        scanf("%d%d", &n, &m);
        int hp, g;
        for (int i = 1; i <= n; i++) {
            scanf("%d%d", &hp, &g);
            monster[i].hp = hp;
            monster[i].g = g;
            monster[i].t = (__int64)ceil((double)monster[i].hp / (double)m);
        }
        sort(monster + 1, monster + 1 + n, cmp);
        for (int i = 1; i <= n; i++) {
            Time += monster[i].t;
            ans += (long long)monster[i].g*Time;

        }
        printf("Case #%d: %I64d\n", ++Kase, ans);
    }

    return 0;

}

HDU 3979【貪心】