[USACO2007 Demo] Cow Acrobats
阿新 • • 發佈:2018-11-08
[題目連結]
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; }