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
| #include<iostream> #include<cstdio> #include<cstring> #include<cctype> #include<algorithm> #include<cmath> using namespace std; inline int read(){ int w=0,x=0;char c=getchar(); while(!isdigit(c))w|=c=='-',c=getchar(); while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=getchar(); return w?-x:x; } namespace star { const int maxn=2e4+1,maxm=3e6+1; int n,Q,a[maxn],cnt,b[maxn],rt[maxn]; long long ans; int ls[maxm],rs[maxm],tot,val[maxm]; void update(int &ro,int l,int r,int x,int k){ if(!ro) ro=++tot; val[ro]+=k; if(l==r)return; int mid=l+r>>1; if(x<=mid)update(ls[ro],l,mid,x,k); else update(rs[ro],mid+1,r,x,k); } int qa[maxn],qb[maxn]; inline long long query(int l,int r,int x,int type){ int cnta=0,cntb=0; long long ans=0; for(int i=l-1;i;i-=i&-i) qa[++cnta]=rt[i]; for(int i=r;i;i-=i&-i) qb[++cntb]=rt[i]; l=1,r=n; while(l<r){ int mid=l+r>>1; if(x>mid){ if(type){ for(int i=1;i<=cnta;i++) ans-=val[ls[qa[i]]]; for(int i=1;i<=cntb;i++) ans+=val[ls[qb[i]]]; } for(int i=1;i<=cnta;i++) qa[i]=rs[qa[i]]; for(int i=1;i<=cntb;i++) qb[i]=rs[qb[i]]; l=mid+1; }else{ if(!type){ for(int i=1;i<=cnta;i++) ans-=val[rs[qa[i]]]; for(int i=1;i<=cntb;i++) ans+=val[rs[qb[i]]]; } for(int i=1;i<=cnta;i++) qa[i]=ls[qa[i]]; for(int i=1;i<=cntb;i++) qb[i]=ls[qb[i]]; r=mid; } } return ans; } inline void work(){ n=read(); for(int i=1;i<=n;i++) a[i]=b[i]=read(); sort(b+1,b+1+n); cnt=unique(b+1,b+1+n)-b-1; for(int i=1;i<=n;i++) a[i]=lower_bound(b+1,b+1+cnt,a[i])-b; for(int i=1;i<=n;i++){ ans+=query(1,i-1,a[i],0); for(int j=i;j<=n;j+=j&-j) update(rt[j],1,n,a[i],1); } printf("%lld\n",ans); Q=read(); while(Q--){ int x=read(),y=read(); if(x==y){ printf("%lld\n",ans);continue; } if(x>y)swap(x,y); ans=ans-query(1,x-1,a[x],0)-query(x+1,n,a[x],1)-query(1,y-1,a[y],0)-query(y+1,n,a[y],1); for(int i=x;i<=n;i+=i&-i) update(rt[i],1,n,a[x],-1),update(rt[i],1,n,a[y],1); for(int i=y;i<=n;i+=i&-i) update(rt[i],1,n,a[x],1),update(rt[i],1,n,a[y],-1); swap(a[x],a[y]); ans=ans+query(1,x-1,a[x],0)+query(x+1,n,a[x],1)+query(1,y-1,a[y],0)+query(y+1,n,a[y],1); if(a[x]<a[y]) ans+=1; else if(a[x]>a[y]) ans-=1; printf("%lld\n",ans); } } } signed main(){ star::work(); return 0; }
|