You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#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的量)
如果一下子没用了,就继续向后做同样的操作
举栗子思考:
3
10 1 1
3
5 1 6
3
1 5 6
*/
for (int i = 1; i <= n; i++) {
int d = a[i] - avg; // 差值,注意:这个差值可能是正的,也可能是负的
total += abs(d);
for (int j = i + 1; j <= n; j++) { // 枚举i的所有后位的小朋友,如果当前i位上的小朋友需要糖果或者多出来糖果时应该把
// 多出来的糖果分给哪些小朋友,或者,少出来的糖果需要从哪些小朋友那里要过来
// 向后找比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(abs(d), a[j] - avg);
a[i] += x;
a[j] -= x;
d += x;
}
if (d == 0) break;
}
}
cout << total << endl;
return 0;
}