A positive number $$$x$$$ of length $$$n$$$ in base $$$p$$$ ($$$2 \le p \le 10^9$$$) is written on the blackboard. The number $$$x$$$ is given as a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < p$$$) — the digits of $$$x$$$ in order from left to right (most significant to least significant).Dmitry is very fond of all the digits of this number system, so he wants to see each of them at least once.In one operation, he can:   take any number $$$x$$$ written on the board, increase it by $$$1$$$, and write the new value $$$x + 1$$$ on the board. For example, $$$p=5$$$ and $$$x=234_5$$$.  Initially, the board contains the digits $$$2$$$, $$$3$$$ and $$$4$$$;  Dmitry increases the number $$$234_5$$$ by $$$1$$$ and writes down the number $$$240_5$$$. On the board there are digits $$$0, 2, 3, 4$$$;  Dmitry increases the number $$$240_5$$$ by $$$1$$$ and writes down the number $$$241_5$$$. Now the board contains all the digits from $$$0$$$ to $$$4$$$. Your task is to determine the minimum number of operations required to make all the digits from $$$0$$$ to $$$p-1$$$ appear on the board at least once.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^3$$$) — the number of test cases. The descriptions of the input test cases follow. The first line of description of each test case contains two integers $$$n$$$ ($$$1 \le n \le 100$$$) and $$$p$$$ ($$$2 \le p \le 10^9$$$) — the length of the number and the base of the number system. The second line of the description of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < p$$$) — digits of $$$x$$$ in number system with base $$$p$$$ It is guaranteed that the number $$$x$$$ does not contain leading zeros (that is, $$$a_1>0$$$).

For each test case print a single integer — the minimum number of operations required for Dmitry to get all the digits on the board from $$$0$$$ to $$$p-1$$$. It can be shown that this always requires a finite number of operations.

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, p] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        // console.log(solve(n, p, arr), solve2(n, p, arr))
        output[i] = Math.min(solve(n, p, arr.slice()), solve2(n, p, arr.slice()))
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, p, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        // o[x] = (o[x] || 0) + 1
        return o
    }, {})

    const last = arr[n - 1]
    let c = 0
    let x = last
    let limit = p
    while (map[x] && c < limit) {
        if (!x) x = p
        x--
        c++
    }
    if (last + c >= p) {
        limit -= c
        //
        arr[n - 1] = 0
        map[0] = 1
        //
        let carry = 1
        for (let i = n - 2; i >= 0; i--) {
            arr[i] += carry
            if (arr[i] === p) {
                arr[i] = 0
                carry = 1
            } else {
                carry = 0
            }
            map[arr[i]] = 1
        }
        if (carry) {
            arr.unshift(1)
            map[1] = 1
        }
        //
        while (map[x] && c < limit) {
            if (!x) x = p
            x--
            c++
        }
    }
    return p - c
}
function solve2(n, p, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        // o[x] = (o[x] || 0) + 1
        return o
    }, {})

    const last = arr[n - 1]
    let c = p - last // last -> p
    let ans = c
    if (last + c >= p) {
        //
        arr[n - 1] = 0
        map[0] = 1
        //
        let carry = 1
        for (let i = n - 2; i >= 0; i--) {
            arr[i] += carry
            if (arr[i] === p) {
                arr[i] = 0
                carry = 1
            } else {
                carry = 0
            }
            map[arr[i]] = 1
        }
        if (carry) {
            arr.unshift(1)
            map[1] = 1
        }
        //
        let x = last
        while (x > 0 && map[x]) {
            // if (!x) x = p
            x--
            // c++
        }
        ans += x
    }
    // console.log('fake', c, ans)
    return ans
}

'use strict';

var fs = require('fs');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const [n, p] = rns(),
        a = rns();
  let b = a[n - 1],
      set = new Set(a);
  let t = -1;
  for (let i = b; i >= 0; i--) {
    if (set.has(i)) continue;
    t = i;
    break;
  }
  if (t === -1) {
    for (let i = p - 1; i >= b; i--) {
      if (set.has(i)) continue;
      t = i;
      break;
    }
    if (t === -1) return 0;
    return t - b;
  } else {
    let res = p - b;
    set.add(0);
    for (let j = n - 2; j >= 0; j--) {
      if (a[j] === p - 1) continue;
      set.add(a[j] + 1);
      for (let i = t; i >= 0; i--) {
        if (set.has(i)) continue;
        return res + i;
      }
      return res;
    }
    set.add(1);
    for (let i = t; i >= 0; i--) {
      if (set.has(i)) continue;
      return res + i;
    }
    return res;
  }
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

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, p] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        // console.log(solve(n, p, arr), solve2(n, p, arr))
        output[i] = Math.min(solve(n, p, arr), solve2(n, p, arr))
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, p, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        // o[x] = (o[x] || 0) + 1
        return o
    }, {})

    const last = arr[n - 1]
    let c = 0
    let x = last
    let limit = p
    while (map[x] && c < limit) {
        if (!x) x = p
        x--
        c++
    }
    if (last + c >= p) {
        limit -= c
        //
        arr[n - 1] = 0
        map[0] = 1
        //
        let carry = 1
        for (let i = n - 2; i >= 0; i--) {
            arr[i] += carry
            if (arr[i] === p) {
                arr[i] = 0
                carry = 1
            } else {
                carry = 0
            }
            map[arr[i]] = 1
        }
        if (carry) {
            arr.unshift(1)
            map[1] = 1
        }
        //
        while (map[x] && c < limit) {
            if (!x) x = p
            x--
            c++
        }
    }
    return p - c
}
function solve2(n, p, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        // o[x] = (o[x] || 0) + 1
        return o
    }, {})

    const last = arr[n - 1]
    let c = p - last // last -> p
    let ans = c
    if (last + c >= p) {
        //
        arr[n - 1] = 0
        map[0] = 1
        //
        let carry = 1
        for (let i = n - 2; i >= 0; i--) {
            arr[i] += carry
            if (arr[i] === p) {
                arr[i] = 0
                carry = 1
            } else {
                carry = 0
            }
            map[arr[i]] = 1
        }
        if (carry) {
            arr.unshift(1)
            map[1] = 1
        }
        //
        let x = last
        while (x > 0 && map[x]) {
            // if (!x) x = p
            x--
            // c++
        }
        ans += x
    }
    // console.log('fake', c, ans)
    return ans
}

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, p] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, p, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, p, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        // o[x] = (o[x] || 0) + 1
        return o
    }, {})

    const last = arr[n - 1]
    let c = 0
    let x = last
    let limit = p
    while (map[x] && c < limit) {
        if (!x) x = p
        x--
        c++
    }
