forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimum-reverse-operations.cpp
120 lines (113 loc) · 3.32 KB
/
minimum-reverse-operations.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// Time: O(n * alpha(n)) = O(n)
// Space: O(n)
// bfs, union find
class Solution {
public:
vector<int> minReverseOperations(int n, int p, vector<int>& banned, int k) {
vector<bool> lookup(n);
for (const auto& i : banned) {
lookup[i] = true;
}
int d = 0;
vector<int> result(n, -1);
result[p] = d++;
UnionFind uf(n + 2);
uf.union_set(p, p + 2);
vector<int> q = {p};
while (!empty(q)) {
vector<int> new_q;
for (const auto& p : q) {
const int left = 2 * max(p - (k - 1), 0) + (k - 1) - p;
const int right = 2 * min(p + (k - 1), n - 1) - (k - 1) - p;
for (int p = uf.right_set(left); p <= right; p = uf.right_set(p)) {
if (!lookup[p]) {
result[p] = d;
new_q.emplace_back(p);
}
uf.union_set(p, p + 2);
}
}
q = move(new_q);
++d;
}
return result;
}
private:
class UnionFind {
public:
UnionFind(int n)
: set_(n)
, rank_(n)
, right_(n) { // added
iota(begin(set_), end(set_), 0);
iota(begin(right_), end(right_), 0); // added
}
int find_set(int x) {
if (set_[x] != x) {
set_[x] = find_set(set_[x]); // Path compression.
}
return set_[x];
}
bool union_set(int x, int y) {
x = find_set(x), y = find_set(y);
if (x == y) {
return false;
}
if (rank_[x] > rank_[y]) {
swap(x, y);
}
set_[x] = y; // Union by rank.
if (rank_[x] == rank_[y]) {
++rank_[y];
}
right_[y] = max(right_[x], right_[y]); // added
return true;
}
int right_set(int x) { // added
return right_[find_set(x)];
}
private:
vector<int> set_;
vector<int> rank_;
vector<int> right_; // added
};
};
// Time: O(nlogn)
// Space: O(n)
// bfs, bst
class Solution2 {
public:
vector<int> minReverseOperations(int n, int p, vector<int>& banned, int k) {
vector<bool> lookup(n);
for (const auto& i : banned) {
lookup[i] = true;
}
int d = 0;
vector<int> result(n, -1);
result[p] = d++;
vector<set<int>> bst(2);
for (int i = 0; i < n; ++i) {
bst[i % 2].emplace(i);
}
bst[p % 2].erase(p);
vector<int> q = {p};
while (!empty(q)) {
vector<int> new_q;
for (const auto& p : q) {
const int left = 2 * max(p - (k - 1), 0) + (k - 1) - p;
const int right = 2 * min(p + (k - 1), n - 1) - (k - 1) - p;
for (auto it = bst[left % 2].lower_bound(left);
it != end(bst[left % 2]) && *it <= right;
it = bst[left % 2].erase(it)) {
if (!lookup[*it]) {
result[*it] = d;
new_q.emplace_back(*it);
}
}
}
q = move(new_q);
++d;
}
return result;
}
};