poj 3045 叠罗汉问题 贪心算法

题意:将n头牛叠起来,每头牛的力气 s体重 w  倒下的风险是身上的牛的体重的和减去s 求最稳的罗汉倒下去风险的最大值 

思路:

     将s+w最大的放在下面,从上往下看

解决问题的代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include <algorithm>
using namespace std;

int n;
struct node {
    int w, s;
    bool operator< (const node b) const
    {
        return w + s < b.w + b.s;
    }
}cow[50005];

int main()
{
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        scanf("%d%d", &cow[i].w,&cow[i].s);
    }
    sort(cow, cow + n);
    int sum = 0;
    int ans = -0x3f3f3f3f;
    for (int i = 0; i < n; i++)
    {
        ans = max(ans, sum - cow[i].s);
        sum += cow[i].w;
    }
    printf("%d
", ans);
    return 0;
}

其中要学习的一个知识点是:

 bool operator< (const node b) const
    {
        return w + s < b.w + b.s;
    }

这个重载 <是因为在 sort函数中会用到这个比较

君子知命不惧,自当日日自新
原文地址:https://www.cnblogs.com/xuxiaojin/p/9414843.html