let r1 = p - c
    let fake = 0
    if (last + c >= p) {
        //
    } else {
        fake = p - (last + c)
        c = p - last
    }
    if (last + c >= p) {
        limit -= c
        //
        arr[n - 1] = 0
        map[0] = 1
        //
        let carry = 1
        for (let i = n - 2; i >= 0; i--) {
            if (++arr[i] === p) {
                arr[i] = 0
                carry = 1
            } else {
                carry = 0
            }
            map[arr[i]] = 1
        }
        if (carry) {
            arr.unshift(1)
            map[1] = 1
        }
        //
        while (map[x] && c < limit) {
            if (!x) x = p
            x--
            c++
        }
    }
let r2 = fake + p - c
        // console.log(arr, fake, r2)
    return Math.min(r1, r2)
    // let max = 0
    // for (let i = 0; i < n - 1; i++) {
    //     if (arr[i] < last && arr[i] > max) {
    //         max = arr[i]
    //     }
    // }
    // return [n, p, arr]
}

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, p] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, p, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, p, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = 1
        // o[x] = (o[x] || 0) + 1
        return o
    }, {})

    const last = arr[n - 1]
    let c = 0
    let x = last
    let limit = p
    while (map[x] && c < limit) {
        if (!x) x = p
        x--
        c++
    }
    if (last + c >= p) {
        limit -= c
        //
        arr[n - 1] = 0
        map[0] = 1
        //
        let carry = 1
        for (let i = n - 2; i >= 0; i--) {
            if (++arr[i] === p) {
                arr[i] = 0
                carry = 1
            } else {
                carry = 0
            }
            map[arr[i]] = 1
        }
        if (carry) {
            arr.unshift(1)
            map[1] = 1
        }
        //
        while (map[x] && c < limit) {
            if (!x) x = p
            x--
            c++
        }
    }
        // console.log(arr)
    return p - c
    // let max = 0
    // for (let i = 0; i < n - 1; i++) {
    //     if (arr[i] < last && arr[i] > max) {
    //         max = arr[i]
    //     }
    // }
    // return [n, p, arr]
}


Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.Initially, each mole i (1 ≤ i ≤ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible.Each mole i has a home placed at the position (ai, bi). Moving this mole one time means rotating his position point (xi, yi) 90 degrees counter-clockwise around it's home point (ai, bi).A regiment is compact only if the position points of the 4 moles form a square with non-zero area.Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.

The first line contains one integer n (1 ≤ n ≤ 100), the number of regiments. The next 4n lines contain 4 integers xi, yi, ai, bi ( - 104 ≤ xi, yi, ai, bi ≤ 104).

Print n lines to the standard output. If the regiment i can be made compact, the i-th line should contain one integer, the minimal number of required moves. Otherwise, on the i-th line print "-1" (without quotes).

NoteIn the first regiment we can move once the second or the third mole.We can't make the second regiment compact.In the third regiment, from the last 3 moles we can move once one and twice another one.In the fourth regiment, we can move twice the first mole and once the third mole.

;(function () {

	function Rotate(point, center, angine) {
		return {
			x: Math.round(center.x + (point.x - center.x) * Math.cos(angine) - (point.y - center.y) * Math.sin(angine)),
			y: Math.round(center.y + (point.y - center.y) * Math.cos(angine) + (point.x - center.x) * Math.sin(angine))
		};
	}

	function distance (pointA, pointB) {
		return Math.sqrt(Math.pow(pointA.x - pointB.x, 2) + Math.pow(pointA.y - pointB.y, 2));
	}

	function isSomeOne (a, b, c, d) {
		if (a.x === b.x && a.y === b.y) return true;
		if (a.x === c.x && a.y === c.y) return true;
		if (a.x === d.x && a.y === d.y) return true;
		if (b.x === c.x && b.y === c.y) return true;
		if (b.x === d.x && b.y === d.y) return true;
		if (c.x === d.x && c.y === d.y) return true;
		return false;
	}

	function isSquare (a, b, c, d) {
		var ab = distance(a, b),
			ac = distance(a, c),
			ad = distance(a, d),
			bc = distance(b, c),
			bd = distance(b, d),
			cd = distance(c, d);

		var map = {};
		[ab, ac, ad, bc, bd, cd].forEach(function (e) { map[e] = map[e] ? map[e] + 1 : 1; });

		var flag = false;
		for (var key in map) {
			if (map[key] === 4 && key !== 0) {
				flag = true;
			}
		}

		if (flag) {
			for (var key in map) {
				if (map[key] === 2 && key !== 0) {
					return true;
				}
			}
		}

		return false;
	}

	print(function (n) {

		var answers = [];

		while (n--) answers.push(function () {

			var regiment = [];
			for (var i = 0; i < 4; i++) {
				var newRegiment = readline().split(' ').map(Number);
				regiment.push(newRegiment);
			}

			var moles = [], homes = [];
			for (var i = 0; i < 4; i++) {

				var newMole = {
					x: regiment[i][0],
					y: regiment[i][1]
				};

				var newHome = {
					x: regiment[i][2],
					y: regiment[i][3]
				};

				moles.push(newMole);
				homes.push(newHome);
			}

			var squares = [];
			for (var rotate_1 = 0; rotate_1 < 4; rotate_1++)
				for (var rotate_2 = 0; rotate_2 < 4; rotate_2++)
					for (var rotate_3 = 0; rotate_3 < 4; rotate_3++)
						for (var rotate_4 = 0; rotate_4 < 4; rotate_4++) {
							var mole1 = Rotate(moles[0], homes[0], Math.PI / 2 * rotate_1),
								mole2 = Rotate(moles[1], homes[1], Math.PI / 2 * rotate_2),
								mole3 = Rotate(moles[2], homes[2], Math.PI / 2 * rotate_3),
								mole4 = Rotate(moles[3], homes[3], Math.PI / 2 * rotate_4);

							var differences = isSomeOne(mole1, mole2, mole3, mole4) === false,
								square = isSquare(mole1, mole2, mole3, mole4);
							if (differences && square) {
								squares.push(rotate_1 + rotate_2 + rotate_3 + rotate_4);
							}
						}

			if (squares.length === 0) return -1;
			else if (squares.length === 1) return squares[0];
			else return Math.min.apply(null, squares);

		}());

		return answers.join('\n');

	}(+readline()));

}.call(this));

var n = parseInt(readline());
var a = new Array();
var x = new Array();
var y = new Array();
var bx = new Array();
var by = new Array();
var d = new Array();
var ans = -1;
var tt = 0;
for(var i=0;i<4;i++)
{
    a[i] = new Array();
	x[i] = new Array();
	y[i] = new Array();
	d[i] = new Array();

	for(var j=0;j<4;j++)
	{
	    x[i][j]=new Array();
		y[i][j]=new Array();
	}
}
while(n--)
{
    ans = -1;
	tt = 0;
    for(var i=0;i<4;i++)
	{
        var str = readline().split(' ');
	    for(var j=0;j<4;j++)
		{
		    a[i][j]=parseInt(str[j]);
		}
		var l = a[i][0] - a[i][2];
		var s = a[i][1] - a[i][3];
		x[i][0] = a[i][2]+l;
		y[i][0] = a[i][3]+s;
		x[i][1] = a[i][2]-s;
		y[i][1] = a[i][3]+l;
		x[i][2] = a[i][2]-l;
		y[i][2] = a[i][3]-s;
		x[i][3] = a[i][2]+s;
		y[i][3] = a[i][3]-l;
	}
	gao(0);
	print(ans);
}

function gao(k)
{
    if(ans!=-1&&tt>=ans)
	{
	    return;
	}
	if(k==4)
	{
	    if(isCube())
		{
			if(ans==-1||tt<ans)
			{
				ans = tt;
			}
		}
		return;
	}
    for(var i=0;i<4;i++)
	{
	    bx[k]=x[k][i];
		by[k]=y[k][i];
		tt+=i;
		gao(k+1);
		tt-=i;
	}
}

function isCube()
{
    for(var i=0;i<4;i++)
	{
	    for(j=0;j<4;j++)
		{
		    d[i][j]=(bx[i]-bx[j])*(bx[i]-bx[j])+(by[i]-by[j])*(by[i]-by[j]);
		}
		d[i].sort(sortNum);
	}
	for(var i=0;i<4;i++)
	{
	    if(d[i][1]!=d[i][2]||d[i][3]!=2*d[i][2]||d[i][3]==0)
		{
		    return false;
		}
		if(i!=0&&d[i][1]!=d[i-1][1])
		{
		    return false;
		}
	}
	return true;
}

function sortNum(a, b)
{
    return a-b;
}

;(function () {

	print(function (n) {

		var answer = [];

		while (n--) {
			var regiment = [
				readline().split(' ').map(Number),
				readline().split(' ').map(Number),
				readline().split(' ').map(Number),
				readline().split(' ').map(Number)
			];

			var deviation = [
				[regiment[0][0] - regiment[0][2], regiment[0][1] - regiment[0][3]],
				[regiment[1][0] - regiment[1][2], regiment[1][1] - regiment[1][3]],
				[regiment[2][0] - regiment[2][2], regiment[2][1] - regiment[2][3]],
				[regiment[3][0] - regiment[3][2], regiment[3][1] - regiment[3][3]]
			];

			var posiblePositions = [
				[
					[regiment[0][0],   regiment[0][1]],
					[regiment[0][2] - deviation[0][1], regiment[0][3] + deviation[0][0]],
					[regiment[0][2] - deviation[0][0], regiment[0][3] - deviation[0][1]],
					[regiment[0][2] + deviation[0][1], regiment[0][3] - deviation[0][0]]
				],
				[
					[regiment[1][0],   regiment[1][1]],
					[regiment[1][2] - deviation[1][1], regiment[1][3] + deviation[1][0]],
					[regiment[1][2] - deviation[1][0], regiment[1][3] - deviation[1][1]],
					[regiment[1][2] + deviation[1][1], regiment[1][3] - deviation[1][0]]
				],
				[
					[regiment[2][0],   regiment[2][1]],
					[regiment[2][2] - deviation[2][1], regiment[2][3] + deviation[2][0]],
					[regiment[2][2] - deviation[2][0], regiment[2][3] - deviation[2][1]],
					[regiment[2][2] + deviation[2][1], regiment[2][3] - deviation[2][0]]
				],
				[
					[regiment[3][0],   regiment[3][1]],
					[regiment[3][2] - deviation[3][1], regiment[3][3] + deviation[3][0]],
					[regiment[3][2] - deviation[3][0], regiment[3][3] - deviation[3][1]],
					[regiment[3][2] + deviation[3][1], regiment[3][3] - deviation[3][0]]
				]
			];

			var posibleSquare = [];
			for (var i = 0; i < 4; i++)
				for (var j = 0; j < 4; j++)
					for (var k = 0; k < 4; k++)
						for (var l = 0; l < 4; l++) {
							var position_i = posiblePositions[0][i],
								position_j = posiblePositions[1][j],
								position_k = posiblePositions[2][k],
								position_l = posiblePositions[3][l];

							var side_ij = Math.sqrt(Math.pow(position_i[0] - position_j[0], 2) + Math.pow(position_i[1] - position_j[1], 2)),
								side_ik = Math.sqrt(Math.pow(position_i[0] - position_k[0], 2) + Math.pow(position_i[1] - position_k[1], 2)),
								side_il = Math.sqrt(Math.pow(position_i[0] - position_l[0], 2) + Math.pow(position_i[1] - position_l[1], 2));

							if (side_ij === side_ik) {
								var side_lj = Math.sqrt(Math.pow(position_l[0] - position_j[0], 2) + Math.pow(position_l[1] - position_j[1], 2)),
									side_kl = Math.sqrt(Math.pow(position_k[0] - position_l[0], 2) + Math.pow(position_k[1] - position_l[1], 2));

								if (side_ij === side_lj && side_ij === side_kl && side_ij !== 0) {
									if ((position_i[0] === position_j[0] && position_i[1] === position_j[1]) ||
									   (position_i[0] === position_k[0] && position_i[1] === position_k[1]) ||
									   (position_i[0] === position_l[0] && position_i[1] === position_l[1]) ||
									   (position_j[0] === position_k[0] && position_j[1] === position_k[1]) ||
									   (position_j[0] === position_l[0] && position_j[1] === position_l[1]) ||
									   (position_k[0] === position_l[0] && position_k[1] === position_l[1])) {}
									else posibleSquare.push(i + j + k + l);
								}
							} else if (side_ij === side_il) {
								var side_jk = Math.sqrt(Math.pow(position_j[0] - position_k[0], 2) + Math.pow(position_j[1] - position_k[1], 2)),
									side_kl = Math.sqrt(Math.pow(position_k[0] - position_l[0], 2) + Math.pow(position_k[1] - position_l[1], 2));

								if (side_ij === side_jk && side_ij === side_kl && side_ij !== 0) {
									if ((position_i[0] === position_j[0] && position_i[1] === position_j[1]) ||
									   (position_i[0] === position_k[0] && position_i[1] === position_k[1]) ||
									   (position_i[0] === position_l[0] && position_i[1] === position_l[1]) ||
									   (position_j[0] === position_k[0] && position_j[1] === position_k[1]) ||
									   (position_j[0] === position_l[0] && position_j[1] === position_l[1]) ||
									   (position_k[0] === position_l[0] && position_k[1] === position_l[1])) {}
									else posibleSquare.push(i + j + k + l);
								}
							} else if (side_ik === side_il) {
								var side_jl = Math.sqrt(Math.pow(position_j[0] - position_l[0], 2) + Math.pow(position_j[1] - position_l[1], 2)),
									side_kj = Math.sqrt(Math.pow(position_k[0] - position_j[0], 2) + Math.pow(position_k[1] - position_j[1], 2));

								if (side_ik === side_jl && side_ik === side_kj && side_ik !== 0) {
									if ((position_i[0] === position_j[0] && position_i[1] === position_j[1]) ||
									   (position_i[0] === position_k[0] && position_i[1] === position_k[1]) ||
									   (position_i[0] === position_l[0] && position_i[1] === position_l[1]) ||
									   (position_j[0] === position_k[0] && position_j[1] === position_k[1]) ||
									   (position_j[0] === position_l[0] && position_j[1] === position_l[1]) ||
									   (position_k[0] === position_l[0] && position_k[1] === position_l[1])) {}
									else posibleSquare.push(i + j + k + l);
								}
							}
						}

			if (posibleSquare.length === 0) answer.push(-1);
			else if(posibleSquare.length === 1) answer.push(posibleSquare[0]);
			else answer.push(Math.min.apply(null, posibleSquare));
		}

		return answer.join('\n');

	}(+readline()));

}.call(this));

;(function () {

	function Rotate(point, center, angine) {
		return {
			x: Math.round(center.x + (point.x - center.x) * Math.cos(angine) - (point.y - center.y) * Math.sin(angine)),
			y: Math.round(center.y + (point.y - center.y) * Math.cos(angine) + (point.x - center.x) * Math.sin(angine))
		};
	}

	function distance (pointA, pointB) {
		return Math.sqrt(Math.pow(pointA.x - pointB.x, 2) + Math.pow(pointA.y - pointB.y, 2));
	}

	function isSomeOne (a, b, c, d) {
		if (a.x === b.x && a.y === b.y) return true;
		if (a.x === c.x && a.y === c.y) return true;
		if (a.x === d.x && a.y === d.y) return true;
		if (b.x === c.x && b.y === c.y) return true;
		if (b.x === d.x && b.y === d.y) return true;
		if (c.x === d.x && c.y === d.y) return true;
		return false;
	}

	function isSquare (a, b, c, d) {
		var ab = distance(a, b),
			ac = distance(a, c),
			ad = distance(a, d),
			bc = distance(b, c),
			bd = distance(b, d),
			cd = distance(c, d);

		var map = {};
		[ab, ac, ad, bc, bd, cd].forEach(function (e) { map[e] = map[e] ? map[e] + 1 : 1; });

		for (var key in map) {
			if (map[key] === 4 && key !== 0) {
				return true;
			}
		}

		return false;
	}

	print(function (n) {

		var answers = [];

		while (n--) answers.push(function () {

			var regiment = [];
			for (var i = 0; i < 4; i++) {
				var newRegiment = readline().split(' ').map(Number);
				regiment.push(newRegiment);
			}

			var moles = [], homes = [];
			for (var i = 0; i < 4; i++) {

				var newMole = {
					x: regiment[i][0],
					y: regiment[i][1]
				};

				var newHome = {
					x: regiment[i][2],
					y: regiment[i][3]
				};

				moles.push(newMole);
				homes.push(newHome);
			}

			var squares = [];
			for (var rotate_1 = 0; rotate_1 < 4; rotate_1++)
				for (var rotate_2 = 0; rotate_2 < 4; rotate_2++)
					for (var rotate_3 = 0; rotate_3 < 4; rotate_3++)
						for (var rotate_4 = 0; rotate_4 < 4; rotate_4++) {
							var mole1 = Rotate(moles[0], homes[0], Math.PI / 2 * rotate_1),
								mole2 = Rotate(moles[1], homes[1], Math.PI / 2 * rotate_2),
								mole3 = Rotate(moles[2], homes[2], Math.PI / 2 * rotate_3),
								mole4 = Rotate(moles[3], homes[3], Math.PI / 2 * rotate_4);

							var differences = isSomeOne(mole1, mole2, mole3, mole4) === false,
								square = isSquare(mole1, mole2, mole3, mole4);
							if (differences && square) {
								squares.push(rotate_1 + rotate_2 + rotate_3 + rotate_4);
							}
						}

			if (squares.length === 0) return -1;
			else if (squares.length === 1) return squares[0];
			else return Math.min.apply(null, squares);

		}());

		return answers.join('\n');

	}(+readline()));

}.call(this));


There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below:There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X" or "O". Then the player chooses two positive integers a and b (a·b = 12), after that he makes a table of size a × b from the cards he put on the table as follows: the first b cards form the first row of the table, the second b cards form the second row of the table and so on, the last b cards form the last (number a) row of the table. The player wins if some column of the table contain characters "X" on all cards. Otherwise, the player loses.Inna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers a and b to choose. Help her win the game: print to her all the possible ways of numbers a, b that she can choose and win.

The first line of the input contains integer t (1 ≤ t ≤ 100). This value shows the number of sets of test data in the input. Next follows the description of each of the t tests on a separate line. The description of each test is a string consisting of 12 characters, each character is either "X", or "O". The i-th character of the string shows the character that is written on the i-th card from the start.

For each test, print the answer to the test on a single line. The first number in the line must represent the number of distinct ways to choose the pair a, b. Next, print on this line the pairs in the format axb. Print the pairs in the order of increasing first parameter (a). Separate the pairs in the line by whitespaces.

4
OXXXOXOOXOOX
OXOXOXOXOXOX
XXXXXXXXXXXX
OOOOOOOOOOOO

var n=+readline();
while(n--){
	var s=readline();
	var ans=[];
	var x=[1,2,3,4,6,12].filter(function(k){
		for(var i=0; i<k; i++){
			if(s[i]==='X'){
				var f=true;
				for(var j=i; j<12; j+=k){
					if(s[j]!=='X'){
						f=false;
					}
				}
				if(f){
					return true;
				}
			}
		}
		return false;
	});
	print(x.length===0 ? 0 : x.length+' '+x.map(function(v){return (12/v)+'x'+v;}).reverse().join(' '));
}

;(function () {

	print((function (n) {

		var ret = [];

		while (n--) {
			var p = 0, s = readline(), k = [];

			[1, 2, 3, 4, 6, 12].forEach( function (a) {
				for (var _b = 0, b = 12 / a; _b < b; _b++) {
					for (var j = 0, q = []; j < b; j++) q.push(j === _b ? 'X' : '.');
					q = '(' + q.join('') + '){' + a + '}';
					if ( (new RegExp(q)).test(s) ) {
						k.push(a + 'x' + b);
						p++;
						break;
					}
				}
			});

			if (k.length) {
				k.unshift(p);
				ret.push(k.join(' '));
			} else ret.push('0');
		}

		return ret.join('\n');

	})(+readline()));

}).call(this);

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i]);
	};
	return tokens;
}

