Test instructions: Give you the number of M, and then you choose a number to replace it with another number, making. Minimum. Note that the selected number must be replaced by the same number in the M number as it is.
Idea: Use a vector to record the number of each number adjacent to it, if the same does not have to be recorded, and then traverse to replace it with a number of adjacent to the number of the median number of all numbers and take the smallest can be.
1#include <cstdio>2#include <iostream>3#include <cstring>4#include <vector>5#include <algorithm>6#include <cmath>7 #defineMAXN 1000108 #definell __int649 using namespacestd;Ten Const intMod=1000000007; One Const intinf=1<< -; A - intn,m; - ll A[MAXN]; the intSUM[MAXN]; - intP[MAXN]; -vector<int>G[MAXN]; - + intMain () - { +Cin>>n>>m; All sum=0, max1=0; at for(intI=1; i<=m; i++) - { -scanf"%i64d",&a[i]); -max1=Max (max1,a[i]); - if(i==1)Continue; - if(a[i]!=a[i-1]) in { -g[a[i-1]].push_back (A[i]); toG[a[i]].push_back (a[i-1]); +Sum+=abs (a[i]-a[i-1]); - } the } *ll ans=sum; $ for(intI=1; i<=max1; i++)Panax Notoginseng { -ll tem=sum; the if(!g[i].size ())Continue; + sort (G[i].begin (), G[i].end ()); A intXx=g[i][g[i].size ()/2]; the for(intj=0; j< (int) G[i].size (); J + +) + { -tem+= (ABS (Xx-g[i][j])-abs (i-g[i][j])); $ } $ans=min (ans,tem); - } -printf"%i64d\n", ans); the return 0; -}View Code
Codeforces C. Ryouko ' s Memory Note