链接
http://www.lydsy.com/JudgeOnline/problem.php?id=2141
题解
很麻烦,但是竟然1A了。
考虑一次修改,可以把整个序列拆成多段。图中x和y是我要交换的两个数字,容易看出x和y的交换对A和C两段的逆序对没有任何影响(只要有一个数在A和C中,这个逆序对就和此次交换无关),但是B段里面和x或y有关的逆序对会有增添。
我们把整个序列分块,每块维护一个权值树状数组,方便我们快速求出这一块中有多少大于x的数字(或者小于)。拿x举例,B中原来比x小的和x组成逆序对,交换后这些逆序对消失,所以答案应该减去这些元素;B中原来比x大的原来和x不是逆序对,交换后会和x组成逆序对,所以答案应该加上这些元素。对于y的话同理。
这样的话复杂度为O(NlogN*sqrt(N))
话说这道题数据规模这么小它到底是想让你怎么做。。
代码
//分块
#include <cstdio>
#include <algorithm>
#include <map>
#define maxn 21000
#define size 200
#define lowbit(x) (x&-x)
using namespace std;
int ta[150][maxn], ans, N, M, h[maxn], tmp[maxn], lp[maxn];
void add(int *r, int pos, int v)
{for(;pos<=N;pos+=lowbit(pos))r[pos]+=v;}
int sum(int *r, int pos)
{int ans;for(ans=0;pos;pos-=lowbit(pos))ans+=r[pos];return ans;}
void init()
{
int i;
scanf("%d",&N);
for(i=1;i<=N;i++)scanf("%d",tmp+i),h[i]=tmp[i];
sort(tmp+1,tmp+N+1);
for(i=1;i<=N;i++)h[i]=lower_bound(tmp+1,tmp+N+1,h[i])-tmp;
for(i=1;i<=N;i++)
{
lp[i]=i/size;
add(ta[lp[i]],h[i],1);
}
}
int calc(int pos, int val)
{
int i, cnt=0;
for(i=0;i<lp[pos];i++)cnt+=sum(ta[i],val);
for(i=lp[pos]*size;i<=pos;i++)if(i and h[i]<=val)cnt++;
return pos-cnt;
}
void work()
{
int x, y, i, t1, t2;
for(i=1;i<=N;i++)ans+=calc(i,h[i]);
printf("%d\n",ans);
scanf("%d",&M);
while(M--)
{
scanf("%d%d",&x,&y);
if(x>y)swap(x,y);
t1=calc(y-1,h[x])-calc(x,h[x]);
t2=calc(y-1,h[x]-1)-calc(x,h[x]-1);
ans+=t1-(y-x-1-t2);
t1=calc(y-1,h[y])-calc(x,h[y]);
t2=calc(y-1,h[y]-1)-calc(x,h[y]-1);
ans-=t1-(y-x-1-t2);
if(h[x]>h[y])ans--;
if(h[x]<h[y])ans++;
add(ta[lp[x]],h[x],-1);add(ta[lp[y]],h[x],1);
add(ta[lp[y]],h[y],-1);add(ta[lp[x]],h[y],1);
swap(h[x],h[y]);
printf("%d\n",ans);
}
}
int main()
{
init();
work();
return 0;
}