// Q: https://codeforces.com/contest/1339/problem/B

const readline = require('readline');

let input = [];

const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
});

rl.on('line', lineInput => {
	input.push(lineInput);
});

rl.on('close', () => {
	const test = parseInt(input[0]);
	for (let t=0; t < test; t++) {
		let n = parseInt(input[2*t+1]);
		let arr = input[2*t+2].split(' ').map((a) => parseInt(a));
		console.log(solution(n, arr));
	}
});

function solution(n, arr) {
	arr = arr.sort((a, b) => a-b);
	let ans = [], i = 0, j=n-1;
	while (i <= j) {
		ans.push(arr[i]);
		if (i < j) {
			ans.push(arr[j]);
		}
		i++;
		j--;
	}
	ans = ans.reverse();
	return ans.join(' ');
}

let i = '';
let lines;
process.stdin.on('data', (c) => (i += c));
process.stdin.on('end', () => {
  const { EOL } = require('os');
  lines = i.split(EOL); /*your input text, split by lines*/
  main();
});

function solve(n, nums) {
  nums.sort((a, b) => a - b);
  result = []
  for (let i = 0; i*2 < n; ++i) {
    result.push(nums[i]);
    if ( i !== n - i - 1)
      result.push(nums[n - i - 1]);
  }
  return result.reverse().join(' ');
}

function main() {
  let currentLine = 0;
  const readLine = (_) => lines[currentLine++].split(' ').map((val) => parseInt(val));

  const test = readLine()[0];
  for (let t = 1; t <= test; ++t) {
    const n = readLine()[0];
    const nums = readLine();
    const S = solve(n, nums);
    console.log(S);
  }
}

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
    console.log(x);
}

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});
function readline() {
    return inputString[currentLine++];
}

//-----------main fucntion-----------

function main() {
    var T = parseInt(readline());
    while (T--) {
        var input = parseInt(readline());
        var input1 = readline().split(' ').map(x => parseInt(x));
        input1.sort((x, y) => x - y)
        var I = 0, j = input - 1, a = []
        for (var i = 0; i < input; i++) {
            if (i % 2) {
                a[i] = input1[I]
                I++
            }
            else {
                a[i] = input1[j]
                j--
            }
        }

        a.reverse()
        print(a.join(" "))
    }

}

var tests = parseInt(readline())
for (var t = 0; t < tests; t++){
var size = parseInt(readline())
var array = readline().split(' ').map(c => parseInt(c))
var head = (size%2) ? parseInt(size/2 + 1): size/2
var tail = head+1, res = []
array.sort((a,b) => b-a)
while (head){
	res.push(array[head-1],array[tail-1])
	head -= 1; tail += 1
}
print(res.join(' '))
}

const readline = require("readline");

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

let arr = [];

rl.on("line", (line) => {
    arr.push(line);
}).on("close", () => {
    solve(arr);
    process.exit(0);
});

function solve(lines) {
    let row = 0;
    let t = +lines[row++];
    for(let i = 0; i < t; i++) {
        let n = +lines[row++];
        numbers_to_rearrange = lines[row++].split(" ").map(x => +x);
        console.log(rearranged_numbers(numbers_to_rearrange).join(" "));
    }
}

function rearranged_numbers(arr) {
    arr.sort((a, b) => a - b);
    let len = Math.floor(arr.length / 2) * 2;
    let new_arr = [];
    for(let i = len / 2; i < len; i++) {
        new_arr.push(arr[i]);
        new_arr.push(arr[len - i - 1]);
    }
    if(new_arr.length !== arr.length) {
        new_arr.push(arr[arr.length - 1]);
    }
    return new_arr;
}

//Input
//==================================================
const readline = require('readline');
const fs = require('fs');
var bufInd=0,buffer = new Array();

function createReadObject() {
	read = readline.createInterface( {
    	input: process.stdin,
    	//input: fs.createReadStream('input.txt'),
    	output: process.stdout,
    	terminal: false
	} );
}

function loadBuffer(inpLine) {
	var t = inpLine.split(" ");
	for(var i of t)
		buffer.push(i);
}

function getString() {
	try {
		return buffer[bufInd++];
	} catch(e) {
		console.log(e);
	}
}

function inpNumber() {
	var integer = +getString();
	return integer;
}

function inpString() {
	var string = getString();
	return string;
}

//================================================

//Merge Sort
//================================================
function Merge (array,start,mid,end) {
	let lt = [],rt = [];
	for (let i = start; i < mid; i++)
		lt.push(array[i]);

	for(let i = mid; i<end; i++)
		rt.push(array[i]);

	let i=0,j=0,k=start;
	while (i<lt.length && j<rt.length) {
		if (lt[i]<=rt[j])
			array[k++] = lt[i++];
		else
			array[k++] = rt[j++];
	}

	while (i<lt.length)
		array[k++] = lt[i++];

	while (j<rt.length)
		array[k++] = rt[j++];
}

function Mergesort(array,start,end) {
	if(start == end-1)
		return;

	let mid = Math.floor((start+end)/2);
	Mergesort(array,start,mid);
	Mergesort(array,mid,end);

	Merge(array,start,mid,end);
}
//==========================================

//Main Function containing solution
function main() {
	var t;
	t = inpNumber();
	//console.log(t);

	while (t>0) {
		let n;
		let ar = new Array();
		n = inpNumber();

		for (let i = 0; i<n; i++) {
			ar.push(inpNumber());
		}

		// console.log(typeof(ar[0]));
		// for (let i = 0; i < n; i++) {
		// 	console.log("bef "+ar[i]);
		// }

		Mergesort(ar,0,ar.length);

		// for (let i = 0; i < n; i++) {
		// 	console.log(ar[i]);
		// }

		// let min = (2*1e9);
		// let pivot = -1;
		// for(let i=0; i<n-1; i++) {
		// 	if(Math.abs(ar[i+1]-ar[i]) < min) {
		// 		pivot = i;
		// 		min = ar[i+1]-ar[i];
		// 	}
		// }

		let pivot = Math.floor((n+1)/2) - 1;
		let res = ar[pivot].toString();
		let next;
		for(let i=1; i<n/2+1; i++) {
			if (pivot+i < n)
				res += " "+ar[pivot+i].toString();
			if (pivot-i > -1)
				res += " "+ar[pivot-i].toString();
		}

		console.log(res);
		t--;
	}
}

//take input and call solution function
createReadObject();
read.on('line',(inp) => {
	loadBuffer(inp);
});
read.on('close',() => {
	//console.log("finished");
	main();
});

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));
  main();
});

function readLine() {
  return inputString[currentLine++];
}

function solve(a, n) {
  a.sort((a, b) => a - b);
  let startIdx = Math.floor(n / 2);
  let res = [];
  res.push(a[startIdx]);
  for (let i = 1; i < n / 2 + 1; i++) {
    if (startIdx - i >= 0) res.push(a[startIdx - i]);
    if (startIdx + i < n) res.push(a[startIdx + i]);
  }
  return res;
}

function main() {
  const t = parseInt(readLine());
  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let a = readLine().split(' ').map((val) => parseInt(val));
    let res = solve(a, n);
    let s = '';
    for (let i = 0; i < n; i++) s += res[i] + ' ';
    console.log(s);
  }
  //process.stdout.write("hello: ");
}

var t = parseInt(readline());

function mapper(num) {
    return +num;
}
function sorter(a, b) {
    return a-b;
}

for (var i = 0; i < t; i++) {
    var n = parseInt(readline());
    var a = readline().split(' ').map(mapper).sort(sorter);

    var b = [];
    var m = Math.floor(n / 2);

    if (n % 2 !== 0) {
        b.push(a[m]);

        for (var j = 1; j <= m; j++) {
            b.push(a[m + j]);
            b.push(a[m - j]);
        }
    } else {
        for (var j = 1; j <= m; j++) {
            b.push(a[m + j - 1]);
            b.push(a[m - j]);
        }
    }

    print(b.join(' '));
}

//Input
//==================================================
const readline = require('readline');
const fs = require('fs');
var bufInd=0,buffer = new Array();

function createReadObject() {
	read = readline.createInterface( {
    	input: process.stdin,
    	//input: fs.createReadStream('input.txt'),
    	output: process.stdout,
    	terminal: false
	} );
}

function loadBuffer(inpLine) {
	var t = inpLine.split(" ");
	for(var i of t)
		buffer.push(i);
}

