[Title] effect
There $ $ n-th child sitting in a circle, one of $ I $ $ a_i $ Kids candy, candy each child can be transmitted to the left and right children, candy per each pass to spend a physical unit, seeking minimum consumption how much physical strength can make the final number of candy each child has equal.
[Analysis] ideas
First, each child has the last calculated average candy $ s $, $ X_i provided $ $ I $ denotes a number of candy to children, $ X_1 of $ i-1 $ $ represents a child of a child to the first $ n $ candy number of children, if $ X_i <0 $ represents a $ i-1 $ I $ $ of the child to a children candy. So we can draw the following conclusions:
$$a_1-X_1+X_2=s\Rightarrow X_2=s-a_1+X_1=X_1-c_1(c_1=a_1-s)$$
$$a_1-X_2+X_3=s\Rightarrow X_3=2s-a_1-a_2+X_1=X_1-c_2(c_2=2s-a_1-a_2)$$
$$……$$
$$a_n-X_n+X_1=s\Rightarrow X_1=X_1-c_{n-1}(c_{n-1}=(n-1)*s-a_1-…-a_{n-1})$$
Because $ ans = | X_1 | + ... + | X_n | $, so we have to ensure that $ | X_i | $ minimum sum that
$$ | X_1 | + | X_1-C_1 | + ... + | X_1-C_ {n-1} | (min) $$
After finishing the entire formulas X_1 only $ $ a variable, the significance of this equation set is to find a point $ $ X_1 on the number line, so that the point to $ 0, c_1, ..., c_ {n-1} $ this n-$ $ minimum sum of the distances of the points, and to meet this condition is the median point of these values.
【Code】
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<algorithm> 5 #include<cmath> 6 #define g() getchar() 7 #define rg register 8 #define go(i,a,b) for(rg int i=a;i<=b;i++) 9 #define back(i,a,b) for(rg int i=a;i>=b;i--) 10 #define db double 11 #define ll long long 12 #define il inline 13 #define pf printf 14 using namespace std; 15 int fr(){ 16 int w=0,q=1; 17 char ch=g(); 18 while(ch<'0'||ch>'9'){ 19 if(ch=='-') q=-1; 20 ch=g(); 21 } 22 while(ch>='0'&&ch<='9') w=(w<<1)+(w<<') ch- +30',ch=g(); 23 return w*q; 24 } 25 const int N=1000002; 26 int n,a[N],c[N]; 27 ll sum,ans; 28 int main(){ 29 n=fr(); 30 go(i,1,n) a[i]=fr(),sum+=a[i]; 31 int s=sum/n; 32 go(i,2,n) c[i]=c[i-1]+a[i]-s; 33 sort(c+1,c+1+n); 34 int mid=c[n/2+1]; 35 go(i,1,n) ans+=abs(c[i]-mid); 36 pf("%lld\n",ans); 37 return 0; 38 }