# 题目

## Description

A Communist regime is trying to redistribute wealth in a village.
They have have decided to sit everyone around a circular table.
First, everyone has converted all of their properties to coins of equal value, such that the total number of coins is divisible by the number of people in the village.
Finally, each person gives a number of coins to the person on his right and a number coins to the person on his left, such that in the end, everyone has the same number of coins.
Given the number of coins of each person, compute the minimum number of coins that must be transferred using this method so that everyone has the same number of coins.

## Input

There is a number of inputs. Each input begins with n (n < 1000001), the number of people in the
village. n lines follow, giving the number of coins of each person in the village, in counterclockwise
order around the table. The total number of coins will fit inside an unsigned 64 bit integer.

## Output

For each input, output the minimum number of coins that must be transferred on a single line.

3
100
100
100
4
1
2
5
4

0
4

# 题解

`n` 个人循环给金币,使大家最后的金币数一样

• 对于第 `1` 个: `M = A1 - x1 + xn`
• 对于第 `2` 个: `M = A2 - x2 + x1`
可化为: `x2 = A2 - M + x1`
• 对于第 `3` 个: `M = A3 - x3 + x2`
可化为: `x3 = A3 - M + x2 = A2 + A3 - 2M + x1`
• ……
• 对于第 `n` 个: `xn = A2 + …… + An - (n-1)M + x1`

# 代码

```/*
By:OhYee
Github:OhYee
Blog:http://www.oyohyee.com/
Email:oyohyee@oyohyee.com

かしこいかわいい？
エリーチカ！

*/
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <map>
#include <set>
#include <list>
#include <queue>
#include <stack>
#include <string>
#include <vector>
#include <bitset>
#include <functional>

using namespace std;

const int maxn = 1000005;

long long a[maxn];

bool Do() {
int n;
if(!(cin >> n))
return false;

long long sum = 0;
for(int i = 0;i < n;i++) {
long long t;
cin >> t;
sum += t;
if(i == 0)
a = t;
else
a[i] = sum - a;
}
sum /= n;
for(int i = 0;i < n;i++) {
if(i == 0)
a = 0;
else
a[i] -= i*sum;
}
sort(a,a + n);

sum = 0;
for(int i = 0;i < n;i++)
sum += abs(a[i] - a[n / 2 - 1]);

cout << sum << endl;
return true;
}

int main() {
while(Do());
return 0;
}
```