笔记
//利用动态数组统计与i相邻的不相等的值; //每个值对答案的最大贡献是修改为与其相连的点的中间值; #include<cstdio> #include<vector> #include<algorithm> #define ll long long using namespace std; int n,m; vector<int> f[100001]; ll ans=0,be,af,zzz,a[100001]; ll max(ll a,ll b){return a>b?a:b;} int cha(ll a,ll b){ if(a>b) return (a-b); else return (b-a); } int main(){ freopen("note.in","r",stdin); freopen("note.out","w",stdout); scanf("%d%d",&n,&m); for(int i=1;i<=m;i++) scanf("%d",a+i); for(int i=1;i<=m;i++){ if(i>1&&a[i]!=a[i-1]) f[a[i-1]].push_back(a[i]); if(i<m&&a[i]!=a[i+1]) f[a[i+1]].push_back(a[i]); } zzz=0; for(int i=2;i<=m;i++) zzz+=(ll)cha(a[i],a[i-1]);//修改前所有差值; for(int i=1;i<=n;i++){ if(!f[i].size()) continue; sort(f[i].begin(),f[i].end()); ll y=f[i][f[i].size()/2]; be=0,af=0; for(int j=0;j<f[i].size();j++){ be+=(ll)cha(i,f[i][j]); //累加修改前i和与i相邻的数的差值; af+=(ll)cha(y,f[i][j]); //修改后 } ans=max(ans,be-af); //记录最大差值 } printf("%I64d\n",zzz-ans); fclose(stdin); fclose(stdout); return 0; }