比较常见的题型,应该递推求解
#include<bits/stdc++.h> #define forn(i, n) for (int i = 0 ; i < int(n) ; i++) #define fore(i, s, t) for (int i = s ; i < (int)t ; i++) #define fi first #define se second #define all(x) x.begin(),x.end() #define pf2(x,y) printf("%d %d ",x,y) #define pf(x) printf("%d ",x) #define each(x) for(auto it:x) cout<<it<<endl; #define pii pair<int,int> using namespace std; typedef long long ll; const int maxn=2e6+5; const int maxm=2e5+5; const int inf=1e9; int n,m,a[maxn]; ll ans; vector<int> g[maxn]; int main(){ cin>>n>>m; for(int i=0;i<m;i++){ cin>>a[i]; if(i) ans+=abs(a[i]-a[i-1]); } for(int i=1;i<m;i++){ g[a[i]].push_back(a[i-1]); g[a[i-1]].push_back(a[i]); } cout<<ans<<' '; for(int i=2;i<=n;i++){ for(auto x:g[i]) { if(x!=i-1 && x!=i) { if(x<i) ans-=i-x-1,ans+=x; else ans-=x-i,ans+=x-1; } } for(auto x:g[i-1]) { if(x!=i && x!=i-1) { if(x<i) ans-=x,ans+=i-x-1; else ans-=x-1,ans+=x-i; } } cout<<ans<<' '; } cout<<endl; }