2014
02-25

## Problem

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.

## The 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.

## The Output

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

## Sample Input

3
100
100
100
4
1
2
5
4

## Sample Output

0
4

Ai表示i号一开始持有的金币

……

====>|X1|+|X1-C1|+|X1-C2|+……+|Xn-1-Cn|的最小值

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 1000000+50
#define LL long long
LL C[MAXN];
LL A[MAXN];
int n;

int main()
{
while(~scanf("%d",&n)){
LL sum=0;
for(int i=0;i<n;i++){
scanf("%lld",&A[i]);
sum+=A[i];
}
LL M=sum/n;
sum=0;
for(int i=0;i<n-1;i++){
sum+=A[i];
C[i]=sum-(i+1)*M;
}
sort(C,C+n-1);
LL x=C[(n-1)/2];
LL ans=abs(x);
for(int i=0;i<n-1;i++){
ans+=abs(x-C[i]);
}
cout<<ans<<endl;
}
return 0;
}

1. #include <cstdio>
#include <cstring>

const int MAXSIZE=256;
//char store[MAXSIZE];
char str1[MAXSIZE];
/*
void init(char *store) {
int i;
store['A']=’V', store['B']=’W',store['C']=’X',store['D']=’Y',store['E']=’Z';
for(i=’F';i<=’Z';++i) store =i-5;
}
*/
int main() {
//freopen("input.txt","r",stdin);
//init(store);
char *p;
while(fgets(str1,MAXSIZE,stdin) && strcmp(str1,"STARTn")==0) {
if(p=fgets(str1,MAXSIZE,stdin)) {
for(;*p;++p) {
//*p=store[*p]
if(*p<’A’ || *p>’Z') continue;
if(*p>’E') *p=*p-5;
else *p=*p+21;
}
printf("%s",str1);
}
fgets(str1,MAXSIZE,stdin);
}
return 0;
}

2. 我还有个问题想请教一下，就是感觉对于新手来说，递归理解起来有些困难，不知有没有什么好的方法或者什么好的建议？

3. int half(int *array,int len,int key)
{
int l=0,r=len;
while(l<r)
{
int m=(l+r)>>1;
if(key>array )l=m+1;
else if(key<array )r=m;
else return m;
}
return -1;
}
这种就能避免一些Bug
l,m,r
左边是l,m;右边就是m+1,r;