-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
30 lines (30 loc) · 958 Bytes
/
Solution.java
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
class Solution {
public int[] minReverseOperations(int n, int p, int[] banned, int k) {
int[] ans = new int[n];
TreeSet<Integer>[] ts = new TreeSet[] {new TreeSet<>(), new TreeSet<>()};
for (int i = 0; i < n; ++i) {
ts[i % 2].add(i);
ans[i] = i == p ? 0 : -1;
}
ts[p % 2].remove(p);
for (int i : banned) {
ts[i % 2].remove(i);
}
ts[0].add(n);
ts[1].add(n);
Deque<Integer> q = new ArrayDeque<>();
q.offer(p);
while (!q.isEmpty()) {
int i = q.poll();
int mi = Math.max(i - k + 1, k - i - 1);
int mx = Math.min(i + k - 1, n * 2 - k - i - 1);
var s = ts[mi % 2];
for (int j = s.ceiling(mi); j <= mx; j = s.ceiling(mi)) {
q.offer(j);
ans[j] = ans[i] + 1;
s.remove(j);
}
}
return ans;
}
}