function main() {
	var caseNum = parseInt(readline());
	for (var caseIndex = 0; caseIndex < caseNum; ++caseIndex) {
		var line = trim(readline());
		var solutions = [];
		for (var rowNum = 1; rowNum <= 12; ++rowNum) {
			if (12%rowNum != 0) {
				continue;
			}
			var colNum = 12/rowNum;
			for (var c = 0; c < colNum; ++c) {
				var okay = true;
				for (var r = 0; okay && r < rowNum; ++r) {
					if (line.charAt(r*colNum+c) == 'O') {
						okay = false;
					}
				}
				if (okay) {
					solutions.push(rowNum+'x'+colNum);
					break;
				}
			}
		}
		solutions.unshift(solutions.length);
		print(solutions.join(' '));
	}
}

main();

var n = +readline();
var width = [12, 6, 4, 3, 2, 1];
for (var i=0; i<n; i++) {
	var s = readline();
	var ans = '';
	var count = 0;
		next: for (var k=0; k<6; k++) {
			next1: for (var j=0; j<width[k]; j++) {

				 for (var z=j; z<12; z += width[k]) {
						if (s[z] != 'X') continue next1;
					}

				ans += ' ' + 12/width[k] + 'x' + width[k];
				count++;
				continue next;
			}
		}
print (count + ans);
}

