Files
python/TangDou/LanQiaoBei/ZhongGaoJi/LanQiao15STEMA202401/5.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

66 lines
1.9 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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