function getString() {
	try {
		return buffer[bufInd++];
	} catch(e) {
		console.log(e);
	}
}

function inpNumber() {
	var integer = +getString();
	return integer;
}

function inpString() {
	var string = getString();
	return string;
}

//================================================

//Merge Sort
//================================================
function Merge (array,start,mid,end) {
	let lt = [],rt = [];
	for (let i = start; i < mid; i++)
		lt.push(array[i]);

	for(let i = mid; i<end; i++)
		rt.push(array[i]);

	let i=0,j=0,k=start;
	while (i<lt.length && j<rt.length) {
		if (lt[i]<=rt[j])
			array[k++] = lt[i++];
		else
			array[k++] = rt[j++];
	}

	while (i<lt.length)
		array[k++] = lt[i++];

	while (j<rt.length)
		array[k++] = rt[j++];
}

function Mergesort(array,start,end) {
	if(start == end-1)
		return;

	let mid = Math.floor((start+end)/2);
	Mergesort(array,start,mid);
	Mergesort(array,mid,end);

	Merge(array,start,mid,end);
}
//==========================================

//Main Function containing solution
function main() {
	var t;
	t = inpNumber();
	//console.log(t);

	while (t>0) {
		let n;
		let ar = new Array();
		n = inpNumber();

		for (let i = 0; i<n; i++) {
			ar.push(inpNumber());
		}

		//Mergesort(ar,0,ar.length);
		ar.sort((a,b) => {
			return a-b;
		});

		let pivot = Math.floor((n+1)/2) - 1;
		let res = ar[pivot].toString();
		for(let i=1; i<n/2+1; i++) {
			if (pivot+i < n)
				res += " "+ar[pivot+i].toString();
			if (pivot-i > -1)
				res += " "+ar[pivot-i].toString();
		}

		console.log(res);
		t--;
	}
}

//take input and call solution function
createReadObject();
read.on('line',(inp) => {
	loadBuffer(inp);
});
read.on('close',() => {
	//console.log("finished");
	main();
});

var inputs = readline();

for(var k=0;k<inputs;k++) {
    var timeSeries = readline();
    var times = readline().split(" ").map(x=> parseInt(x));

    var output = [];
    var sortedTimes = times.sort((a, b) => a - b);

    for(var i=0,j=sortedTimes.length-1;i<=j;i++,j--){
        if(i === j) {
            output.push(times[i]);
        }else {
            if(sortedTimes.length % 2 === 0) {
                output.push(sortedTimes[i], sortedTimes[j]);
            } else {
                output.push(sortedTimes[j], sortedTimes[i]);
            }
        }

    }
    print(output.reverse().join(" "));
}

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});

let tasks = [];
rl.on('line', (line) => {
  tasks.push(line);
}).on('close', () => {
  for (let index = 2; index < tasks.length; index += 2) {
    let task = tasks[index].split(' ').map(v => +v).sort((a, b) => a - b);
    const centre = Math.ceil(task.length / 2) - 1;
    let i = 1;

    const newArr = [];
    newArr.push(task[centre])
    while(true) {
      if(task[centre + i] !== undefined) {
        newArr.push(task[centre + i]);
      }
      if (task[centre - i] !== undefined) {
        newArr.push(task[centre - i]);
      }
      if (task[centre + i] === undefined && task[centre - i] === undefined) break;

      i++;
    }

    process.stdout.write(`${newArr.join(' ')}\n`);
  }
});

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
    console.log(x);
}

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});
function readline() {
    return inputString[currentLine++];
}

//-----------main fucntion-----------

function main() {
    var T = parseInt(readline());
    while (T--) {
        var input = parseInt(readline());
        var input1 = readline().split(' ').map(x => parseInt(x));
        input1.sort((x, y) => x - y)
        var I = 0, j = input - 1, a = []
        for (var i = 0; i < input; i++) {
            if (i % 2) {
                a[i] = input1[I]
                I++
            }
            else {
                a[i] = input1[j]
                j--
            }
        }

        a.sort((x, y) => x - y)

        print(a)
    }

}

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
    console.log(x);
}

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});
function readline() {
    return inputString[currentLine++];
}

//-----------main fucntion-----------

function main() {
    var T = parseInt(readline());
    while (T--) {
        var input = parseInt(readline());
        var input1 = readline().split(' ').map(x => parseInt(x));
        input1.sort((x, y) => x - y)
        var I = 0, j = input - 1, a = []
        for (var i = 0; i < input; i++) {
            if (i % 2) {
                a[i] = input1[I]
                I++
            }
            else {
                a[i] = input1[j]
                j--
            }
        }

        a.sort((x, y) => x - y)
        print(a.join(" "))
    }

}

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
    console.log(x);
}

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});
function readline() {
    return inputString[currentLine++];
}

//-----------main fucntion-----------

function main() {
    var T = parseInt(readline());
    while (T--) {
        var input = parseInt(readline());
        var input1 = readline().split(' ').map(x => parseInt(x));
        input1.sort((x, y) => x - y)
        var I = 0, j = input - 1, a = []
        for (var i = 0; i < input; i++) {
            if (i % 2) {
                a[i] = input1[I]
                I++
            }
            else {
                a[i] = input1[j]
                j--
            }
        }

        a.sort((x, y) => y - x)

        print(a)
    }

}

"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");

function print(x) {
    console.log(x);
}

let inputString = "";
let currentLine = 0;

process.stdin.on("data", inputStdin => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});
function readline() {
    return inputString[currentLine++];
}

//-----------main fucntion-----------

function main() {
    var T = parseInt(readline());
    while (T--) {
        var input = parseInt(readline());
        var input1 = readline().split(' ').map(x => parseInt(x));
        input1.sort((x, y) => x - y)
        var I = 0, j = input - 1, a = []
        for (var i = 0; i < input; i++) {
            if (i % 2) {
                a[i] = input1[I]
                I++
            }
            else {
                a[i] = input1[j]
                j--
            }
        }

        a.sort((x, y) => y - x)
        print(a.join(" "))
    }

}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));
  main();
});

function readLine() {
  return inputString[currentLine++];
}

function solve(a, n) {
  a.sort((a, b) => a - b);
  let startIdx = Math.floor(n / 2);
  let res = [];
  res.push(a[startIdx]);
  for (let i = 1; i < n / 2 + 1; i++) {
    if (startIdx - i >= 0) res.push(a[startIdx - i]);
    if (startIdx + i < n) res.push(a[startIdx + i]);
  }
  return res;
}

function main() {
  const t = parseInt(readLine());
  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let a = readLine().split(' ').map((val) => parseInt(val));
    let res = solve(a, n);
    console.log(res);
  }
  //process.stdout.write("hello: ");
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));
  main();
});

function readLine() {
  return inputString[currentLine++];
}

function solve(a, n) {
  a.sort((a, b) => a - b);
  let startIdx = Math.floor(n / 2);
  let res = [];
  res.push(a[startIdx]);
  if (n % 2 === 0) res.push(a[startIdx - 1])
  for (let i = 1; i < n / 2 + 1; i++) {
    if (i === 1 && n % 2 === 0) {
      if (startIdx + i < n) res.push(a[startIdx + i]);
      continue;
    }
    if (startIdx - i >= 0) res.push(a[startIdx - i]);
    if (startIdx + i < n) res.push(a[startIdx + i]);
  }
  return res;
}

function main() {
  const t = parseInt(readLine());
  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let a = readLine().split(' ').map((val) => parseInt(val));
    let res = solve(a, n);
    console.log(res);
  }
  //process.stdout.write("hello: ");
}

var tests = parseInt(readline())
for (t in tests){
var size = parseInt(readline())
var array = readline().split(' ').map(c => parseInt(c))
var head = (size%2) ? parseInt(size/2 + 1): size/2
var tail = head+1, res = []
array.sort((a,b) => b-a)
while (head){
	res.push(array[head-1],array[tail-1])
	head -= 1; tail += 1
}
print(res.join(' '))
}

var t = parseInt(readline());

function mapper(num) {
    return parseInt(num);
}

for (var i = 0; i < t; i++) {
    var n = parseInt(readline());
    var a = readline().split(' ').map(mapper).sort();

    var b = [];
    var m = Math.floor(n / 2);

    if (n % 2 !== 0) {
        b.push(a[m]);

        for (var j = 1; j <= m; j++) {
            b.push(a[m + j]);
            b.push(a[m - j]);
        }
    } else {
        for (var j = 1; j <= m; j++) {
            b.push(a[m + j - 1]);
            b.push(a[m - j]);
        }
    }

    print(b.join(' '));
}

