2020.7.30新更新，之前不会用$\LaTeX$，现在加上了……

## 解说

$X_2=ave-A_1+X_1$

$X_3=ave-A_2+X_2=2 \times ave-A2-A1+X1$

$X4=ave-A3+X3=3 \times ave-A3-A2-A1+X1$

$\dots$

$X_n=(n-1) \times ave-A_{n-1}-\dots-A_2-A_1+X_1$

$C_1=0$

$X_2=X_1-C_2$

$X_3=X_1-C_3$

$X_4=X_1-C_4$

$\dots$

$X_n=X_1-C_n$

## 代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=1000000+2;
typedef long long ll;//数据范围显示要开long long
ll a[maxn],sum,ave,c[maxn];
int n;
int main(){
while(scanf("%d",&n)!=EOF){
sum=0;
for(int i=1;i<=n;i++) {
scanf("%lld",&a[i]);
sum+=a[i];
}
ave=sum/n;
c[1]=a[1]-ave;
for(int i=2;i<=n;i++) c[i]=c[i-1]+a[i]-ave;
//上面这两行用于计算Ci
sort(c+1,c+1+n);
ll mid=c[n/2];//中位数
ll ans=0;
for(int i=1;i<=n;i++) ans+=abs(mid-c[i]);
printf("%lld\n",ans);
}
return 0;
}


## 尾声

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=1000000+2;
typedef long long ll;
ll a[maxn],sum,ave,c[maxn];
int n;
int main(){
while(scanf("%d",&n)!=EOF){
sum=0;
for(int i=1;i<=n;i++) {
scanf("%lld",&a[i]);
sum+=a[i];
}
ave=sum/n;
c[1]=a[1]-ave;
for(int i=2;i<=n;i++) c[i]=c[i-1]+a[i]-ave;
sort(c+1,c+1+n);
ll mid=c[n/2];
ll ans1=0;
for(int i=1;i<=n;i++) ans1+=abs(mid-c[i]);
mid=c[n/2+1];
ll ans2=0;
for(int i=1;i<=n;i++) ans2+=abs(mid-c[i]);
printf("%lld\n",min(ans1,ans2));
}
return 0;
}


posted @ 2020-07-30 19:52  DarthVictor  阅读(108)  评论(2编辑  收藏  举报