var t = parseInt(readline()),
		widths = [ 12, 6, 4, 3, 2, 1 ];

	for(var i = 0; i < t; i++)	{
		var row = readline().replace(/o/gi, 0).replace(/x/gi, 1), count = 0, result = [];

		widths.forEach(function(width, i)	{
			var height = 12 / width, s = 0, e = 1, cols = height, rs = [];

			rs = row.split('').map(function(v1, v2, arr)	{
				var returnVal = arr.slice(s, e * height).map(Number);

				s = e * height;
				e++;

				return returnVal;
			}).slice(0, width);

			for(var col = 0; col < cols; col++)	{
				var rsValCheck = 1, flag = true;

				for(var n = 0; n < rs.length; n++)	{
					rsValCheck *= parseInt(rs[n][col]);

					if(!rsValCheck)	{
						flag = false;
						break;
					}
				}

				if(flag)	{
					count++;
					result.push(width);
					break;
				}
			}

		});

		result = result.sort(function(a, b){ return a + b; }).map(function(a) { return a + 'x' + 12 / a });
		print(count + ' ' + result.join(' '));
	}

var n=+readline();
while(n--){
	var s=readline();
	var ans=[];
	var x=[1,2,3,4,6,12].filter(function(k){
		for(var i=0; i<k; i++){
			if(s[i]==='X'){
				var f=true;
				for(var j=i; j<12; j+=k){
					if(s[j]!=='X'){
						f=false;
					}
				}
				if(f){
					return true;
				}
			}
		}
		return false;
	});
	print(x.length===0 ? 0 : x.length+' '+x.map(function(v){return (12/v)+'x'+v;}).join(' '));
}

