1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #include<iostream> #include<cstdio> #include<cmath> #define ll long long #define lowbit(x) (x&(-x)) using namespace std; const int N=5e5+10,M=5e4+10; template<class T> inline void read(T &x) { x=0;int f=0; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=1;ch=getchar();} while(ch>='0'&&ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=getchar(); if(f)x=~x+1; } template<class T,class ...T1> inline void read(T &x,T1 &...x1) { read(x),read(x1...); } int n,m; int tot; int a[N],t[N]; struct Op { int t,p,x,y; }q[N+(M<<2)],w[N+(M<<2)]; ll res[M],ans[M]; inline void add(int x,int k) { for(;x<=n;x+=lowbit(x))t[x]+=k; } inline int ask(int x) { int res=0; for(;x;x-=lowbit(x))res+=t[x]; return res; } void solve(int l,int r) { if(l>=r)return ; int mid=l+r>>1; solve(l,mid),solve(mid+1,r); int i=l,j=mid+1,k=l; auto lm=[&](){add(q[i].x,q[i].y),w[k++]=q[i++];}; auto mr=[&](){ans[q[j].t]+=(ask(n)-ask(q[j].x))*q[j].y,w[k++]=q[j++];}; while(i<=mid&&j<=r) { if(q[i].p<=q[j].p)lm(); else mr(); } while(i<=mid)lm(); while(j<=r)mr(); for(int i=l;i<=mid;i++)add(q[i].x,-q[i].y); i=mid,j=r; auto ml=[&](){add(q[i].x,q[i].y),i--;}; auto rm=[&](){ans[q[j].t]+=ask(q[j].x-1)*q[j].y,j--;}; while(i>=l&&j>=mid+1) { if(q[i].p>=q[j].p)ml(); else rm(); } while(i>=l)ml(); while(j>=mid+1)rm(); for(int i=l;i<=mid;i++)add(q[i].x,-q[i].y); for(int i=l;i<=r;i++)q[i]=w[i]; } int main() { read(n,m); for(int i=1;i<=n;i++)read(a[i]),q[++tot]={0,i,a[i],1},res[0]+=abs(a[i]-i); for(int i=1;i<=m;i++) { int x,y; read(x,y); res[i]=res[i-1]; res[i]-=abs(a[x]-x)+abs(a[y]-y); q[++tot]={i,x,a[x],-1},q[++tot]={i,y,a[y],-1}; swap(a[x],a[y]); res[i]+=abs(a[x]-x)+abs(a[y]-y); q[++tot]={i,x,a[x],1},q[++tot]={i,y,a[y],1}; } solve(1,tot); for(int i=1;i<=m;i++) { ans[i]+=ans[i-1]; printf("%lld\n",res[i]-ans[i]); } return 0; }
|