var inputs = readline();

for(var i=0;i<inputs;i++) {
    var timeSeries = readline();
    var times = readline().split(" ").map(x=> parseInt(x));
    var output = [];
    var counter = 0;

    while(times.length) {
        if(times.length >= 2) {
            var max = Math.max.apply(null, times);
            var min = Math.min.apply(null, times);
            if(counter % 2 == 0) {
                output.push(min, max);
            } else {
                output.push(max, min);

            }
            times.splice(times.indexOf(max), 1);
            times.splice(times.indexOf(min), 1);
            counter++;
        } else {
            output.push(times.pop());
        }

    }
    print(output.reverse().join(" "));
}

var inputs = readline();

for(var i=0;i<inputs;i++) {
    var timeSeries = readline();
    var times = readline().split(" ").map(x=> parseInt(x));
    var output = [];
    var counter = 0;
    times = times.sort((a, b) => a - b);

    for(var i=0,j=times.length-1;i<=j;i++,j--){
        if(i === j) {
            output.push(times[i]);
        }else {
            if(times.length % 2 === 0) {
                output.push(times[i], times[j]);
            } else {
                output.push(times[j], times[i]);
            }
        }

    }
    print(output.reverse().join(" "));
}

var inputs = readline();

for(var i=0;i<inputs;i++) {
    var timeSeries = readline();
    var times = readline().split(" ").map(x=> parseInt(x));
    var output = [];
    var counter = 0;

    while(times.length) {
        var max = Math.max.apply(null, times);
        var min = Math.min.apply(null, times);
        if(counter % 2 == 0) {
            output.push(min, max);
        } else {
            output.push(max, min);

        }
        times.splice(times.indexOf(max), 1);
        times.splice(times.indexOf(min), 1);
        counter++;

    }
    print(output.reverse().join(" "));
}

var inputs = readline();

for(var i=0;i<inputs;i++) {
    var timeSeries = readline();
    var times = readline().split(" ").map(x=> parseInt(x));
    var output = [];
    var counter = 0;

    while(times.length) {
        var max = Math.max.apply(null, times);
        var min = Math.min.apply(null, times);
        if(counter % 2 == 0) {
            output.push(min, max);
        } else {
            output.push(max, min);

        }
        times.splice(times.indexOf(max), 1);
        times.splice(times.indexOf(min), 1);
        counter++;

    }
    print(output.reverse());
}

//Input
//==================================================
const readline = require('readline');
const fs = require('fs');
var bufInd=0,buffer = new Array();

function createReadObject() {
	read = readline.createInterface( {
    	input: process.stdin,
    	//input: fs.createReadStream('input.txt'),
    	output: process.stdout,
    	terminal: false
	} );
}

function loadBuffer(inpLine) {
	var t = inpLine.split(" ");
	for(var i of t)
		buffer.push(i);
}

function getString() {
	try {
		return buffer[bufInd++];
	} catch(e) {
		console.log(e);
	}
}

function inpNumber() {
	var integer = +getString();
	return integer;
}

function inpString() {
	var string = getString();
	return string;
}

//================================================

//Merge Sort
//================================================
function Merge (array,start,mid,end) {
	let lt = [],rt = [];
	for (let i = start; i < mid; i++)
		lt.push(array[i]);

	for(let i = mid; i<end; i++)
		rt.push(array[i]);

	let i=0,j=0,k=start;
	while (i<lt.length && j<rt.length) {
		if (lt[i]<=rt[j])
			array[k++] = lt[i++];
		else
			array[k++] = rt[j++];
	}

	while (i<lt.length)
		array[k++] = lt[i++];

	while (j<rt.length)
		array[k++] = rt[j++];
}

function Mergesort(array,start,end) {
	if(start == end-1)
		return;

	let mid = Math.floor((start+end)/2);
	Mergesort(array,start,mid);
	Mergesort(array,mid,end);

	Merge(array,start,mid,end);
}
//==========================================

//Main Function containing solution
function main() {
	var t;
	t = inpNumber();
	//console.log(t);

	while (t>0) {
		let n;
		let ar = new Array();
		n = inpNumber();

		for (let i = 0; i<n; i++) {
			ar.push(inpNumber());
		}

		// console.log(typeof(ar[0]));
		// for (let i = 0; i < n; i++) {
		// 	console.log("bef "+ar[i]);
		// }

		Mergesort(ar,0,ar.length);

		// for (let i = 0; i < n; i++) {
		// 	console.log(ar[i]);
		// }

		let min = (2*1e9);
		let minInd = -1;
		for(let i=0; i<n-1; i++) {
			if(ar[i+1]-ar[i] < min) {
				minInd = i;
				min = ar[i+1]-ar[i];
			}
		}

		let res = ar[minInd].toString();
		let next;
		for(let i=1; i<n; i++) {
			if(minInd-i<0) {
				minInd += i;
				next = 1;
				break;
			}
			else if(minInd+i > n-1) {
				minInd -= i;
				next = -1;
				break;
			}
			else {
				res += " "+ar[minInd+i].toString();
				res += " "+ar[minInd-i].toString();
			}
		}

		while(minInd < n && minInd > -1) {
			res += " "+ar[minInd].toString();
			minInd += next;
		}

		console.log(res);
		t--;
	}
}

//take input and call solution function
createReadObject();
read.on('line',(inp) => {
	loadBuffer(inp);
});
read.on('close',() => {
	//console.log("finished");
	main();
});

//Input
//==================================================
const readline = require('readline');
const fs = require('fs');
var buffer = new Array();

function createReadObject() {
	read = readline.createInterface( {
    	input: process.stdin,
    	//input: fs.createReadStream('input.txt'),
    	output: process.stdout,
    	terminal: false
	} );
}

function loadBuffer(inpLine) {
	var t = inpLine.split(" ");
	for(var i of t)
		buffer.push(i);
}

function getString() {
	try {
		return buffer.shift();
	} catch(e) {
		console.log(e);
	}
}

function inpNumber() {
	var integer = +getString();
	return integer;
}

function inpString() {
	var string = getString();
	return string;
}

//================================================

//Main Function containing solution
function main() {
	var t;
	t = inpNumber();
	//console.log(t);

	while (t>0) {
		let n;
		let ar = new Array();
		n = inpNumber();

		for (let i = 0; i<n; i++) {
			ar.push(inpNumber());
		}

		ar.sort();

		let min = (2*1e9);
		let minInd = -1;
		for(let i=0; i<n-1; i++) {
			if(ar[i+1]-ar[i] < min) {
				minInd = i;
				min = ar[i+1]-ar[i];
			}
		}

		let res = ar[minInd].toString();
		let next;
		for(let i=1; i<n; i++) {
			if(minInd-i<0) {
				minInd += i;
				next = 1;
				break;
			}
			else if(minInd+i > n-1) {
				minInd -= i;
				next = -1;
				break;
			}
			else {
				res += " "+ar[minInd+i].toString();
				res += " "+ar[minInd-i].toString();
			}
		}

		while(minInd < n && minInd > -1) {
			res += " "+ar[minInd].toString();
			minInd += next;
		}

		console.log(res);
		t--;
	}
}

//take input and call solution function
createReadObject();
read.on('line',(inp) => {
	loadBuffer(inp);
});
read.on('close',() => {
	//console.log("finished");
	main();
});

//Input
//==================================================
const readline = require('readline');
const fs = require('fs');
var bufInd=0,buffer = new Array();

function createReadObject() {
	read = readline.createInterface( {
    	input: process.stdin,
    	//input: fs.createReadStream('input.txt'),
    	output: process.stdout,
    	terminal: false
	} );
}

function loadBuffer(inpLine) {
	var t = inpLine.split(" ");
	for(var i of t)
		buffer.push(i);
}

function getString() {
	try {
		return buffer[bufInd++];
	} catch(e) {
		console.log(e);
	}
}

function inpNumber() {
	var integer = +getString();
	return integer;
}

function inpString() {
	var string = getString();
	return string;
}

//================================================