var t = parseInt(readline()),
		solves = [ 1, 2, 3, 4, 6, 12 ];

	for(var i = 0; i < t; i++)	{
		var row = readline().split(''), count = 0, rs = [],
			json = {
				'12' : 1,
				'6' : 2,
				'4' : 3,
				'3' : 4,
				'2' : 6,
				'1' : 12
			};

		row.forEach(function(c, index)	{
			if(c == 'X')	{
				solves.forEach(function(pos)	{
					if((index + 1) % pos == 0)	json[pos] -= 1;
					if(json[pos] == 0)	{
						count++;

						rs.push(pos);
					}
				});
			}
		});

		rs = rs.sort(function(a, b){ return a + b; }).map(function(a) { return 12 / a + 'x' + a });
		print(count + ' ' + rs.join(' '));
	}

var t = parseInt(readline()),
		solves = [ 1, 2, 3, 4, 6, 12 ];

	for(var i = 0; i < t; i++)	{
		var row = readline().split(''),
			json = {
				'1' : 12,
				'2' : 6,
				'3' : 4,
				'4' : 3,
				'6' : 2,
				'12' : 1
			},
			count = 0, rs = [];

		row.forEach(function(c, index)	{
			if(c == 'X')	{
				solves.forEach(function(pos)	{
					if(!((index + 1) % pos))	json[pos] -= 1;

					if(json[pos] == 0)	{
						count++;

						rs.push(pos + 'x' + 12 / pos);
					}
				});
			}
		});

		print(count + ' ' + rs.join(' '));
	}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from $$$a$$$ to make it a good array. Recall that the prefix of the array $$$a=[a_1, a_2, \dots, a_n]$$$ is a subarray consisting several first elements: the prefix of the array $$$a$$$ of length $$$k$$$ is the array $$$[a_1, a_2, \dots, a_k]$$$ ($$$0 \le k \le n$$$).The array $$$b$$$ of length $$$m$$$ is called good, if you can obtain a non-decreasing array $$$c$$$ ($$$c_1 \le c_2 \le \dots \le c_{m}$$$) from it, repeating the following operation $$$m$$$ times (initially, $$$c$$$ is empty):  select either the first or the last element of $$$b$$$, remove it from $$$b$$$, and append it to the end of the array $$$c$$$. For example, if we do $$$4$$$ operations: take $$$b_1$$$, then $$$b_{m}$$$, then $$$b_{m-1}$$$ and at last $$$b_2$$$, then $$$b$$$ becomes $$$[b_3, b_4, \dots, b_{m-3}]$$$ and $$$c =[b_1, b_{m}, b_{m-1}, b_2]$$$.Consider the following example: $$$b = [1, 2, 3, 4, 4, 2, 1]$$$. This array is good because we can obtain non-decreasing array $$$c$$$ from it by the following sequence of operations:  take the first element of $$$b$$$, so $$$b = [2, 3, 4, 4, 2, 1]$$$, $$$c = [1]$$$;  take the last element of $$$b$$$, so $$$b = [2, 3, 4, 4, 2]$$$, $$$c = [1, 1]$$$;  take the last element of $$$b$$$, so $$$b = [2, 3, 4, 4]$$$, $$$c = [1, 1, 2]$$$;  take the first element of $$$b$$$, so $$$b = [3, 4, 4]$$$, $$$c = [1, 1, 2, 2]$$$;  take the first element of $$$b$$$, so $$$b = [4, 4]$$$, $$$c = [1, 1, 2, 2, 3]$$$;  take the last element of $$$b$$$, so $$$b = [4]$$$, $$$c = [1, 1, 2, 2, 3, 4]$$$;  take the only element of $$$b$$$, so $$$b = []$$$, $$$c = [1, 1, 2, 2, 3, 4, 4]$$$ — $$$c$$$ is non-decreasing. Note that the array consisting of one element is good.Print the length of the shortest prefix of $$$a$$$ to delete (erase), to make $$$a$$$ to be a good array. Note that the required length can be $$$0$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: the length of the shortest prefix of elements you need to erase from $$$a$$$ to make it a good array.

