算法竞赛入门经典 分金币

算法竞赛入门经典 分金币

/*
	Name: 分金币 
	Copyright: 刘汝佳 
	Author: Analyst 
	Date: 28/02/14 00:31
	Description: dev-cpp 5.5.3
*/
#include <iostream>
#include <algorithm>
using namespace std;

const int maxn = 1000000+10;
long long A[maxn], C[maxn], tot, M;

int main()
{
	int n;
	
	while (scanf("%d", &n) == 1)        //输入数据大,scanf()比cin快 
	{
		tot = 0;
		for (int i = 1; i <= n; ++i)
		{
			scanf ("%lld", &A[i]);      //%lld输入long long 
			tot += A[i];
		}
		
		M = tot / n;
		C[0] = 0;
		for (int i = 1; i < n; ++i)
			C[i] = C[i-1] + A[i] - M;   //递推C数组 
		sort(C, C+n);
		
		long long x1 = C[n/2], ans = 0; //x1中位数 
		
		for (int i = 0; i < n; ++i)     //转手金币数 
			ans += abs(x1-C[i]);
		
		printf("%lld\n",ans); 
	}
	return 0;
} 

ps:

主要用数轴上的无数点到某个点的最短距离来抽象化。(引入:中位数概念)

同时需要理解递推公式:

for (int i = 1; i < n; ++i)
C[i] = C[i-1] + A[i] - M;   //递推C数组


你可能感兴趣的:(算法竞赛入门经典 分金币)