Uva 11300 By ACReaper

这道题真的是太妙了!模型的转化,建立确实重要!学习了。


定理

1.对于线段上的点,其中点到所有点的距离之和为最短。

证明:

点数为偶数,则在中间两点见的任意位置移动,距离都不变!(可取偏左,偏右都一样)

       点数为奇数,则中间点本来就存在,改点即为中间点


某型的建立:设xi表示第i点给第i - 1点的金币。则最小金币数即是|x1| + |x2| + .... + |xn|


代码如下:

#include <cstdio>
#include <algorithm>
using namespace std;
#define MAXN 1000000 + 10
long long A[MAXN];
long long C[MAXN];
int n;		  	 		 				  	 												
int main(){
	while(scanf("%d",&n) != EOF){
		long long tot =0;
		for(int i = 1; i <= n; i++){
			scanf("%lld", A + i);
			tot += A[i];
		}
		long long M = tot / n;
		C[0] = 0;
		for(int i = 1; i < n; i++){
			C[i] = C[i - 1] + A[i] - M;
		}
		sort(C,C + n);
		long long ans = 0,o = C[n / 2];
		for(int i =  0; i < n; i++){
			ans += abs(C[i] - o);
		}
		printf("%lld\n",ans);
	}
	return 0;
}

By ACReaper

2013 05 06


posted @ 2013-05-06 12:54  算法黑魔王  阅读(114)  评论(0编辑  收藏  举报