跳到正文

个人记录

代码分析3 P2123

fhzm_zt约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年8月26日
收录
2026年8月27日
更新
2026年8月31日
篇幅
约 2 分钟
获赞
1

版本

  1. v1当前
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 50000;
struct Secretary//记录
{
    int a, b, d;//a左手,b右手
} sty[N + 5];
inline bool cmp(const Secretary &x, const Secretary &y)
{
    if (x.d != y.d)//先按d来排序
        return x.d < y.d;
    if (x.d <= 0)//d<=0时,按a排序
        return x.a < y.a;
    else
        return x.b > y.b;//按b排序
}
int main()
{
    int T;//多组数据
    scanf("%d", &T);
    while (T--)
    {
        int n;//人数
        scanf("%d", &n);
        for (int i = 1; i <= n; ++i)//计算每人的d
        {
            scanf("%d%d", &sty[i].a, &sty[i].b);
            sty[i].d = sty[i].a - sty[i].b;
            if (sty[i].d)
                sty[i].d /= abs(sty[i].d);
        }
        sort(sty + 1, sty + n + 1, cmp);
        ll c = 0, s = 0;//c奖金,s当前左手的和
        for (int i = 1; i <= n; ++i)//按顺序求每人的奖金
        {
            s += sty[i].a;//累加左手
            c = max(c, s) + sty[i].b;//算奖金,max(当前上一个人奖金,左手和)+右手
        }
        printf("%lld\n", c);
    }
}//没有return 0;
原文