1. 程式人生 > 其它 >B. Customising the Track

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;
    }
}

總結: