[AcWing] 125. 耍杂技的牛(C++实现)贪心---推公式例题
1. 题目
2. 读题(需要重点注意的东西)
思路:
贪心 -----> 每次在当前的选法中,选择能选的情况中的最优解
解题思路:
代码实现思路:
按上述结论将每头牛从小到大叠罗汉(排序),然后求出最大的风险即可。
3. 解法
---------------------------------------------------解法---------------------------------------------------
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 50010;
int n;
PII cow[N];
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i ++ )
{
int s, w;
scanf("%d%d", &w, &s);
cow[i] = {w + s, w};
}
sort(cow, cow + n);
int res = -2e9, sum = 0;
for (int i = 0; i < n; i ++ )
{
int s = cow[i].first - cow[i].second, w = cow[i].second;
res = max(res, sum - s);
sum += w;
}
printf("%d\n", res);
return 0;
}
可能存在的问题(所有问题的位置都在上述代码中标注了出来)
4. 可能有帮助的前置习题
5. 所用到的数据结构与算法思想
- 贪心
6. 总结
贪心思想、推公式的例题,理解思想并自行推导出公式。