BZOJ 3295 CQOI2011动态逆序对

Problem

BZOJ

Solution

正解是cdq分治,然而我不会,就用了主席树,不过常数好像比较大,洛谷会T一个点,要开O2才能过。。

首先如果统计序列的答案,用树状数组做就是nlogn,那么我们就先用其处理出初始答案
我们不妨考虑a[x]对于答案的贡献,那么就应该是前面比它大的数的个数+后面比它小的数的个数,每删去一个数减去即可。为了统计这个贡献,我们可以用主席树来解决。
当然因为有修改操作,我们在外面套一个树状数组。
那么问题就变成了求区间内在[L,R]之间的数有多少个,由于是树状数组的原因,主席树所累加的历史版本是一段一段的,所以当我们用lowbit拆成一段一段的时候,直接累加sum[rt],就无需再减了。
先统计前面部分比它小的个数cnt,由于树状数组的特性,后面部分比它大的,我们只能容斥一下,注意到前面部分的计算结果可以重复利用,也就是pos-cnt-1即为前面部分比它大的。

Code

#include <cstdio>
#define lowbit(x) ((x)&(-(x)))
using namespace std;
typedef long long ll;
const int maxn=100010,maxm=9000010;
int n,m,tot,cnt[2],tmp[2][20],t[maxn];
int a[maxn],p[maxn],rt[maxn],sum[maxm],lc[maxm],rc[maxm];
ll ans;
template <typename Tp> inline void read(Tp &x)
{
    x=0;char ch=getchar();
    while(ch<'0'||ch>'9') ch=getchar();
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
}
void add(int pos,int val){for(;pos<=n;pos+=lowbit(pos)) t[pos]+=val;}
int ask(int pos)
{
    int res=0;
    for(;pos;pos-=lowbit(pos)) res+=t[pos];
    return res;
}
void update(int l,int r,int pos,int val,int& rt)
{
    if(!rt) rt=++tot;
    sum[rt]+=val;
    if(l==r) return ;
    int m=(l+r)>>1;
    if(pos<=m) update(l,m,pos,val,lc[rt]);
    else update(m+1,r,pos,val,rc[rt]);
}
int query(int l,int r,int L,int R,int rt)
{
    if(L>R||!rt) return 0;
    if(L<=l&&r<=R) return sum[rt];
    int m=(l+r)>>1,res=0;
    if(L<=m) res+=query(l,m,L,R,lc[rt]);
    if(m<R) res+=query(m+1,r,L,R,rc[rt]);
    return res;
}
ll pre(int x,int pos)
{
    ll res=0;int cnt;
    for(int i=pos-1;i;i-=lowbit(i))
    {
        cnt=query(1,n,x+1,n,rt[i]);
        res+=(cnt<<1)-sum[rt[i]];
    }
    for(int i=n;i;i-=lowbit(i))
      res+=query(1,n,1,x-1,rt[i]);
    return res;
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif
    read(n);read(m);
    for(int i=1;i<=n;i++)
    {
        read(a[i]);p[a[i]]=i;add(a[i],1);ans+=i-ask(a[i]);
        for(int j=i;j<=n;j+=lowbit(j)) update(1,n,a[i],1,rt[j]);
    }
    for(int i=1,x;i<m;i++)
    {
        printf("%lld\n",ans);
        read(x);
        ans-=pre(x,p[x]);
        for(int j=p[x];j<=n;j+=lowbit(j)) update(1,n,x,-1,rt[j]);
    }
    printf("%lld\n",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值