This page is still under construction.

Parts of this page are still being built. What you see may change.

Who needs 8 queens when you can have N?

Time limit1sMemory limit128 MB

Summary
Find the lexicographically smallest placement of N non-attacking queens on an N by N board for each test case.
Level

Medium6 of 10

Topics
Backtracking, Recursion, Bit manipulation
Solved
No attempts yet

Problem

The eight queens puzzle asks you to place eight queens on an 8x8 board so that no queen attacks another. The N queens problem asks the same thing on an NxN board with N queens.

Two queens attack each other when they share a row, share a column, or sit on a common diagonal. Number the rows and the columns from 00. Queens at (r1,c1)(r_1, c_1) and (r2,c2)(r_2, c_2) sit on a common diagonal when r1+c1=r2+c2r_1 + c_1 = r_2 + c_2 or r1−c1=r2−c2r_1 - c_1 = r_2 - c_2.

A valid placement holds exactly one queen in every row and exactly one in every column, so it is written as a vector p0,p1,…,pN−1p_0, p_1, \dots, p_{N-1} in which pip_i is the column of the queen in row ii. That vector is a permutation of 00 through N−1N-1.

Every N≥4N \ge 4 admits more than one valid placement, so the answer is pinned to the lexicographically smallest vector. To compare two vectors, read them from index 00 and find the first position where they differ. The vector with the smaller value at that position is the smaller one.

Input

The first line contains the number of test cases TT (1≤T≤201 \le T \le 20). Each of the next TT lines contains one integer NN (4≤N≤184 \le N \le 18).

Output

Print two lines per test case, in the order the cases are given. The first line contains NN. The second line contains the lexicographically smallest vector for that board, that is the NN column numbers p0,p1,…,pN−1p_0, p_1, \dots, p_{N-1} separated by single spaces.

Examples2

  1. Example 1

    Input
    3
    4
    5
    6
    
    Expected output
    4
    1 3 0 2
    5
    0 2 4 1 3
    6
    1 3 5 0 2 4
    
  2. Example 2

    Input
    2
    8
    10
    
    Expected output
    8
    0 4 7 5 2 6 1 3
    10
    0 2 5 7 9 4 8 1 3 6