Skip to content

Commit db80359

Browse files
authored
Update minimum-reverse-operations.cpp
1 parent 30adee9 commit db80359

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

C++/minimum-reverse-operations.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,43 @@ class UnionFind {
7878
vector<int> right_; // added
7979
};
8080
};
81+
82+
// Time: O(nlogn)
83+
// Space: O(n)
84+
// bfs, bst
85+
class Solution2 {
86+
public:
87+
vector<int> minReverseOperations(int n, int p, vector<int>& banned, int k) {
88+
vector<bool> lookup(n);
89+
for (const auto& i : banned) {
90+
lookup[i] = true;
91+
}
92+
int d = 0;
93+
vector<int> result(n, -1);
94+
result[p] = d++;
95+
vector<set<int>> bst(2);
96+
for (int i = 0; i < n; ++i) {
97+
bst[i % 2].emplace(i);
98+
}
99+
bst[p % 2].erase(p);
100+
vector<int> q = {p};
101+
while (!empty(q)) {
102+
vector<int> new_q;
103+
for (const auto& p : q) {
104+
const int left = 2 * max(p - (k - 1), 0) + (k - 1) - p;
105+
const int right = 2 * min(p + (k - 1), n - 1) - (k - 1) - p;
106+
for (auto it = bst[left % 2].lower_bound(left);
107+
it != end(bst[left % 2]) && *it <= right;
108+
it = bst[left % 2].erase(it)) {
109+
if (!lookup[*it]) {
110+
result[*it] = d;
111+
new_q.emplace_back(*it);
112+
}
113+
}
114+
}
115+
q = move(new_q);
116+
++d;
117+
}
118+
return result;
119+
}
120+
};

0 commit comments

Comments
 (0)