NoteIn the first test case of the example, the array $$$a$$$ is already good, so we don't need to erase any prefix.In the second test case of the example, the initial array $$$a$$$ is not good. Let's erase first $$$4$$$ elements of $$$a$$$, the result is $$$[4, 5, 2]$$$. The resulting array is good. You can prove that if you erase fewer number of first elements, the result will not be good.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    if (len === 1) {
      console.log(0);
      continue;
    }
    let i = len - 1;
    let count = 1;

    for (; i >= 1; i--) {
      if (arr[i] > arr[i - 1]) break;
      count++;
    }
    for (; i >= 1; i--) {
      if (arr[i] < arr[i - 1]) break;
      count++;
    }
    console.log(len - count);
  }
}

//↓見なくていいよ！ここから--------------------------------------------------
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);
  console.error("\n");
  var start = new Date();
  Main();
  var end = new Date() - start;

  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
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 = [];
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray();
		var lastIndex = -1;
		var negative = false;
		for(var j = N - 2; j > 0; j--){
			if(list[j] < list[j + 1]){
				negative = true;
			}
			if(list[j - 1] > list[j] && list[j] <= list[j + 1] && negative){
				lastIndex = j;
				break;
			}
		}
		if(lastIndex == -1){
			lastIndex = 0;
		}
		output[i] = lastIndex;
	}
	myout(myconv(output,9));
}

