USACO2007 Protecting the Flowers /// 比值 前缀和 oj21161

题目大意:

 有N (2 ≤ N ≤ 100,000) 头牛偷吃花

将牛赶回牛棚需Ti minutes (1 ≤ Ti ≤ 2,000,000)

每头牛每分钟能吃Di (1 ≤ Di ≤ 100) 朵花

则赶牛的来回需2*Ti minutes (Ti to get there and Ti to return)

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

Output

* Line 1: A single integer that is the minimum number of destroyed flowers

Sample Input

6
3 1
2 5
2 3
3 2
4 1
1 6

Sample Output

86

一开始用DFS 结果TLE

#include <bits/stdc++.h>
using namespace std;
long long n,ans,sum;
struct cow
{
    double t,f,s;
}a[100005];
bool cmp(struct cow a,struct cow b)
{
    return a.s>b.s;
}
int main()
{
    scanf("%lld",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%lf%lf",&a[i].t,&a[i].f);
        a[i].s=a[i].f/a[i].t;    ///s为每分钟吃花的数量与赶牛时间的比值     
        选取耗时少且吃花多的牛能最大限度地减少损失 则应先赶s更大的牛
        sum+=a[i].f;    ///利用前缀和 省略每次重新循环计量的浪费
    }
    sort(a+1,a+1+n,cmp);
    for(int i=1;i<=n;i++)
    {
        sum-=a[i].f;
        ans+=a[i].t*sum*2;
    }
    printf("%lld
",ans);

    return 0;
}        
View Code
原文地址:https://www.cnblogs.com/zquzjx/p/8359509.html