bzoj 2141: 排队 （树状数组套线段树）

代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define N 200003
using namespace std;
int a[N],b[N],n,m,sz,cnt,root[N];
struct data{
int sum,ls,rs;
}tr[N*60];
void pointchange(int &i,int l,int r,int x,int val)
{
if (!i) i=++sz;
tr[i].sum+=val;
if (l==r) return;
int mid=(l+r)/2;
if (x<=mid) pointchange(tr[i].ls,l,mid,x,val);
else pointchange(tr[i].rs,mid+1,r,x,val);
}
int lowbit(int x)
{
return x&(-x);
}
void change(int x,int y,int val)
{
for (int i=x;i<=n;i+=lowbit(i))
pointchange(root[i],1,cnt,y,val);
}
int qjsum(int i,int l,int r,int ll,int rr)
{
if (ll>rr) return 0;
if (ll<=l&&r<=rr) return tr[i].sum;
int mid=(l+r)/2;
int ans=0;
if (ll<=mid) ans+=qjsum(tr[i].ls,l,mid,ll,rr);
if (rr>mid) ans+=qjsum(tr[i].rs,mid+1,r,ll,rr);
return ans;
}
int query(int x,int l,int r)
{
if (!x) return 0;
int ans=0;
for (int i=x;i>=1;i-=lowbit(i))
ans+=qjsum(root[i],1,cnt,l,r);
return ans;
}
int main()
{
freopen("a.in","r",stdin);
freopen("my.out","w",stdout);
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&a[i]),b[i]=a[i];
sort(b+1,b+n+1);
cnt=unique(b+1,b+n+1)-b-1;
for (int i=1;i<=n;i++) a[i]=lower_bound(b+1,b+cnt+1,a[i])-b;
//for (int i=1;i<=n;i++) cout<<a[i]<<" ";
//cout<<endl;
for (int i=1;i<=n;i++)
change(i,a[i],1);
int ans=0;
for (int i=2;i<=n;i++)
ans+=query(i-1,a[i]+1,cnt);//,cout<<ans<<endl;
scanf("%d",&m);
printf("%d\n",ans);
for (int i=1;i<=m;i++) {
int x,y; scanf("%d%d",&x,&y);
if(x>y) swap(x,y);
ans-=query(x-1,a[x]+1,cnt);
ans-=(query(n,1,a[x]-1)-query(x,1,a[x]-1));
ans-=query(y-1,a[y]+1,cnt);
ans-=(query(n,1,a[y]-1)-query(y,1,a[y]-1));
if (a[x]>a[y]) ans++;
change(x,a[x],-1); change(x,a[y],1);
change(y,a[y],-1); change(y,a[x],1);
swap(a[x],a[y]);
ans+=query(x-1,a[x]+1,cnt);
ans+=(query(n,1,a[x]-1)-query(x,1,a[x]-1));
ans+=query(y-1,a[y]+1,cnt);
ans+=(query(n,1,a[y]-1)-query(y,1,a[y]-1));
if (a[x]>a[y]) ans--;
printf("%d\n",ans);
}
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客