bzoj 1629: [Usaco2007 Demo]Cow Acrobats【贪心+排序】

仿佛学到了贪心的新姿势……
考虑相邻两头牛,交换它们对其他牛不产生影响,所以如果交换这两头牛能使这两头牛之间的最大值变小,则交换

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=50005;
int n,ans=-1e9,sum[N];
struct qwe
{
    int x,y;
}a[N];
inline bool cmp(const qwe &a,const qwe &b)
{
    return a.x-b.y<b.x-a.y;
}
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
int main()
{
    n=read();
    for(int i=1;i<=n;i++)
        a[i].x=read(),a[i].y=read();
    sort(a+1,a+n+1,cmp);
    for(int i=1;i<=n;i++)
    {
        if(sum[i-1]-a[i].y>ans)
            ans=sum[i-1]-a[i].y;
        sum[i]=sum[i-1]+a[i].x;
    }
    printf("%d",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lokiii/p/8987078.html