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.
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的量)
如果一下子没用了,就继续向后做同样的操作
举栗子思考:
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 ;
}