//Merge Sort
//================================================
function Merge (array,start,mid,end) {
	let lt = [],rt = [];
	for (let i = start; i < mid; i++)
		lt.push(array[i]);

	for(let i = mid; i<end; i++)
		rt.push(array[i]);

	let i=0,j=0,k=start;
	while (i<lt.length && j<rt.length) {
		if (lt[i]<=rt[j])
			array[k++] = lt[i++];
		else
			array[k++] = rt[j++];
	}

	while (i<lt.length)
		array[k++] = lt[i++];

	while (j<rt.length)
		array[k++] = rt[j++];
}

function Mergesort(array,start,end) {
	if(start == end-1)
		return;

	let mid = Math.floor((start+end)/2);
	Mergesort(array,start,mid);
	Mergesort(array,mid,end);

	Merge(array,start,mid,end);
}
//==========================================

//Main Function containing solution
function main() {
	var t;
	t = inpNumber();
	//console.log(t);

	while (t>0) {
		let n;
		let ar = new Array();
		n = inpNumber();

		for (let i = 0; i<n; i++) {
			ar.push(inpNumber());
		}

		// console.log(typeof(ar[0]));
		// for (let i = 0; i < n; i++) {
		// 	console.log("bef "+ar[i]);
		// }

		Mergesort(ar,0,ar.length);

		// for (let i = 0; i < n; i++) {
		// 	console.log(ar[i]);
		// }

		let min = (2*1e9);
		let minInd = -1;
		for(let i=0; i<n-1; i++) {
			if(Math.abs(ar[i+1]-ar[i]) < min) {
				minInd = i;
				min = ar[i+1]-ar[i];
			}
		}

		let res = ar[minInd].toString();
		let next;
		for(let i=1; i<n; i++) {
			if(minInd-i<0) {
				minInd += i;
				next = 1;
				break;
			}
			else if(minInd+i > n-1) {
				minInd -= i;
				next = -1;
				break;
			}
			else {
				res += " "+ar[minInd+i].toString();
				res += " "+ar[minInd-i].toString();
			}
		}

		while(minInd < n && minInd > -1) {
			res += " "+ar[minInd].toString();
			minInd += next;
		}

		console.log(res);
		t--;
	}
}

//take input and call solution function
createReadObject();
read.on('line',(inp) => {
	loadBuffer(inp);
});
read.on('close',() => {
	//console.log("finished");
	main();
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});

let tasks = [];
rl.on('line', (line) => {
  tasks.push(line);
}).on('close', () => {
  for (let index = 2; index < tasks.length; index += 2) {
    let task = tasks[index].split(' ').map(v => +v).sort((a, b) => a - b);
    const centre = Math.ceil(task.length / 2);
    let i = 1;

    const newArr = [];
    newArr.push(task[centre])
    while(true) {
      if(task[centre + i] !== undefined) {
        newArr.push(task[centre + i]);
      }
      if (task[centre - i] !== undefined) {
        newArr.push(task[centre - i]);
      }
      if (task[centre + i] === undefined && task[centre - i] === undefined) break;

      i++;
    }

    process.stdout.write(`${newArr.join(' ')}\n`);
  }
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});

let tasks = [];
rl.on('line', (line) => {
  tasks.push(line);
}).on('close', () => {
  for (let index = 2; index < tasks.length; index += 2) {
    let task = tasks[index].split(' ').map(v => +v).sort((a, b) => a - b);
    const centre = Math.floor(task.length / 2) - 1;
    let i = 1;

    const newArr = [];
    newArr.push(task[centre])
    while(true) {
      if(task[centre + i] !== undefined) {
        newArr.push(task[centre + i]);
      }
      if (task[centre - i] !== undefined) {
        newArr.push(task[centre - i]);
      }
      if (task[centre + i] === undefined && task[centre - i] === undefined) break;

      i++;
    }

    process.stdout.write(`${newArr.join(' ')}\n`);
  }
});


function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

function div(a, b) {
   return Math.floor(a / b);
}

function solve() {
   var nxt = readArray(BigInt);
   var n = nxt[0];
   var x = nxt[1];
   var t = nxt[2];
   var maxAngry = t / x;
   if (n <= maxAngry + 1n) {
      write(n * (n - 1n) / 2n);
      return;
   }
   write((maxAngry * (maxAngry - 1n) / 2n) + (maxAngry * (n - maxAngry)));
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const assert = (condition) => { if (!condition) throw new Error("Assertion failed"); }
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg2 = Math.log2;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };
const initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
const ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);
const isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 06/21/21 morning
const solve = (n, x, t) => {
    let each = t / x;
    let len = mill(n, each);
    let res = (n - len) * each + (len - 1n) * len / 2n;
    pr(res.toString());
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => ll(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i][1], input[i][2]);
            i++;
        }
    });
};

main()

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
// import * as readline from 'readline'
// const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
// const ask = (query: string) => new Promise<string>((resolve) => rl.question(query, resolve))
// // Don't forget `rl.close()`.
const INT = Math.floor;
Array.prototype.last = function () {
    return this.length === 0 ? undefined : this[this.length - 1];
};
Array.prototype.isEmpty = function () {
    return this.length === 0;
};
const less = (a, b) => (a == b ? 0 : a < b ? -1 : 1);
const greater = (a, b) => (a == b ? 0 : a < b ? 1 : -1);
const bigIntMax = (...args) => args.reduce((m, e) => (e > m ? e : m));
const bigIntMin = (...args) => args.reduce((m, e) => (e < m ? e : m));
const bigIntAbs = (arg) => (arg < 0 ? -arg : arg);
function read_stdin() {
    return fs.readFileSync(process.env.NODE_ENV === 'debug' ? stdin : process.stdin.fd, 'utf8');
}
class Input {
    constructor(str) {
        this.index = 0;
        this.inputs = (str ? str : read_stdin()).split(/\s+/);
    }
    number() {
        return Number(this.inputs[this.index++]);
    }
    numbers(n) {
        return this.inputs.slice(this.index, (this.index += n)).map(Number);
    }
    bigint() {
        return BigInt(this.inputs[this.index++]);
    }
    bigints(n) {
        return this.inputs.slice(this.index, (this.index += n)).map(BigInt);
    }
    word() {
        return this.inputs[this.index++];
    }
    words(n) {
        return this.inputs.slice(this.index, (this.index += n));
    }
}
function array(len, init) {
    return Array(len).fill(init);
}
function array2(h, w, init) {
    return array(h, 0).map(() => array(w, init));
}
function main() {
    const input = new Input();
    const k = input.number();
    const ans = Array(k);
    for (let i = 0; i < k; i++) {
        const [n, x, t] = input.bigints(3);
        const c = t / x;
        const m = bigIntMin(c, n);
        ans[i] = n * c - (c * (c + 1n)) / 2n + ((c - m) * (c - m + 1n)) / 2n;
    }
    console.log(ans.join('\n'));
}
main();
//# sourceMappingURL=aoj.js.map

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, d, tot] = readline()
      .trim()
      .split(" ")
      .map((cur) => BigInt(cur));
    let l = tot / d;
    if (l >= n) {
      n--;
      console.log((n * (n + 1n)) / 2n + "");
      continue;
    }
    n--;
    let i = (n - (l - 1n)) * l;
    let j = n - (n - (l - 1n));
    i += (j * (j + 1n)) / 2n;
    console.log(i + "");
  }
};
solve();

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var args = lines[l++].split(' ').map(Number)
        console.log(solve(args));
    }
});

function solve([n, x, t]) {
    const k = Math.min(n, Math.floor(t / x))
    const rest = BigInt(k - 1 + 1) * BigInt(k - 1) / 2n
    const br = BigInt(n - k) * BigInt(k) + rest
    return br.toString()
}

const lib = require('readline');
const rl = lib.createInterface({
    input: process.stdin,
    output: process.stdout
});

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        let n,x,t;
        [n,x,t] = (await getLine()).split(' ').map(num => parseInt(num));
        if (t<x) {
           console.log(0);
           continue;
        }
        let bad = Math.floor(t/x);
        bad = BigInt(bad);
        n = BigInt(n);
        if (bad > n) {
            console.log((n * (n- BigInt(1)) / BigInt(2)).toString());
        }
        else {
            console.log((n * bad - bad * (bad + BigInt(1)) / BigInt(2)).toString());
        }

    }
}

solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, d, tot] = readline()
      .trim()
      .split(" ")
      .map((cur) => BigInt(cur));
    let l = tot / d;
    if (l >= n) {
      l--;
      console.log((l * (l + 1n)) / 2n + "");
      continue;
    }
    n--;
    let i = (n - (l - 1n)) * l;
    let j = n - (n - (l - 1n));
    i += (j * (j + 1n)) / 2n;
    console.log(i + "");
  }
};
solve();

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var args = lines[l++].split(' ').map(Number)
        console.log(solve(args));
    }
});

function solve([n, x, t]) {
    const k = Math.floor(t / x)
    const rest = BigInt(k - 1 + 1) * BigInt(k - 1) / 2n
    const br = BigInt(n - k) * BigInt(k) + rest
    return br.toString()
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var args = lines[l++].split(' ').map(Number)
        console.log(solve(args));
    }
});

function solve([n, x, t]) {
    const k = Math.floor(t / x)
    const rest = (k - 1 + 1) * (k - 1) / 2
    return (n - k) * k + rest
}

const lib = require('readline');
const rl = lib.createInterface({
    input: process.stdin,
    output: process.stdout
});

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        let n,x,t;
        [n,x,t] = (await getLine()).split(' ').map(num => parseInt(num));
        if (t<x) {
           console.log(0);
           continue;
        }
        let bad = Math.floor(t/x);
        bad = BigInt(bad);
        n = BigInt(n);
        console.log((n * bad - bad*(bad+BigInt(1))/BigInt(2)).toString());

    }
}

solve();

const lib = require('readline');
const rl = lib.createInterface({
    input: process.stdin,
    output: process.stdout
});

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        let n,x,t;
        [n,x,t] = (await getLine()).split(' ').map(num => parseInt(num));
        if (t<x) {
           console.log(0);
           continue;
        }
        let bad = Math.floor(t/x);
        console.log(n * bad - bad*(bad+1)/2);

    }
}

solve();

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const assert = (condition) => { if (!condition) throw new Error("Assertion failed"); }
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg2 = Math.log2;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };
const initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
const ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);
const isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 06/21/21 morning
const solve = (n, x, t) => {
    let each = t / x >> 0;
    let len = mi(n, each);
    pr((n - len) * each + (len - 1) * len / 2);
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i][1], input[i][2]);
            i++;
        }
    });
};

main()

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
// import * as readline from 'readline'
// const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
// const ask = (query: string) => new Promise<string>((resolve) => rl.question(query, resolve))
// // Don't forget `rl.close()`.
const INT = Math.floor;
Array.prototype.last = function () {
    return this.length === 0 ? undefined : this[this.length - 1];
};
Array.prototype.isEmpty = function () {
    return this.length === 0;
};
const less = (a, b) => (a == b ? 0 : a < b ? -1 : 1);
const greater = (a, b) => (a == b ? 0 : a < b ? 1 : -1);
const bigIntMax = (...args) => args.reduce((m, e) => (e > m ? e : m));
const bigIntMin = (...args) => args.reduce((m, e) => (e < m ? e : m));
const bigIntAbs = (arg) => (arg < 0 ? -arg : arg);
function read_stdin() {
    return fs.readFileSync(process.env.NODE_ENV === 'debug' ? stdin : process.stdin.fd, 'utf8');
}
class Input {
    constructor(str) {
        this.index = 0;
        this.inputs = (str ? str : read_stdin()).split(/\s+/);
    }
    number() {
        return Number(this.inputs[this.index++]);
    }
    numbers(n) {
        return this.inputs.slice(this.index, (this.index += n)).map(Number);
    }
    bigint() {
        return BigInt(this.inputs[this.index++]);
    }
    bigints(n) {
        return this.inputs.slice(this.index, (this.index += n)).map(BigInt);
    }
    word() {
        return this.inputs[this.index++];
    }
    words(n) {
        return this.inputs.slice(this.index, (this.index += n));
    }
}
function array(len, init) {
    return Array(len).fill(init);
}
function array2(h, w, init) {
    return array(h, 0).map(() => array(w, init));
}
function main() {
    const input = new Input();
    const k = input.number();
    const ans = Array(k);
    for (let i = 0; i < k; i++) {
        const [n, x, t] = input.bigints(3);
        const c = t / x;
        ans[i] = n * c - (c * (c + 1n)) / 2n;
    }
    console.log(ans.join('\n'));
}
main();
//# sourceMappingURL=aoj.js.map


//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	//1365D
	var t = nextInt();
	var output = new Array(t);
	var dy = [-1,0,1,0];
	var dx = [0,-1,0,1];
	for(var i = 0; i < t; i++){
		var one = nextIntArray();
		var N = one[0];
		var M = one[1];
		var list = new Array(N);
		var isG = false;
		var isB = false;
		var bList = [];
		var gList = [];
		for(var j = 0; j < N; j++){
			list[j] = nextCharArray();
			for(var k = 0; k < M; k++){
				if(list[j][k] == "G"){
					isG = true;
					gList.push([j,k]);
				}
				if(list[j][k] == "B"){
					isB = true;
					bList.push([j,k]);
				}
			}
		}
		if(isG){
			var gCount = 0;
			//両方いるときがヤバイ
			//とりあえずBの4方を防いでしまう
			for(var j = 0; j < bList.length; j++){
				for(var k = 0; k < dy.length; k++){
					var tonariY = bList[j][0] + dy[k];
					var tonariX = bList[j][1] + dx[k];
					if(tonariY < N && tonariY >= 0 && tonariX < M && tonariX >= 0){
						if(list[tonariY][tonariX] != "G" && list[tonariY][tonariX] != "B"){
							list[tonariY][tonariX] = "#";
						}
					}
				}
			}
			function bfs(startY, startX){
				var access = new Array(N);
				var sIndex = 0;
				var eIndex = 1;
				for(var l = 0; l < N; l++){
					access[l] = new Array(M).fill(false);
				}
				var queue = new Array(4000);
				queue[0] = [startY, startX];
				access[startY][startX] = true;
				while(sIndex != eIndex){
					var tmp = queue[sIndex];
					sIndex++;
					var y = tmp[0];
					var x = tmp[1];
					if(list[y][x] == "B"){
						isOK = false;
						return;
					}else if(list[y][x] == "G"){
						gCount++;
					}
					for(var l = 0; l < dy.length; l++){
						var nextY = y + dy[l];
						var nextX = x + dx[l];
						if(nextY < N && nextY >= 0 && nextX < M && nextX >= 0){
							if(!access[nextY][nextX] && list[nextY][nextX] != "#"){
								access[nextY][nextX] = true;
								queue[eIndex] = [nextY, nextX];
								eIndex++;
							}
						}
					}
				}
				return;
			}
			var isOK = true;
			bfs(N - 1, M - 1);
			if(!isOK || gCount != gList.length){
				output[i] = "No";
				continue;
			}
			output[i] = "Yes";
		}else{
			output[i] = "Yes";
		}
	}
	myout(myconv(output,9));
}

// const bg = require('big-integer')
process.stdin.resume()
process.stdin.setEncoding('utf-8')
const MOD1 = 1000000007

function alpha(c = 'A') {
  return [...{
    _b: c === 'A' ? 65 : 97,
    _i: -1,
    [Symbol.iterator]() {
      return this
    },
    next() {
      this._i++
      if (this._i === 26) return {done: true}
      else return {done: false, value: String.fromCharCode(this._i + this._b)}
    }
  }]
}

class rc {
  static construct() {
    this.input = ''
    this.ptr = 0
  }
  static readString() {
    return this.input[this.ptr++]
  }

  static readStrings() {
    return this.input[this.ptr++].split(' ')
  }

  static readInt() {
    return +this.readString()
  }

  static readInts() {
    return this.readStrings().map(a => +a)
  }

  static readBigInteger() {
    return bg(this.readString())
  }

