AcWing 122 糖果传递

题目链接:https://www.acwing.com/problem/content/124/

环形均分纸牌,求出前缀和后转化为货仓选址问题

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;

const int maxn = 1000010;

int n;
ll a[maxn], sum[maxn], tot;

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	n = read(); tot = 0;
	for(int i=1;i<=n;++i){ a[i] = read(); tot += a[i]; }
	
	for(int i=1;i<=n;++i){
		a[i] -= (tot / n);
		sum[i] = sum[i-1] + a[i];
	}
	
	sort(sum + 1, sum + 1 + n);
	
	int Mid = sum[n/2 + 1];
	
	ll ans = 0;
	for(int i=1;i<=n;++i){
		ans += abs(sum[i] - Mid);
	}
	
	cout << ans << endl;
	
	return 0;
}
posted @ 2020-11-06 11:30  Tartarus_li  阅读(53)  评论(0编辑  收藏  举报