-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInversionNumber.cpp
More file actions
33 lines (33 loc) · 908 Bytes
/
InversionNumber.cpp
File metadata and controls
33 lines (33 loc) · 908 Bytes
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
//1-origin
template <typename T>
struct FenwickTree {
vector<T> data;
FenwickTree(int n) : data(n + 1, 0) {}
//data[i] += x
void add(int i, T x){
while (i <= (int)data.size()) {
data[i] += x;
i += i & -i;
}
}
//[1, i)
T sum(int i){
T res = 0;
while (i > 0) {
res += data[i];
i -= i & -i;
}
return res;
}
//[l, r)
T sum(int l, int r) { return sum(r) - sum(l); }
};
long long InversionNumber(const vector<int> &a) {
FenwickTree<long long> ft(300030);
long long res = 0;
for (int i = 0; i < a.size(); i ++) {
res += i - ft.sum(a[i]);
ft.add(a[i], 1);
}
return res;
}