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 cows were in his garden eating his beautiful flowers. Wanting to minimize the subsequent damage, FJ decided to take immediate action and transport the cows back to their barn. Each cow i is at a location that is Ti minutes (1 <= Ti <= 2,000,000) away from the 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 the barn. Moving cow i to the barn requires 2*Ti minutes (Ti to get there and Ti to return). 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.
Input
* Line 1: A single integer
N * Lines 2..N+1: Each line contains two space-separated integers, Ti and Di, that describe a single cow's characteristics
第1行輸入N,之後N行每行輸入兩個整數Ti和Di.
Output
* Line 1: A single integer that is the minimum number of destroyed flowers
一個整數,表示最小數量的花朵被吞食.
Sample Input
3 1
2 5
2 3
3 2
4 1
1 6
Sample Output
HINT
約翰用6,2,3,4,1,5的順序來運送他的奶牛.
Source
題解:
簡單的貪心,最好的方法一定是先運送距離短,喫的多的奶牛。於是可以按照奶牛的飯量和運送時間的比值進行排序了,之後再用前綴和之類的求一下就可以了。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN=100001;
struct xx
{
int d,t;
double s;
}a[MAXN];
bool cmp(xx a,xx b)
{
return a.s>b.s;
}
long long tot,ans;
int main(int argc, char *argv[])
{
int n,m,i,j;
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d%d",&a[i].t,&a[i].d),a[i].s=a[i].d*1.0/a[i].t*1.0,tot+=a[i].d;
sort(a+1,a+n+1,cmp);
for(i=1;i<=n;i++) tot-=a[i].d,ans+=a[i].t*2*tot;
printf("%lld\n",ans);
return 0;
}