Acwing 125. 耍杂技的牛(贪心)(从局部到全局)

地址:https://www.acwing.com/problem/content/description/127/

 

解析:

看到这种题,很容易想到,w,s的排序方法是关键点。

如果只排其中一个,不好想。

所以从局部出发,考虑交换两个相邻奶牛:

对于 i 牛 和 i+1 牛,我们对它俩进行分析。

发现,每个值都含有:W1+....W(i-1),所以去掉就是:

题目要求:最大风险值的最小可能值

所以我们使某个奶牛的风险值降低是没意义的,降低局部风险最大值才有意义。

假设 Wi-S(i+1)>W(i+1)-Si

变形得:Wi+Si>W(i+1)+S(i+1)

既然Wi-S(i+1)>W(i+1)-Si而且Wi-S(i+1)>-S(i+1)

那么不管交换前的i+1处是否是两者最大值,交换以后,方格里的两个值都会比之前的i+1处小,所以,局部最大值减小了,是一个可行的方式。

根据:Wi+Si>W(i+1)+S(i+1),只要 i 羊的w+s比j羊的w+s大,那么交换它俩,就会使局部最大值减小。

所以排序方式按w+s从小到大即可。

最后统计一遍

#include<cstdio>
#include<cstring>
#include<vector>
#include<set>
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int maxn=5e4+10,maxn2=31*maxn;//maxn·­±¶ 
struct node
{
    int w,s;
}st[maxn];
bool cmp(node a,node b)
{
    return a.s+a.w<b.s+b.w;
}
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<= n;i++)
    {
        cin>>st[i].w>>st[i].s;
    }
    sort(st+1,st+1+n,cmp);
    ll maxx=-st[1].s;
    ll sum=st[1].w;
    for(int i=2;i<=n;i++)
    {
        maxx=max(maxx,sum-st[i].s);
        sum+=st[i].w;
    }
    cout<<maxx<<endl;
}
原文地址:https://www.cnblogs.com/liyexin/p/13971317.html