Skip to content

Commit 3c35cd7

Browse files
committed
perf(codeforces): optimize lookup using boolean array in p2189C2
1 parent 8a12ada commit 3c35cd7

File tree

1 file changed

+8
-6
lines changed
  • src/main/java/com/lzw/solutions/codeforces/p2189C2

1 file changed

+8
-6
lines changed

src/main/java/com/lzw/solutions/codeforces/p2189C2/Main.java

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// grok-4.1-thinking
21
package com.lzw.solutions.codeforces.p2189C2;
32

43
import java.io.*;
@@ -14,20 +13,23 @@ public static void main(String[] args) throws IOException {
1413
for (int test = 0; test < t; test++) {
1514
int n = Integer.parseInt(br.readLine());
1615

17-
// If n is power of 2, impossible
18-
if ((n & (n - 1)) == 0) {
16+
if ((n & (n - 1)) == 0) { // power of 2
1917
pw.println(-1);
2018
continue;
2119
}
2220

23-
TreeSet<Integer> available = new TreeSet<>();
21+
TreeSet<Integer> available = new TreeSet<>(Comparator.reverseOrder()); // largest first
2422
for (int i = 1; i <= n; i++) {
2523
available.add(i);
2624
}
2725

26+
boolean[] isAvail = new boolean[n + 2];
27+
Arrays.fill(isAvail, 1, n + 1, true);
28+
2829
int[] p = new int[n + 1];
2930
p[n] = n;
3031
available.remove(n);
32+
isAvail[n] = false;
3133

3234
boolean ok = true;
3335
for (int pos = n - 1; pos >= 1; pos--) {
@@ -36,10 +38,10 @@ public static void main(String[] args) throws IOException {
3638
while (it.hasNext()) {
3739
int v = it.next();
3840
int w = v ^ pos;
39-
// Only accept if w is valid and already placed
40-
if (w >= 1 && w <= n && !available.contains(w)) {
41+
if (w >= 1 && w <= n && !isAvail[w]) {
4142
p[pos] = v;
4243
available.remove(v);
44+
isAvail[v] = false;
4345
found = true;
4446
break;
4547
}

0 commit comments

Comments
 (0)