  static readBigIntegers() {
    return this.readStrings().map(a => bg(a))
  }
}

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if (inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

Array.fill = function(n, m, no = 0) {
  const a = new Array(n)
  for(let i = 0; i < n; i++) a[i] = new Array(m).fill(no)
  return a
}

rc.construct()
// bc.construct()
process.stdin.on('data', (i) => {
  rc.input += i
})

process.stdin.on('end', () => {
  rc.input = rc.input.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  let hasTestCases = true
  if(hasTestCases) {
    let t = rc.readInt()
    while(t--) main()
  }
  else main()
})

function main() {
  const [n, m] = rc.readInts()
  const a = new Array(n)
  for (let i = 0; i < n; i++) a[i] = rc.readString().split('')

  let canPass = true

  // wr(a)

  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if(a[i][j] === 'B') {
        canPass = checkBorder(i - 1, j) && checkBorder(i, j - 1) && checkBorder(i + 1, j) && checkBorder(i, j + 1)
        if(!canPass) {
          wr('No')
          return
        }
      }
    }
  }

  const r = Array.fill(n, m)

  let queue = []
  if(a[n - 1][m - 1] !== '#') queue.push([n - 1, m - 1])

  while(queue.length) {
    let newQueue = []
    queue.forEach(([i, j]) => {
      r[i][j] = 1
      markR(i - 1, j)
      markR(i + 1, j)
      markR(i, j - 1)
      markR(i, j + 1)
      function  markR(i, j) {
        if(i >= 0 && i < n && j >= 0 && j < m) {
          if((a[i][j] === 'G' || a[i][j] === '.') && !r[i][j]) {
            r[i][j] = 1
            newQueue.push([i, j])
          }
        }
      }
    })
    queue = newQueue
  }

  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if(a[i][j] === 'G' && !r[i][j]) {
        wr('No')
        return
      }
    }
  }

  wr('Yes')

  function checkBorder(i, j) {
    if(i >= 0 && i < n && j >= 0 && j < m) {
      if(a[i][j] === 'G') {
        return false
      }
      if(a[i][j] !== 'B') a[i][j] = '#'
    }
    return true
  }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
/**
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
**/

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

Array.fill = function(n, m, no = 0) {
  const a = new Array(n)
  for(let i = 0; i < n; i++) a[i] = new Array(m).fill(no)
  return a
}

function main() {
    let range = parseInt(readline());

    for(let r = 0;r<range;r++) {
        solve();
    }
}

function solve() {
    let [n, m] = readline().split(" ").map(Number);

        const a = [];
        for(let i=0;i<n;i++) {
            a.push(readline().split(""));
        }

        let canPass = true;

        for(let i=0;i<n;i++) {
            for(let j=0;j<m;j++) {
                if(a[i][j] === 'B') {
                    canPass = checkBorder(i, j-1) && checkBorder(i - 1, j) && checkBorder(i+1, j) && checkBorder(i, j+1);
                    if(canPass === false) {
                        console.log('No');
                        return;
                    }
                }
            }
        }

        let quene = [];
        if(a[n-1][m-1] !== '#') {
            quene.push([n-1, m-1]);
        }

        const r = Array.fill(n, m)

        while(quene.length) {
            let newQuene = [];
            quene.forEach(([i, j]) => {
                r[i][j] = 1;
                bfs(i, j - 1);
                bfs(i - 1, j);
                bfs(i, j + 1);
                bfs(i + 1, j);

                function bfs(i, j) {
                    if(i >= 0 && j >= 0 && i < n && j < m) {
                        if((a[i][j] === 'G' || a[i][j] === '.') && !r[i][j]) {
                            r[i][j] = 1;
                            newQuene.push([i, j]);
                        }
                    }
                }
            });
            quene = newQuene;
        }

        for(let i=0;i<n;i++) {
            for(let j=0;j<m;j++) {
                if(a[i][j] === 'G' && !r[i][j]) {
                    console.log('No');
                    return;
                }
            }
        }

        console.log('Yes');

        function checkBorder(i, j) {
            if(i >= 0 && i < n && j >= 0 && j < m) {
              if(a[i][j] === 'G') {
                return false
              }
              if(a[i][j] !== 'B') a[i][j] = '#'
            }
            return true
        }
}

//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var t = nextInt();
	var output = new Array(t);
	var dy = [-1,0,1,0];
	var dx = [0,-1,0,1];
	for(var i = 0; i < t; i++){
		var one = nextIntArray();
		var N = one[0];
		var M = one[1];
		var list = new Array(N);
		var isG = false;
		var isB = false;
		for(var j = 0; j < N; j++){
			list[j] = nextCharArray();
			if(list[j].indexOf("G") != -1){
				isG = true;
			}
			if(list[j].indexOf("B") != -1){
				isB = true;
			}
		}
		if(isG && isB){
			//両方いるときがヤバイ
			//とりあえずBの4方を防いでしまう
			for(var j = 0; j < N; j++){
				for(var k = 0; k < M; k++){
					if(list[j][k] == "B"){
						for(var l = 0; l < dy.length; l++){
							var tonariY = j + dy[l];
							var tonariX = k + dx[l];
							if(tonariY < N && tonariY >= 0 && tonariX < M && tonariX >= 0){
								if(list[tonariY][tonariX] != "G" && list[tonariY][tonariX] != "B"){
									list[tonariY][tonariX] = "#";
								}
							}
						}
					}
				}
			}
			function bfs(startY, startX, isGood){
				var access = new Array(N);
				for(var l = 0; l < N; l++){
					access[l] = new Array(M).fill(false);
				}
				var queue = [[startY, startX]];
				access[startY][startX] = true;
				while(queue.length > 0){
					var tmp = queue.shift();
					var y = tmp[0];
					var x = tmp[1];
					if(y == N - 1 && x == M - 1){
						return isGood;
					}
					for(var l = 0; l < dy.length; l++){
						var nextY = y + dy[l];
						var nextX = x + dx[l];
						if(nextY < N && nextY >= 0 && nextX < M && nextX >= 0){
							if(!access[nextY][nextX] && list[nextY][nextX] != "#"){
								access[nextY][nextX] = true;
								queue.push([nextY, nextX]);
							}
						}
					}
				}
				return !isGood;
			}
			var isOK = true;
			for(var j = 0; j < N; j++){
				for(var k = 0; k < M; k++){
					if(list[j][k] == "B"){
						var res = bfs(j,k,false);
						if(!res){
							isOK = false;
						}
					}
				}
			}
			if(!isOK){
				output[i] = "No";
				continue;
			}
			for(var j = 0; j < N; j++){
				for(var k = 0; k < M; k++){
					if(list[j][k] == "G"){
						var res = bfs(j,k,true);
						if(!res){
							isOK = false;
						}
					}
				}
			}
			if(!isOK){
				output[i] = "No";
				continue;
			}
			output[i] = "Yes";
		}else{
			output[i] = "Yes";
		}
	}
	myout(myconv(output,9));
}


T = readline()

while(T--){
      n = readline()
      a = readline().split(' ').map(el => +el)

      ans = 'YES'
      for(i = 1; i< n; i++){
            if(a[i]%a[0] != 0){
                  ans = 'NO'
                  break
            }
      }

      print(ans)
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = readline().split(" ");
    var flag = true;
    for (var j = 1; j < caseLength; j++)
    {
        var value = parseInt(caseArray[j]) - parseInt(caseArray[j-1]);
        if (value % parseInt(caseArray[0]) !== 0)
        {
            flag = false;
            break;
        }
    }
    if (flag) print("YES"); else print("NO");
}

var tests = parseInt(readline());
    for (var t=0; t < tests; t++) {
        var n = parseInt(readline());
        var arr = readline().split(' ').map(x=>parseInt(x));
        var ans = 'yes';
        for (var i=1; i<n; i++) {
            if (arr[i] % arr[0] != 0) {
                ans = 'no';
                break;
            }

        }
        print(ans);
    }

const main = () => {

	var t = readInt();
	var allans = [];
	for (var zz = 0; zz < t; zz++) {
		var n = readInt();
		var a = readIntArr();
		var z = a[0];
		var ans = 'YES';
		for (var i = 1; i < n; i++)
			if (a[i] % z !== 0)
				ans = 'NO';
		allans.push(ans);
	}
	multiLineArrayPrint(allans);

	return;
}

const readInt = () => parseInt(readline());
const readString = () => readline();
const readIntArr = () => readline().split(" ").map(zzzz => parseInt(zzzz));
const parseLong = (string) => { // javascript's largest long is < (1<<62)
	var n = string.length;
	var res = 0;
	for (var i = 0; i < n; i++) {
		res *= 10;
		res += parseInt(string[i]);
	}
	return res;
}
const readLong = () => parseLong(readLong());
const readLongArr = () => readline().split(" ").map(zzzz => parseLong(zzzz));
const oneLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join(' '));
const multiLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join('\n'));
const multiLineArrayOfArraysPrint = (arr) => print(arr.map(yyyy => yyyy.map(zzzz => zzzz.toString()).join(' ')).join('\n'));
const makeArr = (defaultVal, dimensionsArr) => {
	var n = dimensionsArr.length;
	if (n === 1) return Array(dimensionsArr[0]).fill(defaultVal);
	else {
		var temp = [];
		for (var i = 0; i < dimensionsArr[0]; i++)
			temp.push(makeArr(defaultVal, dimensionsArr.slice(1)));
		return temp;
	}
}

