-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC1409.cpp
More file actions
executable file
·58 lines (50 loc) · 960 Bytes
/
LC1409.cpp
File metadata and controls
executable file
·58 lines (50 loc) · 960 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
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
/*
Problem Statement: https://leetcode.com/problems/queries-on-a-permutation-with-key/
Time: O(m • log m)
Space: O(m)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class FenwickTree {
private:
std::vector<int> ft;
public:
FenwickTree(int n) : ft(n + 1) {}
int LSB(int x) {
return x & (-x);
}
void add(int i, int val) {
while (i < ft.size()) {
ft[i] += val;
i += LSB(i);
}
}
int rsq(int i) {
int sum = 0;
while (i) {
sum += ft[i];
i -= LSB(i);
}
return sum;
}
};
class Solution {
public:
vector<int> processQueries(vector<int>& queries, int m) {
int n = queries.size();
vector<int> res(n);
FenwickTree ft(n + m + 1);
vector<int> mp(m + 1);
for (int i = 1; i <= m; i++) {
ft.add(n + i, 1);
mp[i] = n + i;
}
for (int i = 0; i < queries.size(); i++) {
int q = queries[i];
res[i] = ft.rsq(mp[q]) - 1;
ft.add(mp[q], -1);
ft.add(n - i, 1);
mp[q] = n - i;
}
return res;
}
};