poj 2299(权值线段树)

poj 2299
注意开long long
权值线段树就是线段树每个节点存每个权值出现的次数,本题求逆序对应该算一个比较简单的权值线段树,注意离散化

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<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
#define ms(i, j) memeset(i, j, sizeof i)
#define LL long long
const int MAXN = 500000 + 5;
int n;
int a[MAXN], sa[MAXN], siz;
int sumv[MAXN * 4];
#define M ((l+r)>>1)
#define lc o*2
#define rc o*2+1
void pushup(int o) {
sumv[o] = sumv[lc] + sumv[rc];
}
void update(int o, int l, int r, int p) {
if (l==r) {
sumv[o]++;
return ;
}
if (p<=M) update(lc,l,M,p); else if (M<p) update(rc,M+1,r,p);
pushup(o);
}
int query(int o, int l, int r, int x, int y) {
int ret = 0;
if (x<=l&&r<=y) {
return sumv[o];
}
if (x<=M) ret += query(lc, l, M, x, y);
if (M<y) ret += query(rc, M+1, r, x, y);
return ret;
}
void clear() {
for (int i=0;i<=n*4;i++) {
sumv[i] = 0;
}
}
void init() {
clear();
for (int i=1;i<=n;i++) scanf("%d", &a[i]), sa[i] = a[i];
sort(sa+1, sa+1+n), siz = unique(sa+1, sa+1+n) - sa;
for (int i=1;i<=n;i++) {
a[i] = lower_bound(sa+1, sa+siz, a[i]) - sa;
}
}
void solve() {
LL ans = 0;
for (int i=1;i<=n;i++) {
ans += query(1,1,n,a[i],n);
update(1,1,n,a[i]);
}
printf("%lld\n", ans);
}
int main() {
while (scanf("%d", &n)==1&&n) init(), solve();
return 0;
}

------ 本文结束 ------