[Uva 11990] "Dynamic" Inversion (二维分块)

Uva - 11990

动态逆序对,求删除一个点之前序列中逆序对的个数


首先倒过来看这个问题,把点先全部删掉
然后从最后一个点开始倒着往数列中加点
求加完这个点逆序对的变化

分块做法

把下标看成 x,值看成 y,这样就变成了平面上的点,
将平面分成 bsizbsiz bsiz=N
加入一个点的时候,在它左上方区域的和右下方区域中的点的数目
就是加入这个点所能产生的逆序对的数目
所以只要维护一下每行每个块的前缀和就好,方便求数目
加入一个点 (x,y) 的时候,先暴力更新这行的前缀和 O(N)
然后利用前缀暴力扫每一行,求得左上和右下区域内点的个数 O(N)
不在块内的再暴力扫一遍统计 O(N)
时间复杂度 O(MN)

#pragma comment(linker, "/STACK:102400000,102400000")
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <queue>
using namespace std;
typedef pair<int,int> Pii;
typedef long long LL;
typedef unsigned long long ULL;
typedef double DBL;
typedef long double LDBL;
#define MST(a,b) memset(a,b,sizeof(a))
#define CLR(a) MST(a,0)
#define Sqr(a) (a*a)

const int maxn=2e5+10, maxs=500;
int N,M,bsiz,blen;
int X[maxn], Y[maxn];
bool ban[maxn];
bool have[maxn];

LL psum[maxs][maxs];

int que[maxn];
LL ans[maxn];

LL insert(int,int);
LL sum(int,int);

int main()
{
    #ifdef LOCAL
    freopen("in.txt", "r", stdin);
//  freopen("out.txt", "w", stdout);
    #endif

    while(~scanf("%d%d", &N, &M))
    {
        CLR(X); CLR(Y);
        CLR(psum); CLR(ban); CLR(have);
        bsiz=sqrt(N)+10;
        blen=N/bsiz+1;
        LL tans=0;
        for(int i=0; i<N; i++) 
        {
            scanf("%d", &Y[i]);
            Y[i]--;
            X[ Y[i] ] = i;
        }
        for(int i=0; i<M; i++)
        {
            scanf("%d", &que[i]);
            que[i]--;
            ban[ X[ que[i] ] ]=1;
        }

        for(int i=0; i<N; i++)
        {
            if(!ban[i]) tans+=insert(i, Y[i]);
//          printf("%lld\n", tans);
        }

        for(int i=M-1; i>=0; i--)
        {
            tans+=insert(X[ que[i] ], que[i]);
            ans[i]=tans;
        }
        for(int i=0; i<M; i++) printf("%lld\n", ans[i]);
    }
    return 0;
}

LL insert(int x, int y)
{
    have[x]=1;
    int tx=x/bsiz;
    int ty=y/bsiz;
    for(int i=tx; i<blen; i++) psum[i][ty]++;

    LL res=-2*sum(x,y);
    res+=sum(N-1,y);
    res+=sum(x,N-1);
    return res;
}

LL sum(int x,int y)
{
    int tx=x/bsiz;
    int ty=y/bsiz;
    LL res=0;
    if(tx) for(int i=0; i<ty; i++) res+=psum[tx-1][i];
    for(int i=tx*bsiz; i<=x; i++)
    {
        if(have[i] && Y[i]<ty*bsiz) res++;
    }
    for(int i=ty*bsiz; i<=y; i++)
    {
        if(have[X[i]] && X[i]<=x) res++;
    }
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值