Description

Farmer John went to cut some wood and left N (2 ≤ N ≤ 100,000) cows eating the grass, as usual. When he returned, he found to his horror that the cluster of cows was in his garden eating his beautiful flowers. Wanting to minimize the subsequent damage, FJ decided to take immediate action and transport each cow back to its own barn.
Each cow i is at a location that is Ti minutes (1 ≤ Ti ≤ 2,000,000) away from its own barn. Furthermore, while waiting for transport, she destroys Di (1 ≤ Di ≤ 100) flowers per minute. No matter how hard he tries, FJ can only transport one cow at a time back to her barn. Moving cow i to its barn requires 2 × Ti minutes (Ti to get there and Ti to return). FJ starts at the flower patch, transports the cow to its barn, and then walks back to the flowers, taking no extra time to get to the next cow that needs transport.
Write a program to determine the order in which FJ should pick up the cows so that the total number of flowers destroyed is minimized.

Kurisu 人工翻译: 有一堆牛,每次只能抱一只回去,如果当前有n只牛,当抱一只牛的时候剩下n - 1只会破坏花草,求怎么抱牛最后破坏值最小

Solution

首假设只有两只牛 ,先构造一个式子
这个式子代表先抱 比先抱 优的情况
不等式左右除以 ,得到
其中不等式左右只跟自己本身有关,即可以定义一个属性
先取 小的会更优(上面 更小,先取 更优)
所以直接按 排序,贪心取,用一个前缀和优化一下即可

#include<iostream>
#include<algorithm>

using namespace std;

const int N = 1e5 + 5;

struct node {
    int t, d;
    double rate;
    bool operator < (const node &s) const {
        return rate < s.rate;
    }
}a[N];

int sum[N]; // 前缀和

int main() {
    int n;
    cin >> n;
    for(int i = 1; i <= n; i++) {
        cin >> a[i].t >> a[i].d;
        a[i].rate = 1.0 * a[i].t / a[i].d;
    }
    sort(a + 1, a + 1 + n);
    for(int i = 1; i <= n; i++) {
        sum[i] = sum[i - 1] + a[i].d;        
    }
    long long ans = 0;
    for(int i = 1; i <= n; i++) {
        ans += (sum[n] - sum[i]) * 2 * a[i].t; 
    }
    cout << ans << "\n";
    return 0;
}