使用vector记录一个数两边的数字,然后把这些数字排序,选中间的那个当做修改后的值.
#include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std; const int MAX = ;
int a[MAX];
vector<int>ne[MAX];//相邻页
int fabs(int x)
{
if(x<)x=-x;
return x;
}
int main()
{
int n,m;
int i,j;
int tmp1,tmp2;
long long sum1,sum2,maxdis;
long long ans;
while(scanf("%d %d",&n,&m)!=EOF)
{
for(i=;i<m;i++)
scanf("%d",&a[i]); for(i=;i<m-;i++)//statistics
{
if(a[i]!=a[i+])
{
ne[a[i]].push_back(a[i+]);
ne[a[i+]].push_back(a[i]);
}
} maxdis = ;
ans=;
for(i=;i<=n;i++)//sort
{
if(!ne[i].empty())
{
sort(ne[i].begin(),ne[i].end());
tmp2 = ne[i].size()/;
tmp1 = ne[i][tmp2];
sum1=;
sum2=;
for(j=;j<ne[i].size();j++)
{
sum1+=fabs(ne[i][j]-tmp1);
sum2+=fabs(ne[i][j]-i);
}
maxdis = max(maxdis,sum2-sum1);
ans+=sum2;// total turn page former
}
}
printf("%I64d\n",ans/-maxdis);
for(i=;i<=n;i++)
ne[i].clear();
}
return ;
}