思路:
一道典型的树状数组求逆序对题,不详细写了,主要就是练习一下离散化.
代码: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
using namespace std;
int bit[500005],a[500005],b[500005],n;
int sum(int pos) {
int i=pos,ans=0;
while (i > 0) {
ans += bit[i];
i -= lowbit(i);
}
return ans;
}
void add(int pos, int x) {
int i = pos;
while (i <= 500004) {
bit[i] += x;
i += lowbit(i);
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
while (cin>>n&&n) {
ll ans= 0;
ms(bit, 0);
for (int i = 0;i < n;i++) {
cin >> a[i];
b[i] = a[i];
}
sort(a, a + n);
int size = unique(a, a + n)-a;
for (int i = 0;i < n;i++) {
int index = lower_bound(a, a + size, b[i]) - a+1;
add(index, 1);
ans =ans+(ll)(i-sum(index)+1);
}
cout << ans << "\n";
}
return 0;
}