Uva - 11990
动态逆序对,求删除一个点之前序列中逆序对的个数
首先倒过来看这个问题,把点先全部删掉
然后从最后一个点开始倒着往数列中加点
求加完这个点逆序对的变化
分块做法
把下标看成 x,值看成 y,这样就变成了平面上的点,
将平面分成
bsiz∗bsiz
,
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;
}