const readline = require('readline');
const { setFlagsFromString } = require('v8');

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

var lineCount = 0
var testCount = 0
var outputStr = ''

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if(lineCount%2==1){
        //do nothing?
    }
    else if (lineCount >= 2*testCount) {
        outputStr += compute(input) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += compute(input) + '\n'
    }
    lineCount++
});

function compute(str) {
    var list = str.split(' ')
    var up = false

    for(var i = list.length-2;i>=0;i--){
        if(parseInt(list[i])<parseInt(list[i+1])){
            var up = true
        }
        else if(parseInt(list[i])>parseInt(list[i+1])){
            if(up == true){
                // there's a turn
                return i+1
            }
            else{
                continue
            }
        }
        else{
            continue
        }
    }
    return '0'
}

function solve() {
   var n = Number(read());
   var a = readArray(Number);
   var a1 = [a[0]];
   var fi = [0];
   for (var i = 1; i < n; i++) {
      if (a[i] !== a[i - 1]) {
         a1.push(a[i]);
         fi.push(i);
      }
   }
   var ind = 0;
   var n1 = a1.length;
   for (var i = 1; i < n1 - 1; i++) {
      if (a1[i] < a1[i + 1] && a1[i] < a1[i - 1]) {
         ind = fi[i];
      }
   }
   write(ind);
}

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 {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', 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();
}

//↓見なくていいよ！ここから--------------------------------------------------
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);
  console.error("\n");
  var start = new Date();
  Main();
  var end = new Date() - start;

  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
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 = [];
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray();
		var lastIndex = -1;
		for(var j = N - 2; j > 0; j--){
			if(list[j - 1] > list[j] && list[j] < list[j + 1]){
				lastIndex = j;
				break;
			}
		}
		if(lastIndex == -1){
			lastIndex = 0;
		}
		output[i] = lastIndex;
	}
	myout(myconv(output,9));
}

