poj3045 Cow Acrobats (思维,贪心)
程序员文章站
2022-05-26 13:10:24
题目: "poj3045 Cow Acrobats" 解析: 贪心题,类似于国王游戏 考虑两个相邻的牛$i$,$j$ 设他们上面的牛的重量一共为$sum$ 把$i$放在上面,危险值分别为$x_1=sum s_i$,$ x_2=sum+w_i s_j$ 把$j$放在上面,危险值分别为$x_3=sum ......
题目:
解析:
贪心题,类似于国王游戏
考虑两个相邻的牛\(i\),\(j\)
设他们上面的牛的重量一共为\(sum\)
把\(i\)放在上面,危险值分别为\(x_1=sum-s_i\),$ x_2=sum+w_i-s_j$
把\(j\)放在上面,危险值分别为\(x_3=sum-s_j\), \(x_4=sum+w_j-s_i\)
若把j放在上面更优,则有\(max(x_3,x_4)<max(x_1,x_2)\)
有四种情况
\(x_3<x_1\)
\(x_3<x_2\)
\(x_4<x_1\)
\(x_4<x_2\)
显然\(x_3<x_2\),\(x_1>x_4\)
\(s_i\)和\(s_j\)关系不确定
所以一定有\(w_i+s_i>w_j+w_j\)
按\(w+s\)排序从小到大排序,大的在下面
代码:
很简单
#include <iostream> #include <algorithm> #include <cstdio> #define int long long using namespace std; const int n = 1e5 + 10; const int inf = 0x3f3f3f3f; int n; struct node { int w, s; bool operator <(const node &oth) const { return w + s < oth.w + oth.s; } } e[n]; template<class t>inline void read(t &x) { x = 0; char ch = getchar(); while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); return; } signed main() { read(n); for (int i = 1; i <= n; ++i) read(e[i].w), read(e[i].s); sort(e + 1, e + 1 + n); int sum = 0, ans = -inf; for (int i = 1; i <= n; ++i) ans = max(ans, sum - e[i].s), sum += e[i].w; cout << ans << endl; }
上一篇: 葱爆羊血这样做简单美味!