for (_ = 0; _ < 1; _++) {
	main();
}

// newline for testing
 //newline for testing
// codeforces js cannot use "let" keyword. use "var" instead
// codeforces js cannot destructure arrays

        process.stdin.resume();
        process.stdin.setEncoding('utf-8');
        let inputString = '', currentLine = 0;
        process.stdin.on('data', inputStdin => { inputString += inputStdin; });
        process.stdin.on('end', _ => {
            inputString = inputString.trim().split('\n').map(string => string.trim());
            main();
        });
        function readLine() {
            return inputString[currentLine++];
        }

        function main() {
            const t = parseInt(readLine(), 10);
            for(let i = 0; i < t; i++){
                const n = readLine();
                const arr = readLine().split(' ').map(p => +p);
                let result = myFunc(arr, n);
                console.log(result);
            }
        }

        function myFunc(arr, n){
            for(let i = 1; i < n; i++){
                if(arr[i] % arr[0] != 0) return 'NO';
            }
            return 'YES';
        }

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', (inputStdin) => {
  inputString += inputStdin;
});

process.stdin.on('end', (_) => {
  inputString = inputString
    .trim()
    .split('\n')
    .map((string) => {
      return string.trim();
    });

  main();
});

function readline() {
  return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  const t = readline();

  for (let i = 0; i < t; i++) {
    const n = parseInt(readline(), 10);

    const a = readline()
      .split(' ')
      .map((num) => +num);

    // console.log(`=----------------testcase ${i + 1}----------------=`);
    // console.log('q', q);
    // console.log('a', a);

    const output = f(n, a);

    console.log(output);
  }
}

function f(n, a) {
  return a.slice(1).some(x => x % a[0]) ? 'NO' : 'YES'
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        readline();
        let arr = readline().split(' ').map(Number);
        let yes = true;
        for (let i = 1; i < arr.length; i++) {
            if (arr[i] % arr[0] !== 0) yes= false;
        }

        output(yes ? 'YES' : 'NO');
    }
}

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function main(){
    var tests = parseInt(readline());
    for (let t = 0;t < tests; ++t) {
        var n = parseInt(readline());
        var a = readline().split(" ").map(x=> parseInt(x));
        let res = true;
        for (let i = 0; i < n;++i) {
            if (a[i] % a[0] != 0) {
                res = false;
            }
        }
        if (res) {
            console.log('YES');
        } else {
            console.log('NO');
        }
    }

}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		for(var i = N - 1; i > 0; i--){
			list[i] %= list[i - 1];
		}
		var ok = true;
		for(var i = 1; i < N; i++){
			if(list[i] % list[0] != 0){
				ok = false;
			}
		}
		myout((ok) ? "YES" : "NO");
	}
}

'use strict';

function solve(n, a) {
  for (let i = 1; i < n; i++) {
    if (a[i] % a[0] !== 0) return 'NO';
  }
  return 'YES';
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let div = arr[0],
      ans = true;
    for (let i = 1; i < n; i++) {
      if (arr[i] % div !== 0) {
        ans = false;
        break;
      }
    }
    console.log(`${ans === true ? "YES" : "NO"}`);
  }
};
solve();

var tests = parseInt(readline());
    for (var t=0; t < tests; t++) {
        var n = parseInt(readline());
        var arr = readline().split(' ').map(x=>parseInt(x));
        var ans = 'yes';
        for (var i=1; i<n; i++) {
            if (arr[i-1] == 1) {
                break;
            }
            if (arr[i] % arr[i-1] != 0) {
                ans = 'no';
                break;
            }

        }
        print(ans);
    }

    process.stdin.resume();
    process.stdin.setEncoding('utf-8');
    let inputString = '', currentLine = 0;
    process.stdin.on('data', inputStdin => { inputString += inputStdin; });
    process.stdin.on('end', _ => {
        inputString = inputString.trim().split('\n').map(string => string.trim());
        main();
    });
    function readLine() {
        return inputString[currentLine++];
    }

    function main() {
        const t = parseInt(readLine(), 10);
        for(let i = 0; i < t; i++){
            const n = readLine();
            const arr = readLine().split(' ').map(p => +p);
            let result = myFunc(arr, n);
            console.log(result);
        }
    }

    function myFunc(arr, n){
        for(let i = 1; i < n; i++){
            if(arr[i] < arr[i-1] || arr[i] % arr[0] != 0) return 'NO';
        }
        return 'YES';
    }

    process.stdin.resume();
    process.stdin.setEncoding('utf-8');
    let inputString = '', currentLine = 0;
    process.stdin.on('data', inputStdin => { inputString += inputStdin; });
    process.stdin.on('end', _ => {
        inputString = inputString.trim().split('\n').map(string => string.trim());
        main();
    });
    function readLine() {
        return inputString[currentLine++];
    }

    function main() {
        const t = parseInt(readLine(), 10);
        for(let i = 0; i < t; i++){
            const n = readLine();
            const arr = readLine().split(' ').map(p => +p);
            let result = myFunc(arr, n);
            console.log(result);
        }
    }

    function myFunc(arr, n){
        for(let i = 1; i < n; i++){
            if(arr[i] < arr[i-1]) return 'NO';
        }
        return 'YES';
        return 'YES';
    }

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', (inputStdin) => {
  inputString += inputStdin;
});

process.stdin.on('end', (_) => {
  inputString = inputString
    .trim()
    .split('\n')
    .map((string) => {
      return string.trim();
    });

  main();
});

function readline() {
  return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  const t = readline();

  for (let i = 0; i < t; i++) {
    const n = parseInt(readline(), 10);

    const a = readline().split(' ').map(num => +num);

    // console.log(`=----------------testcase ${i + 1}----------------=`);
    // console.log('q', q);
    // console.log('a', a);

    const output = f(n, a);

    console.log(output);
  }
}

function f(n, a) {

  for (let i = 1; i < n; i++) {
    if(a[i] < a[i-1]) return 'NO'
  }

  return 'YES';
}


let dataitr;
let stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", (input) => {
  stdin_input += input;
});
process.stdin.on("end", () => {
  dataitr = stdin_input.split("\n").values();
  main();
});

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(" ");
const rna = () => ra().map((x) => Number(x));
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  let T = rn();
  while (T--) {
    const n = rn();
    const a = rna();

    let ans = -1;
    const types = {};
    let minBetween = n + 1;
    for (let i = 0; i < n; i++) {
      if (types[`${a[i]}`] === undefined) {
        types[`${a[i]}`] = i;
        continue;
      }

      const last = types[`${a[i]}`];
      const between = i - last;

      if (between === 1) {
        ans = n - 1;
        break;
      }

      types[`${a[i]}`] = i;

      if (minBetween > between) {
        minBetween = between;
      }
    }

    if (ans === -1) {
      ans = n - minBetween;
    }

    console.log(ans);
  }
}

let _inputLines;
let _lineNumber = 0;
let inputReader = _inputReader ();

function _main() {

	_inputLines = _inputData.trim().split('\n').map((string) => {
		return string.trim();
	});;

	let t = inputReader.readNumber();

	function solve() {
	  let n = inputReader.readNumber();
	  let v = inputReader.readNumberArray();
	  let m = new Map();
	  let ans = -1;
	  for(let i = 0; i < n; i++) {
	    if(m.has(v[i])) {
	      ans = Math.max(ans, m.get(v[i]) + n - i);
	    }
	    m.set(v[i], i);
	  }
	  console.log(ans);
	}

	while (t--) {
	  solve();
	}

	//cp-convert -s CP.js -d CP-CF.js

}

var _inputData = '';
function cacheInput(data) {
	_inputData += data;
}

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', cacheInput).on('end', _main);

function _inputReader () {
	function readNumber(){
		return Number(_inputLines[_lineNumber++]);
	}

	function readNumberArray(){
		return _inputLines[_lineNumber++].split(' ').map(val => Number(val));
	}

	return {
		readNumber,
		readNumberArray,
	}
}

