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 96 97 98 99 100 101 102 103 104 105 106 107 108
   | #include <bits/stdc++.h> using namespace std;
  const int maxn=1e5+5; const int maxm=1e3+5; #define ll long long
  struct Tree {     int RT[maxn],Ncnt,Top;     int L[maxn],R[maxn],Lcnt,Rcnt;     int ls[maxn<<7],rs[maxn<<7],sum[maxn<<7];     vector<int>TL[maxm],TR[maxm];
      int limit;     inline int lowbit(int x){return x&(-x);}
      void update(int &rt,int l,int r,int x,int v)     {         if(!rt) rt=++Ncnt;         sum[rt]+=v;         if(l==r) return;         int mid=(l+r)>>1;         if(x<=mid) update(ls[rt],l,mid,x,v);         else update(rs[rt],mid+1,r,x,v);     }
      inline void add(int pos,int x,int v)     {         for(int i=pos;i<=limit;i+=lowbit(i)) update(RT[i],1,limit,x,v);     }
      int query(int ql,int qr,int l,int r)     {         int res=0,mid=(l+r)>>1;         for(int i=1;i<=Lcnt;i++) res-=sum[L[i]];         for(int i=1;i<=Rcnt;i++) res+=sum[R[i]];         if(ql==l && qr==r) return res;
          if(qr<=mid)         {             for(int i=1;i<=Lcnt;i++) L[i]=ls[L[i]];             for(int i=1;i<=Rcnt;i++) R[i]=ls[R[i]];             return query(ql,qr,l,mid);         }         else if(ql>=mid+1)         {             for(int i=1;i<=Lcnt;i++) L[i]=rs[L[i]];             for(int i=1;i<=Rcnt;i++) R[i]=rs[R[i]];             return query(ql,qr,mid+1,r);         }         else         {             res=0;             int now=Top++;             TL[now].clear();TR[now].clear();             for(int i=1;i<=Lcnt;i++) TL[now].push_back(L[i]);             for(int i=1;i<=Rcnt;i++) TR[now].push_back(R[i]);
              for(int i=1;i<=Lcnt;i++) L[i]=ls[TL[now][i-1]];             for(int i=1;i<=Rcnt;i++) R[i]=ls[TR[now][i-1]];             res+=query(ql,mid,l,mid);
              for(int i=1;i<=Lcnt;i++) L[i]=rs[TL[now][i-1]];             for(int i=1;i<=Rcnt;i++) R[i]=rs[TR[now][i-1]];             res+=query(mid+1,qr,mid+1,r);             return res;         }     }
      int ask(int l,int r,int ql,int qr)     {         if(ql>qr || l>r) return 0;         Lcnt=Rcnt=Top=0;         for(int i=l-1;i;i-=lowbit(i)) L[++Lcnt]=RT[i];         for(int i=r;i;i-=lowbit(i)) R[++Rcnt]=RT[i];         return query(ql,qr,1,limit);     } }T;
  int pos[maxn];
  int main() {     ios::sync_with_stdio(0);     cin.tie(0);cout.tie(0);
      int n,m;     cin>>n>>m;     ll ans=0;     T.limit=n;     for(int i=1;i<=n;i++)     {         int x;cin>>x;         pos[x]=i;         ans+=T.ask(1,i-1,x+1,n);         T.add(i,x,1);     }     for(int i=1;i<=m;i++)     {         int x;cin>>x;         cout<<ans<<'\n';         ans-=T.ask(1,pos[x]-1,x+1,n);         ans-=T.ask(pos[x]+1,n,1,x-1);         T.add(pos[x],x,-1);     }     return 0; }
   |