【线段树】逆序对

求逆序对的线段树做法。
对于每一个数,类似桶排序记录出现的次数,则那个数记入前大于它的数的次数和就是那个数的逆序对个数。于是只需线段树维护区间和即可。
然而对于桶排序的数据范围太大了,因此离散化了一下,离散化后的数据入桶建树即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct number{
int no,val;
};
number num[40005];
int change[40005],sgt[40005*4]={0};
int n;

inline bool cmp(number &a,number &b){
return a.val<b.val;
}

int query(int rt,int nst,int ned,int qst,int qed){
if(qst>ned||qed<nst)
return 0;
if(qst<=nst&&qed>=ned)
return sgt[rt];
int mid=(nst+ned)>>1;
return query(rt*2,nst,mid,qst,qed)+query(rt*2+1,mid+1,ned,qst,qed);
}

void update(int rt,int nst,int ned,int index){
if(nst==ned){
if(nst==index)
sgt[rt]++;
return;
}
int mid=(nst+ned)>>1;
if(index<=mid)
update(rt*2,nst,mid,index);
else update(rt*2+1,mid+1,ned,index);
sgt[rt]=sgt[rt*2]+sgt[rt*2+1];
}

int main(){
scanf("%d",&n);
int i;
for(i=1;i<=n;i++){
scanf("%d",&num[i].val);
num[i].no=i;
}

sort(num+1,num+n+1,cmp);

for(i=1;i<=n;i++)
change[num[i].no]=i;

int ans=0;

for(i=1;i<=n;i++){
update(1,1,n,change[i]);
ans+=query(1,1,n,change[i]+1,n);
}

printf("%d",ans);

return 0;
}