B. Customising the Track

题目链接:https://codeforces.com/contest/1543/problem/B

题意:

给定 n 个数,每次可以将某一个数减一,另一个数加一,进行若干次操作之后要使得 \({\sum_{i=1}^{n} \sum_{j=i+1}^{n} {\vert{a_i-a_j}\vert}}\) 最小,输出这个最小的\({\sum_{i=1}^{n} \sum_{j=i+1}^{n} {\vert{a_i-a_j}\vert}}\)

思路:

输入数的同时求总和 sum,输入完后求出总和模总个数的余数 res,即最佳情况为所有数平分 sum-res,然后其中 res 个数+1,不妨设这 res 数就是前 res 个数,此时\({\sum_{i=1}^{n} \sum_{j=i+1}^{n} {\vert{a_i-a_j}\vert}}\) 即为 \({res \times (n-res)}\)

代码:

#include <iostream>
using namespace std;
typedef long long ll;
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    int t;
    cin >> t;
    while (t--)
    {
        int n, x;
        ll sum = 0, res;
        cin >> n;
        for (int i = 0; i < n; i++)
            cin >> x, sum += x;
        res = sum % n;
        cout << res * (n - res) << endl;
    }
}

总结:

posted @ 2021-07-09 11:19  Wajor  阅读(91)  评论(0)    收藏  举报