|
|
|
@ -0,0 +1,59 @@
|
|
|
|
|
#include <bits/stdc++.h>
|
|
|
|
|
using namespace std;
|
|
|
|
|
const int N = 10010;
|
|
|
|
|
int a[N];
|
|
|
|
|
int sum, avg, total;
|
|
|
|
|
int main() {
|
|
|
|
|
int n;
|
|
|
|
|
cin >> n;
|
|
|
|
|
|
|
|
|
|
for (int i = 1; i <= n; i++) {
|
|
|
|
|
cin >> a[i];
|
|
|
|
|
sum += a[i];
|
|
|
|
|
}
|
|
|
|
|
if (sum % n) {
|
|
|
|
|
cout << -1 << endl;
|
|
|
|
|
exit(0);
|
|
|
|
|
}
|
|
|
|
|
avg = sum / n; // 平均数
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
算法思路
|
|
|
|
|
1、求出平均数avg
|
|
|
|
|
2、枚举每个数字:
|
|
|
|
|
(1) 如果当前数字比avg大,不断向后面找出比avg小的数,将自己多出的部分传递给这个数=min(超过avg的量,少于avg的量)
|
|
|
|
|
如果一下子没用了,就继续向后做同样的操作
|
|
|
|
|
(2) 如果当前数字比avg小,不断向后面找出比avg大的数,将自己少出的部分传递给这个数=min(超过avg的量,少于avg的量)
|
|
|
|
|
如果一下子没用了,就继续向后做同样的操作
|
|
|
|
|
|
|
|
|
|
举栗子思考:
|
|
|
|
|
10 1 1
|
|
|
|
|
5 1 6
|
|
|
|
|
1 5 6
|
|
|
|
|
*/
|
|
|
|
|
for (int i = 1; i <= n; i++) {
|
|
|
|
|
int d = a[i] - avg; // 差值,注意:这个差值可能是正的,也可能是负的
|
|
|
|
|
total += d;
|
|
|
|
|
|
|
|
|
|
int j = i + 1;
|
|
|
|
|
while (d != 0 && j <= n) {
|
|
|
|
|
// 向后找出,比avg小的
|
|
|
|
|
if (d > 0 && a[j] < avg) {
|
|
|
|
|
int x = min(d, avg - a[j]);
|
|
|
|
|
a[i] -= x;
|
|
|
|
|
a[j] += x;
|
|
|
|
|
d -= x;
|
|
|
|
|
}
|
|
|
|
|
// 向后找出,比avg大的
|
|
|
|
|
if (d < 0 && a[j] > avg) {
|
|
|
|
|
int x = min(d, a[j] - avg);
|
|
|
|
|
a[i] += x;
|
|
|
|
|
a[j] -= x;
|
|
|
|
|
d += x;
|
|
|
|
|
}
|
|
|
|
|
j++;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
cout << total << endl;
|
|
|
|
|
return 0;
|
|
|
|
|
}
|