11package com .lzw .solutions .codeforces .p2189C2 ;
22
3- import java .io .BufferedReader ;
4- import java .io .IOException ;
5- import java .io .InputStreamReader ;
6- import java .io .PrintWriter ;
3+ import java .io .*;
4+ import java .util .*;
75
86public class Main {
9- private static final BufferedReader in = new BufferedReader (new InputStreamReader (System .in ));
10- private static final PrintWriter out = new PrintWriter (System .out , true );
7+ public static void main (String [] args ) throws IOException {
8+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
9+ PrintWriter pw = new PrintWriter (System .out );
1110
12- private static void solve () throws IOException {
13- // your code here
14- }
11+ int t = Integer .parseInt (br .readLine ());
1512
16- public static void main (String [] args ) throws IOException {
17- solve ();
18- out .close ();
13+ for (int test = 0 ; test < t ; test ++) {
14+ int n = Integer .parseInt (br .readLine ());
15+
16+ // Check if n is power of 2
17+ if ((n & (n - 1 )) == 0 ) {
18+ pw .println (-1 );
19+ continue ;
20+ }
21+
22+ // TreeSet to keep available numbers in sorted order
23+ TreeSet <Integer > available = new TreeSet <>();
24+ for (int i = 1 ; i <= n ; i ++) {
25+ available .add (i );
26+ }
27+
28+ int [] p = new int [n + 1 ];
29+
30+ // Place n at position n
31+ p [n ] = n ;
32+ available .remove (n );
33+
34+ // From n-1 down to 1
35+ for (int pos = n - 1 ; pos >= 1 ; pos --) {
36+ boolean found = false ;
37+
38+ // Try smallest available numbers first
39+ Iterator <Integer > it = available .iterator ();
40+ while (it .hasNext ()) {
41+ int v = it .next ();
42+ int w = v ^ pos ;
43+
44+ // Check if w is invalid or already used
45+ if (w < 1 || w > n || !available .contains (w )) {
46+ // v is good to place at pos
47+ p [pos ] = v ;
48+ available .remove (v );
49+ found = true ;
50+ break ;
51+ }
52+ }
53+
54+ // In theory this should never happen for non-power-of-2 n
55+ if (!found ) {
56+ pw .println (-1 );
57+ break ;
58+ }
59+ }
60+
61+ if (p [1 ] == 0 ) continue ; // failed case (should not occur)
62+
63+ // Output the permutation
64+ for (int i = 1 ; i <= n ; i ++) {
65+ if (i > 1 ) pw .print (" " );
66+ pw .print (p [i ]);
67+ }
68+ pw .println ();
69+ }
70+
71+ pw .flush ();
72+ pw .close ();
1973 }
20- }
74+ }
0 commit comments