const solve = arr=>{
   let obj = {};
     let max = 0;
     for(let i=0;i<arr.length;i++){
          if(obj[arr[i]]!==undefined){
               let t = arr.length - (i - obj[arr[i]]);
               max = Math.max(max,t);
               obj[arr[i]] = i;
          }
          else obj[arr[i]] = i;
     }
     if(max===0) console.log(-1);
     else console.log(max);
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(arr);
  }
}
main();

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    // const min = {}
    // const max = {}
    const p = {}
    arr.forEach((x, i) => {
        p[x] = p[x] || []
        p[x].push(i)
        // min[x] = (x in min) ? Math.min(min[x], i) : i
        // max[x] = (x in max) ? Math.max(max[x], i) : i
    })
    // console.log(min, max)
    let ans = -1
    for (let x in p) {
        // const a = min[x]
        // const b = max[x]
        if (p[x].length < 2) continue
        // if (a !== b) {
        //     const prev = Math.min(a, b)
        //     const after = Math.min(n - 1 - a, n - 1 - b)
        //     ans = Math.max(ans, prev + 1 + after)
        // }
        for (let i = 1; i < p[x].length; i++) {
            const a = p[x][i - 1]
            const b = p[x][i]
            ans = Math.max(ans, a + 1 + (n - 1 - b))
        }
    }
    return ans
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

const INF = 1e9;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		const mp = new Map();
		let mnd = INF;
		for (let i = 0; i < n; i++) {
			if (mp.has(a[i])) {
				mnd = Math.min(mnd, i - mp.get(a[i]));
			}
			mp.set(a[i], i);
		}

		console.log(mnd < INF ? n - mnd : -1);
	}
}

const solve = arr=>{
   let obj = {};
     let max = 0;
     for(let i=0;i<arr.length;i++){
          if(obj[arr[i]]!==undefined){
               let t = arr.length - (i - obj[arr[i]]);
               if(t*2>=arr.length){
                    max = Math.max(max,t);
               }
               obj[arr[i]] = i;
          }
          else obj[arr[i]] = i;
     }
     if(max===0) console.log(-1);
     else console.log(max);
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(arr);
  }
}
main();

const solve = arr=>{
   let obj = {};
     let max = 0;
     for(let i=0;i<arr.length;i++){
          if(obj[arr[i]]!==undefined){
               let t = arr.length - (i - obj[arr[i]]);
               if(t*2>=arr.length){
                    max = Math.max(max,t);
                    break;
               }
          }
          else obj[arr[i]] = i;
     }
     if(max===0) console.log(-1);
     else console.log(max);
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(arr);
  }
}
main();

const solve = arr=>{
 let obj = {};
     for(let i=0;i<arr.length;i++){
          if(obj[arr[i]]) obj[arr[i]].push(i);
          else obj[arr[i]] = [i];
     }
     arr.sort((a,b)=>a-b);
     let max = 0;
     for(let i=0;i<arr.length-1;i++){
          if(arr[i]===arr[i+1]){
               let t = obj[arr[i]];
               for(let j=t.length-1;j>0;j--){
                    let k = arr.length-(t[j]-t[j-1]);
                    if(k*2>=arr.length){
                         max = Math.max(max,k);
                         break;
                    }
               }
               if(t.length===arr.length) break;
          }
     }
     if(max===0) console.log(-1);
     else console.log(max);
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(arr);
  }
}
main();


function solve(input) {
    const len = parseInt(input)
    const out = 3;
    const list = Array.from({length: len}, (_, i) => i + 1);
    // 2 3 4 ... n 1
    console.log([...Array.from({length: len - 1}, (_, i) => i + 2), 1].join(' '))
    // 3 4 5 ... n 1 2
    console.log([...Array.from({length: len - 2}, (_, i) => i + 3), 1, 2].join(' '))
    // mundur
    console.log([...Array.from({length: len}, (_, i) => len - i)].join(' '))
    if (len > 3) {
      let baseList = Array.from({length: len}, (_, i) => len - i);
      for (let i = 3; i < len; i++) {
        const awal = baseList[0]
        baseList = [...baseList, awal].slice(1, len + 1)
        console.log(baseList.join(' '))
      }
    }
}

// =========== DEFAULT FORMAT ==============
const readline = require('readline').createInterface({ input: process.stdin });

let i = 1;
let t = 0;
readline.on('line', line => {
    if (i == 1) {
        // number of test case
        t = parseInt(line)
        i++;
    } else {
        solve(line)
        if (i <= t) i++
        else readline.close()
    }
});

// =========== DEFAULT FORMAT END ==============

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var n = lines[0];
    for(i = 1; i <= n; i++){
        var a = lines[i];
        for(j = 1; j <= a; j++){
            var ans = '';
            ans += j;
            for(k = a; k >= 1; k--){
                if(j != k){
                    ans += ' ' + k;
                }
            }
            console.log(ans);
        }
    }
});

'use strict';
/* ================== */
process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
  inputString += inputStdin;
});

process.stdin.on('end', _ => {
  inputString = inputString.trim().split('\n').map(string => {
    return string.trim();
  });

  main();
});

const readline = () => inputString[currentLine++];
const readline_arr = () => readline().split('');
const readline_num_arr = () => readline().split(' ').map((n) => parseInt(n, 10));
const print = (...txt) => process.stdout.write(`${txt}\n`)
/* ================== */

function main() {
  let t = parseInt(readline(), 10);
  while (t--) {
    solve();
  }
}

const checkPermute = (p) => {
  for (let i = 2; i < p.length; i++) {
    if (p[i - 2] + p[i - 1] === p[i]) {
      return false;
    }
  }

  return true;
}

function solve() {
  const n = parseInt(readline());
  for (let i = 1; i <= n; i++) {
    const res = [];
    res.push(i)

    for (let j = n; j >= 1; j--) {
      if (j !== i) res.push(j);
    }

    print(res.join(' '));
  }
}

'use strict';

function solve(n) {
  if (n === 3) return `1 3 2\n2 3 1\n3 1 2`;
  const s = Array.from({
    length: n
  }, (_, i) => n - i);
  const res = Array.from({
    length: n
  }, () => new Array(n));
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      res[i][j] = s[(j + i) % n];
    }
  }
  return res.map(arr => arr.join(' ')).join('\n');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      res[i] = solve(n);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', stdin => inputString += stdin);

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(s => s.trim());
    main();
});

function readline() {
    return inputString[currentLine++];
}

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let [n] = readline().split(' ').map(Number);

        let perm = [];
        for (let i = 0; i < n; i++) {
            perm.push(i + 1);
        }

        for (let i = 1; i <= n; i++) {
            let res = [i];
            let m = perm.filter( x => x !== i)
            m.sort((a, b) => b - a);
            output([...res, ...m].join(' '));
        }
    }
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        output[i] = solve(n)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n) {
    const ans = []
    for (let i = 0; i < n; i++) {
        const now = [i + 1]
        for (let j = n; j >= 1; j--) {
            if (j === i + 1) continue
            now.push(j)
        }
        ans[i] = now.join(' ')
    }
    return ans.join('\n')
}

var t = readline();

for (var i = 0; i < t; i++) {
  var n = readline();

  for (var j = 1; j <= n; ++j) {
    write(j);
    for (var k = n; k > 0; --k) {
      if (j != k) {
        write(' ',k);
      }
    }
    print();
  }
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var n = lines[0];
    for(var i = 1; i <= n; i++){
        var k = lines[i];
        var ans = '';
        for(j = 0; j < k; j++){
            ans += 1 + ' ';
        }
        console.log(ans);
    }
});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(var j = 1; j <= n; j++){
        var r = lines[j].split(' ').map(Number);
        var a = r[0];
        var b = r[1];
        var k = r[2];
        var d = 0;
        var answer = 0;
        if(k % 2 == 1){
            d = Math.floor(k / 2);
        }else{
            d = k / 2;
        }
        answer = (d * a) - ((k - d) * b);
        console.log(answer);
    }
});

'use strict';

function solve(n) {
  const s = Array.from({
    length: n
  }, (_, i) => n - i);
  const res = Array.from({
    length: n
  }, () => new Array(n));
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      res[i][j] = s[(j + i) % n];
    }
  }
  return res.map(arr => arr.join(' ')).join('\n');
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      res[i] = solve(n);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});