题目来源: http://acm.pku.edu.cn/JudgeOnline/problem?id=3262
首先这是一个贪心算法。证明我就不会了。大概解释一下解题思路
对于2个cow,肯定要有一个赶回去的先后顺序。为了使损失最小化,我们比较d1,t1,d2,t2。
如果d1*t2>d2*t1,即让奶牛1等待是不合理的,因为这样会损坏花更严重些。所以奶牛1要比奶牛2先回。
这样一个排序,就可以得到所有的奶牛顺序。再按照这个顺序计算总的消耗。这里有点技巧,大概有点dp的思想。
代码:

Code
1
#include <iostream>
2
3
using namespace std;
4
5
struct pp
6

{
7
__int64 t;
8
__int64 d;
9
};
10
11
int cmp(const void *a,const void *b)
12

{
13
pp aa=(*(pp *)a);
14
pp bb=(*(pp *)b);
15
return aa.d*bb.t-aa.t*bb.d;
16
}
17
18
pp all[100001];
19
20
int main()
21

{
22
int n,i=0;
23
freopen("test.txt","r",stdin);
24
while (scanf("%d",&n)!=EOF&&n)
25
{
26
//memset(sum,0,sizeof(sum));
27
i=0;
28
while(n--)
29
{
30
scanf("%lld%lld",&all[i].t,&all[i].d);
31
i++;
32
}
33
qsort(all,i,sizeof(pp),cmp);
34
35
__int64 ans=0,sum=0;
36
for(int j=1;j<i;j++)
37
{
38
sum+=all[j-1].d;
39
ans+=sum*all[j].t;
40
}
41
printf("%lld\n",ans*2);
42
}
43
}
做题的时候,那个i=0的初始化少写了。调试了n长的时间,fent。