[USACO2007 Demo] Cow Acrobats

[题目链接]

          https://www.lydsy.com/JudgeOnline/problem.php?id=1629

[算法]

        贪心

        考虑两头相邻的牛 , 它们的高度值和力量值分别为ax , ay , bx , by 

        我们发现 , 当ax + ay < bx + by时 , x排在前面比y排在前面更优

        也就是说 , 当序列中有相邻的牛使得ax + ay >= bx + by时 , 可以通过交换两头牛使得答案更优

        综上 , 按牛的(高度值 + 力量值)以关键字升序排序 , 即可

        时间复杂度 : O(NlogN)

[代码]

        

#include<bits/stdc++.h>
using namespace std;
#define MAXN 50010
typedef long long LL;
const LL inf = 1e18;

struct info
{
        LL x , y;
} a[MAXN];

int n;

template <typename T> inline void chkmax(T &x,T y) { x = max(x,y); }
template <typename T> inline void chkmin(T &x,T y) { x = min(x,y); }
template <typename T> inline void read(T &x)
{
    T f = 1; x = 0;
    char c = getchar();
    for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
    for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0';
    x *= f;
}
inline bool cmp(info a , info b)
{
        return a.x + a.y < b.x + b.y;
}

int main()
{
        
        read(n);
        for (int i = 1; i <= n; i++)
        {
                read(a[i].x);
                read(a[i].y);
        }
        sort(a + 1 , a + n + 1 , cmp);
        LL ans = -inf , now = 0;
        for (int i = 1; i <= n; i++)
        {
                chkmax(ans , now - a[i].y);
                now += a[i].x;        
        }
        cout<< ans << '\n';
        
        return 0;
    
}

猜你喜欢

转载自www.cnblogs.com/evenbao/p/9932435.html