[AcWing] 125. 耍杂技的牛(C++实现)贪心---推公式例题

[AcWing] 125. 耍杂技的牛(C++实现)贪心---推公式例题,第1张

[AcWing] 125. 耍杂技的牛(C++实现)贪心---推公式例题

[AcWing] 125. 耍杂技的牛(C++实现)贪心---推公式例题
  • 1. 题目
  • 2. 读题(需要重点注意的东西)
  • 3. 解法
  • 4. 可能有帮助的前置习题
  • 5. 所用到的数据结构与算法思想
  • 6. 总结

1. 题目


2. 读题(需要重点注意的东西)

思路:

贪心 -----> 每次在当前的选法中,选择能选的情况中的最优解

解题思路:


代码实现思路:
按上述结论将每头牛从小到大叠罗汉(排序),然后求出最大的风险即可。

3. 解法

---------------------------------------------------解法---------------------------------------------------

#include 
#include 

using namespace std;

typedef pair 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("%dn", res);

    return 0;
}

可能存在的问题(所有问题的位置都在上述代码中标注了出来)

4. 可能有帮助的前置习题 5. 所用到的数据结构与算法思想
  • 贪心
6. 总结

贪心思想、推公式的例题,理解思想并自行推导出公式。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5690535.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存