Skip to content

Commit c1733d4

Browse files
committed
refactor(codeforces): simplify logic and cleanup comments in p2189C2
1 parent aea80dd commit c1733d4

1 file changed

Lines changed: 14 additions & 23 deletions

File tree

  • src/main/java/com/lzw/solutions/codeforces/p2189C2

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

Lines changed: 14 additions & 23 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,59 +13,51 @@ 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-
// Check if n is power of 2
16+
// If n is power of 2, impossible
1817
if ((n & (n - 1)) == 0) {
1918
pw.println(-1);
2019
continue;
2120
}
2221

23-
// TreeSet to keep available numbers in sorted order
2422
TreeSet<Integer> available = new TreeSet<>();
2523
for (int i = 1; i <= n; i++) {
2624
available.add(i);
2725
}
2826

2927
int[] p = new int[n + 1];
30-
31-
// Place n at position n
3228
p[n] = n;
3329
available.remove(n);
3430

35-
// From n-1 down to 1
31+
boolean ok = true;
3632
for (int pos = n - 1; pos >= 1; pos--) {
37-
boolean found = false;
38-
39-
// Try smallest available numbers first
4033
Iterator<Integer> it = available.iterator();
34+
boolean found = false;
4135
while (it.hasNext()) {
4236
int v = it.next();
4337
int w = v ^ pos;
44-
45-
// Check if w is invalid or already used
46-
if (w < 1 || w > n || !available.contains(w)) {
47-
// v is good to place at pos
38+
// Only accept if w is valid and already placed
39+
if (w >= 1 && w <= n && !available.contains(w)) {
4840
p[pos] = v;
4941
available.remove(v);
5042
found = true;
5143
break;
5244
}
5345
}
54-
55-
// In theory this should never happen for non-power-of-2 n
5646
if (!found) {
57-
pw.println(-1);
47+
ok = false;
5848
break;
5949
}
6050
}
6151

62-
if (p[1] == 0) continue; // failed case (should not occur)
63-
64-
// Output the permutation
65-
for (int i = 1; i <= n; i++) {
66-
if (i > 1) pw.print(" ");
67-
pw.print(p[i]);
52+
if (!ok) {
53+
pw.println(-1);
54+
} else {
55+
for (int i = 1; i <= n; i++) {
56+
if (i > 1) pw.print(" ");
57+
pw.print(p[i]);
58+
}
59+
pw.println();
6860
}
69-
pw.println();
7061
}
7162

7263
pw.flush();

0 commit comments

Comments
 (0)