[训练指南] 第一章 例题3 分金币 (Spreading the wealth,Uva 11300)

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#define maxn 1000010
using namespace std;
typedef long long ll;
ll n;
ll a[maxn];
ll tot;
ll m;
ll c[maxn];
int main()
{
	while(scanf("%lld",&n)==1)
	{
		memset(a,0,sizeof(a));
		tot = 0;
		for(int i=1;i<=n;i++)
		{
			scanf("%lld",&a[i]);
			tot+=a[i];
		}
		m = tot / n;
		for(int i=1;i<=n;i++)
		c[i]=c[i-1]+a[i]-m;
		sort(c+1,c+1+n);
		ll x1 = c[n/2];
		ll ans = 0;
		for(int i=1;i<=n;i++)ans+=abs(x1-c[i]);
		printf("%lld\n",ans);
	}
	return 0;
}
优化
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#define maxn 1000010
using namespace std;
typedef long long ll;
ll n;
//ll a[maxn];
ll tot;
ll m;
ll c[maxn];
int main()
{
	while(scanf("%lld",&n)==1)
	{
		//memset(a,0,sizeof(a));
		ll a = 0;
		tot = 0;
		for(int i=1;i<=n;i++)
		{
			//scanf("%lld",&a[i]);
			scanf("%lld",&a);
			tot+=a;
			c[i]+=c[i-1]+a;
		}
		m = tot / n;
		for(int i=1;i<=n;i++)
		//c[i]=c[i-1]+a[i]-m;
		c[i]-=m*i;
		sort(c+1,c+1+n);
		ll x1 = c[n/2];
		ll ans = 0;
		for(int i=1;i<=n;i++)ans+=abs(x1-c[i]);
		printf("%lld\n",ans);
	}
	return 0;
}

你可能感兴趣的:([训练指南] 第一章 例题3 分金币 (Spreading the wealth,Uva 11300))