跳到正文

题解

CF2014C Robin Hood in Town tj

_colin1112_约 3 分钟
原文
文章信息与版本

文章信息

发布
2024年10月19日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 3 分钟
获赞
1
题目
CF2014C

版本

  1. v1当前

思路

考虑二分答案,二分对象是新发现的黄金 xx。

对于二分出来的 xx,每次计算不快乐的人数,如果 严格大于 总人口 nn 的一半,说明当前的 xx 是可行的,需要再次缩小范围继续枚举;否则,则扩大范围,将 xx 增大。

最后二分出来的最小的 xx 就为答案。

注意:00 也是可行的答案,以及 n≤2n \leq 2 时显然不可行,要输出 −1-1。

Code

C++
#include <bits/stdc++.h>
#define ll long long
#define endl '\n'

using namespace std;
const int E = 1e6 + 5;
ll t, n;
ll a[E];
inline bool check(ll x)
{
    ll max1 = -1e18, id = 0, sum = 0;
    for (int i = 1; i <= n; i++)
        if (max1 > a[i])
            max1 = a[i], id = i, sum += a[i];
        else
            sum += a[i];
    a[id] += x, sum += x;
    double avg = sum * 1.0 / n;
    ll ans = 0;
    for (int i = 1; i <= n; i++)
        if (a[i] < avg / 2.0)
            ans++;
    // cout << avg << endl;
    a[id] -= x;
    return ans > n / 2;
}
int main()
{
    cin >> t;
    while (t--)
    {
        cin >> n;
        for (int i = 1; i <= n; i++)
            cin >> a[i];
        if (n <= 2)
        {
            cout << -1 << endl;
            continue;
        }
        ll l = 0, r = 1e18, ans = -1;
        while (l <= r)
        {
            ll mid = l + r >> 1;
            if (check(mid))
                r = mid - 1, ans = mid;
            else
                l = mid + 1;
        }
        cout << ans << endl;
    }
    return 0;
}
原文