1. 程式人生 > >糖果傳遞 HYSBZ

糖果傳遞 HYSBZ

有n個小朋友坐成一圈,每人有ai個糖果。每人只能給左右兩人傳遞糖果。每人每次傳遞一個糖果代價為1。

Input

第一行一個正整數nn<=1'000'000,表示小朋友的個數.

接下來n行,每行一個整數ai,表示第i個小朋友得到的糖果的顆數.

Output

求使所有人獲得均等糖果的最小代價。

Sample Input

4 1 2 5 4

Sample Output

4

中位數的性質即可;

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<bitset>
#include<ctime>
#include<deque>
#include<stack>
#include<functional>
#include<sstream>
//#include<cctype>
//#pragma GCC optimize("O3")
using namespace std;
#define maxn 1000004
#define inf 0x3f3f3f3f
#define INF 999999999999
#define rdint(x) scanf("%d",&x)
#define rdllt(x) scanf("%lld",&x)
typedef long long  ll;
typedef unsigned long long ull;
typedef unsigned int U;
#define ms(x) memset((x),0,sizeof(x))
const int mod = 1e9 + 7;
#define Mod 20100403
#define sq(x) (x)*(x)
#define eps 1e-7
typedef pair<int, int> pii;
#define pi acos(-1.0)
#define REP(i,n) for(int i=0;i<(n);i++)

inline int rd() {
	int x = 0;
	char c = getchar();
	bool f = false;
	while (!isdigit(c)) {
		if (c == '-') f = true;
		c = getchar();
	}
	while (isdigit(c)) {
		x = (x << 1) + (x << 3) + (c ^ 48);
		c = getchar();
	}
	return f ? -x : x;
}

ll gcd(ll a, ll b) {
	return b == 0 ? a : gcd(b, a%b);
}
ll sqr(ll x) { return x * x; }

int n;
int a[maxn];
int b[maxn];

int main()
{
	//ios::sync_with_stdio(false);
	rdint(n);
	int C;
	ll sum = 0;
	for (int i = 1; i <= n; i++) {
		rdint(a[i]); sum += (ll)a[i];
	}
	C = (ll)sum / (ll)n;
	b[0] = 0;
	for (int i = 1; i < n; i++) {
		b[i] = b[i - 1] + a[i] - C;
	}
	sort(b, b + n);
	int tmp = b[n / 2];
	ll ans = 0;
	for (int i = 0; i < n; i++) {
		ans += (ll)abs(tmp - b[i]);
	}
	cout << ans << endl;
	return 0;
}