CF1931B题解

· · 题解

思路

我们首先要计算出 mid=\frac{\sum a_i}n,因为这是我们的目标。由于 i 必须 <j,所以我们可以从前往后贪心。如果 a_i>mid,那就把多余的 a_i-mid 单位的水倒到下一桶 a_{i+1} 里;如果 a_i<mid,那说明把前面所有多余的水都给它都不够,这时候无解。

代码

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int t, n, a[200005];
ll sum, x;
int main () {
    ios::sync_with_stdio (0);
    cin.tie (0);
    cout.tie (0);
    cin >> t;
    while (t --) {
        cin >> n;
        x = sum = 0;
        for (int i = 0; i < n; ++ i)
            cin >> a[i], sum += a[i];
        sum /= n;
        for (int i = 0; i < n; ++ i) {
            a[i] += x;
            if (a[i] < sum) {
                cout << "NO\n";
                goto there;
            }
            x = a[i] - sum;
        }
        cout << "YES\n";
there:
        ;
    }
    return 0;
}