-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
43 lines (39 loc) · 929 Bytes
/
Solution.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
class BinaryIndexedTree {
public:
BinaryIndexedTree(int _n)
: n(_n)
, c(_n + 1) {}
void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += x & -x;
}
}
int query(int x) {
int s = 0;
while (x) {
s += c[x];
x -= x & -x;
}
return s;
}
private:
int n;
vector<int> c;
};
class Solution {
public:
int createSortedArray(vector<int>& instructions) {
int m = *max_element(instructions.begin(), instructions.end());
BinaryIndexedTree tree(m);
const int mod = 1e9 + 7;
int ans = 0;
for (int i = 0; i < instructions.size(); ++i) {
int x = instructions[i];
int cost = min(tree.query(x - 1), i - tree.query(x));
ans = (ans + cost) % mod;
tree.update(x, 1);
}
return ans;
}
};