//↓見なくていいよ！ここから--------------------------------------------------
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);
  console.error("\n");
  var start = new Date();
  Main();
  var end = new Date() - start;

  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
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 = [];
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray();
		var lastIndex = -1;
		for(var j = N - 2; j > 0; j--){
			if(list[j - 1] > list[j] && list[j] <= list[j + 1]){
				lastIndex = j;
				break;
			}
		}
		if(lastIndex == -1){
			lastIndex = 0;
		}
		output[i] = lastIndex;
	}
	myout(myconv(output,9));
}

//↓見なくていいよ！ここから--------------------------------------------------
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);
  console.error("\n");
  var start = new Date();
  Main();
  var end = new Date() - start;

  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
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 = [];
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray();
		var lastIndex = -1;
		var max = 0;
		for(var j = N - 2; j > 0; j--){
			if(list[j - 1] > list[j] && list[j] < list[j + 1]){
				lastIndex = j;
			}
		}
		if(lastIndex == -1){
			lastIndex = 0;
		}
		output[i] = lastIndex;
	}
	myout(myconv(output,9));
}

const readline = require('readline');
const { setFlagsFromString } = require('v8');

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

var lineCount = 0
var testCount = 0
var outputStr = ''

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if(lineCount%2==1){
        //do nothing?
    }
    else if (lineCount >= 2*testCount) {
        outputStr += compute(input) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += compute(input) + '\n'
    }
    lineCount++
});

function compute(str) {
    var list = str.split(' ')
    var up = false

    for(var i = list.length-2;i>=0;i--){
        if(parseInt(list[i])<parseInt(list[i+1])){
            var up = true
        }
        else{
            if(up == true){
                // there's a turn
                return i+1
            }
            else{
                continue
            }
        }
    }
    return '0'
}

function solve() {
   var n = Number(read());
   var a = readArray(Number);
   var ind = 0;
   for (var i = 1; i < n - 1; i++) {
      if (a[i] < a[i + 1] && a[i] < a[i - 1]) {
         ind = i;
      }
   }
   write(ind);
}

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 {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', 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 solve() {
   var n = Number(read());
   var a = readArray(Number);
   if (n < 3) {
      write(0);
      return;
   }
   var ind = 0;
   for (var i = n - 2; i > 0; i--) {
      if (a[i] < a[i + 1] && a[i] < a[i - 1]) {
         ind = i;
         break;
      }
   }
   write(ind);
}

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 {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', 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 solve() {
   var n = Number(read());
   var a = readArray(Number);
   if (n < 3) {
      write(0);
      return;
   }
   var ind = 0;
   for (var i = n - 2; i > 0; i--) {
      if (a[i] < a[i + 1] && a[i] < a[i - 1]) {
         ind = i;
         break;
      }
   }
   write(i);
}

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 {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', 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 solve() {
   var n = Number(read());
   if (n === 1) {
      write(-1);
      return;
   }
   var a = readArray(Number);
   var a1 = [a[0]];
   var fi = [0];
   for (var i = 1; i < n; i++) {
      if (a[i] !== a[i - 1]) {
         a1.push(a[i]);
         fi.push(i);
      }
   }
   var ind = 0;
   var n1 = a1.length;
   for (var i = 1; i < n1 - 1; i++) {
      if (a1[i] < a1[i + 1] && a1[i] < a1[i - 1]) {
         ind = fi[i];
      }
   }
   write(ind);
}

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 {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', 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 solve() {
   var n = Number(read());
   var a = readArray(Number);
   var ind = 0;
   for (var i = n - 2; i > 0; i--) {
      if (a[i] < a[i + 1] && a[i] < a[i - 1]) {
         ind = i;
         break;
      }
   }
   write(i);
}

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 {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', 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();
}


You have array of $$$n$$$ numbers $$$a_{1}, a_{2}, \ldots, a_{n}$$$. Rearrange these numbers to satisfy $$$|a_{1} - a_{2}| \le |a_{2} - a_{3}| \le \ldots \le |a_{n-1} - a_{n}|$$$, where $$$|x|$$$ denotes absolute value of $$$x$$$. It's always possible to find such rearrangement.Note that all numbers in $$$a$$$ are not necessarily different. In other words, some numbers of $$$a$$$ may be same.You have to answer independent $$$t$$$ test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$3 \le n \le 10^{5}$$$) — the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).

For each test case, print the rearranged version of array $$$a$$$ which satisfies given condition. If there are multiple valid rearrangements, print any of them.

NoteIn the first test case, after given rearrangement, $$$|a_{1} - a_{2}| = 0 \le |a_{2} - a_{3}| = 1 \le |a_{3} - a_{4}| = 2 \le |a_{4} - a_{5}| = 2 \le |a_{5} - a_{6}| = 10$$$. There are other possible answers like "5 4 5 6 -2 8".In the second test case, after given rearrangement, $$$|a_{1} - a_{2}| = 1 \le |a_{2} - a_{3}| = 2 \le |a_{3} - a_{4}| = 4$$$. There are other possible answers like "2 4 8 1".

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(" "))
    }

}

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;
}

'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 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(' '))
}

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(' '));
}

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(" "));
}

//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();
});

//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();
});

// 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(' ');
}

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`);
  }
});