-
Notifications
You must be signed in to change notification settings - Fork 0
/
class_Fenwick.cpp
58 lines (56 loc) · 1.17 KB
/
class_Fenwick.cpp
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
#include "auto_util_header.hpp"
class Fenwick {
using val_t = ll;
private:
vector<val_t> nodes;
int n;
public:
Fenwick(int n) {
this->n = n;
nodes = vector<val_t>(n, 0);
}
Fenwick(const vector<val_t> &a) {
this->n = a.size();
nodes = vector<val_t>(n, 0);
Loop(i, a.size()) add(i, a[i]);
}
void add(int k, val_t x) {
++k;
for (int id = k; id <= n; id += id & -id) {
nodes[id - 1] += x;
}
}
void upd(int k, val_t x) {
val_t cur = sumof(k, k + 1);
val_t d = x - cur;
add(k, d);
}
// note: sum of [s, t)
val_t sumof(int s, int t) {
val_t ret = 0;
for (int id = t; id > 0; id -= id & -id) {
ret += nodes[id - 1];
}
for (int id = s; id > 0; id -= id & -id) {
ret -= nodes[id - 1];
}
return ret;
}
};
// solve the number of pair(i, j) such that a[i] > a[j] (i < j)
ll solve_inversion_number(const vll &a) {
int n = a.size();
map<ll, int> mp;
Loop(i, n) mp[a[i]] = 1;
int cnt = 0;
Loopitr(itr, mp) itr->second = cnt++;
vi b(n);
Loop(i, n) b[i] = mp[a[i]];
Fenwick fnk(vll(cnt, 0));
ll ret = 0;
Loop(i, n) {
ret += fnk.sumof(b[i] + 1, cnt);
fnk.add(b[i], 1);
}
return ret;
}