如题:http://poj.org/problem?id=3262
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 4725 | Accepted: 1894 |
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.
Input
Lines 2.. N+1: Each line contains two space-separated integers, Ti and Di, that describe a single cow's characteristics
Output
Sample Input
6 3 1 2 5 2 3 3 2 4 1 1 6
Sample Output
86
Hint
Source
题目大意:给出几头牛每头牛在草地上吃草,T是牛回到仓库的时间,D是它每单位时间吃掉花的数量,每次运输一头牛需要花费T*2(来回),其他的牛会在这个时间里会不停的吃花,求最小的吃花数目,运完一头牛回来到另一头牛身边不花费时间。
贪心:这一题显然要考虑运输牛的顺序,什么顺序是最优的,和距离与吃花数有关,如果D/T小代表这头牛吃花数很少,反之吃花吃的最快,肯定要先运输。
我求和用了树状数组,很浪费时间,没有必要,只需要在输入的时候求出所有牛D的总值,每次累加减掉那个要运走的牛的D就行了
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define ll _int64
struct node
{
int T,D;
};
node a[100005];
ll c[100005];
int N;
int lowbit(int x)
{
return x&(x^(x-1));
}
ll sum(int end)
{
ll t=0;
while(end>0)
{
t+=c[end];
end-=lowbit(end);
}
return t;
}
void update(int pos,int num)
{
while(pos<=N)
{
c[pos]+=num;
pos+=lowbit(pos);
}
}
int cmp(node &a,node &b)
{
float x=(float)a.D/a.T;
float y=(float)b.D/b.T;
return x>y;
}
int main()
{
int i;
scanf("%d",&N);
for(i=1;i<=N;i++)
scanf("%d%d",&a[i].T,&a[i].D);
sort(a+1,a+1+N,cmp);
for(i=1;i<=N;i++)
update(i,a[i].D);
ll res=0;
for(i=1;i<=N;i++)
{
res+=(sum(N)-sum(i))*a[i].T*2;
}
printf("%I64d\n",res);
return 0;
}