Let there be an array $$$b_1, b_2, \ldots, b_k$$$. Let there be a partition of this array into segments $$$[l_1; r_1], [l_2; r_2], \ldots, [l_c; r_c]$$$, where $$$l_1 = 1$$$, $$$r_c = k$$$, and for any $$$2 \leq i \leq c$$$ holds that $$$r_{i-1} + 1 = l_i$$$. In other words, each element of the array belongs to exactly one segment.Let's define the cost of a partition as $$$$$$c + \sum_{i = 1}^{c} \operatorname{mex}(\{b_{l_i}, b_{l_i + 1}, \ldots, b_{r_i}\}),$$$$$$ where $$$\operatorname{mex}$$$ of a set of numbers $$$S$$$ is the smallest non-negative integer that does not occur in the set $$$S$$$. In other words, the cost of a partition is the number of segments plus the sum of MEX over all segments. Let's define the value of an array $$$b_1, b_2, \ldots, b_k$$$ as the maximum possible cost over all partitions of this array.You are given an array $$$a$$$ of size $$$n$$$. Find the sum of values of all its subsegments.An array $$$x$$$ is a subsegment of an array $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 30$$$) — the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case print a single integer — the answer to the problem.

NoteIn the second test case:   The best partition for the subsegment $$$[2, 0, 1]$$$: $$$[2], [0, 1]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0, 1\}) = 2 + 0 + 2 = 4$$$.  The best partition for the subsegment $$$[2, 0]$$$: $$$[2], [0]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0\}) = 2 + 0 + 1 = 3$$$  The best partition for the subsegment $$$[2]$$$: $$$[2]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{2\}) = 1 + 0 = 1$$$.  The best partition for the subsegment $$$[0, 1]$$$: $$$[0, 1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0, 1\}) = 1 + 2 = 3$$$.  The best partition for the subsegment $$$[0]$$$: $$$[0]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0\}) = 1 + 1 = 2$$$.  The best partition for the subsegment $$$[1]$$$: $$$[1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{1\}) = 1 + 0 = 1$$$. The sum of values over all subsegments equals to $$$4 + 3 + 1 + 3 + 2 + 1 = 14$$$.

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

const main = () => {

	// simply break every subsegment into individual items
	var t = readInt();
	while (t--) {
		var n = readInt();
		var a = readIntArr();
		var l = 1;
		var r = n;
		var ans = 0;
		for (var x of a) {
			var v;
			if (x === 0) v = 2;
			else v = 1;
			ans += v * l++ * r--;
		}
		print(ans);
	}

	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


You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.

For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.

NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
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) => JSON.stringify(a) == JSON.stringify(b);
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 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; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/B
 */

const solve = (n, a) => {
    if (isAscending(a)) return pr(0);
    if (a[0] == 1 || a[n - 1] == n) return pr(1);
    if (a[0] == n && a[n - 1] == 1) return pr(3);
    pr(2);
};

const isAscending = (arr) => {
    return arr.every((x, i) => {
        return i === 0 || x > arr[i - 1];
    });
};

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]);
            i += 2;
        }
    });
};

main()

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

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

    let testCases = parseInt(readLine());

    while(testCases--) {

        const n = parseInt(readLine());

        const arr = get_ints();

        b(n,arr);
    }
});

function a(k)
{
    let e = 0;
    let w = 0;
    let pe = k;
    let pw = 100 - k;
    const c = gcd(pe,pw);
    return console.log(pe / c + pw / c);
}

function b(n,arr)
{
    let flag = true;
    for(let i = 0 ; i < n; i++)
    {
        if(arr[i] !== i+1) {
            flag = false;
            break;
        }
    }
    if(flag) return console.log(0);
    if(arr[0] === n && arr[n-1] === 1) return console.log(3);
    if(arr[0] === 1 || arr[n-1] === n) return console.log(1);
    return console.log(2);
}

function gcd(x, y) {
    if ((typeof x !== 'number') || (typeof y !== 'number'))
      return false;
    x = Math.abs(x);
    y = Math.abs(y);
    while(y) {
      var t = y;
      y = x % y;
      x = t;
    }
    return x;
  }

function get_ints() {
    return readLine().split(' ').map(Number);
}

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

module.exports = b;

//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] = BigInt(next());
		}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 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 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);
		var isOK = true;
		for(var i = 1; i < N; i++){
			if(list[i - 1] + 1 != list[i]){
				isOK = false;
				break;
			}
		}
		if(isOK){
			myout(0);
			continue;
		}
		if(list[0] == 1 || list[N - 1] == N){
			myout(1);
		}else if(list[0] == N && list[N - 1] == 1){
			myout(3);
		}else{
			myout(2);
		}

	}
}

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 readLine = () => dataitr.next().value.trim();
function rl () {
	let ans = readLine().split(' ');
	if (!isNaN(Number(ans[0]))) ans = ans.map(x => Number(x));
	return ans.length == 1 ? ans[0] : ans;
}

function main () {
	let t = rl();
	while(t--) {
		let n = rl();
		let a = rl();

		let min = max = a[0], isSorted = true;
		for (let i = 1; i < n; i++) {
			if (a[i] < a[i - 1]) isSorted = false;
			min = Math.min(min, a[i]);
			max = Math.max(max, a[i]);
		}
		let ans;
		if (isSorted) ans = 0;
		else if (min == a[n - 1] && max == a[0]) ans = 3;
		else if (min == a[0] || max == a[n - 1]) ans = 1;
		else ans = 2;

		console.log(ans);
	}
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));

  var min = a[0];
  var max = min;
  var min_i = 0;
  var max_i = min_i;
  var sorted = true;

  for (var i = 1; i < n; i++) {
    if (a[i] < min) {
      min = a[i];
      min_i = i;
    } else if (a[i] > max) {
      max = a[i];
      max_i = i;
    }
    if (a[i] < a[i - 1])
      sorted = false;
  }

  if (sorted)
    print(0);
  else if (min_i === n - 1 && max_i === 0)
    print(3);
  else if (min_i !== 0 && max_i !== n - 1)
    print(2);
  else
    print(1);
}

const isSorted = (arr, temp) => {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] != temp[i]) {
            return false
        }
    }
    return true
}

const cases = readline();
for (var i = 0; i < cases; i++) {
    var size = readline()
    var inp = readline()
    var arr = inp.split(' ')
    var temp = inp.split(' ')
    temp = temp.sort((a, b) => { return a - b })
    var res = 2
    if (isSorted(arr, temp))
        res = 0;
    else if (arr[0] == 1 || arr[size - 1] == size)
        res = 1;
    else if (arr[0] == size && arr[size - 1] == 1)
        res = 3;
    print(res)
}

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
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) => JSON.stringify(a) == JSON.stringify(b);
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 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; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 05/15/21 night
 * https://codeforces.com/contest/1525/problem/B
 */

const solve = (n, a) => {
    if (isAscending(a)) return pr(0);
    if (a[0] == 1 || a[n - 1] == n) return pr(1);
    if (a[0] == n || a[n - 1] == 1) return pr(3);
    pr(2);
};

const isAscending = (arr) => {
    return arr.every((x, i) => {
        return i === 0 || x > arr[i - 1];
    });
};

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]);
            i += 2;
        }
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
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) => JSON.stringify(a) == JSON.stringify(b);
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 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 solve = (n, a) => {
    let sa = [...a];
    stin(sa);
    // pr(sa);
    // pr(n, a)
    let res = 0;
    if (isAscending(a)) return pr(res);
    while (!isAscending(a)) {
        // let next = 0;
        for (let i = 0; i < n; i++) {
            let should = i + 1;
            if (a[i] != should) {
                let l = a.slice(0, i + 1);
                let ol = [...l];
                stin(l);
                if (!aeq(l, ol)) res++;
                let r = a.slice(i + 1);
                let or = [...r]
                stin(r);
                if (!aeq(r, or)) res++;
                a = l.concat(r);
            }
        }
    }
    // pr(a);
    pr(res);
};

const isAscending = (arr) => {
    return arr.every((x, i) => {
        return i === 0 || x > arr[i - 1];
    });
};

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]);
            i += 2;
        }
    });
};

main()

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

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

    let testCases = parseInt(readLine());

    while(testCases--) {

        const n = parseInt(readLine());

        const arr = get_ints();

        b(arr);
    }
});

function a(k)
{
    let e = 0;
    let w = 0;
    let pe = k;
    let pw = 100 - k;
    const c = gcd(pe,pw);
    return console.log(pe / c + pw / c);
}

function b(n,arr)
{
    let flag = true;
    for(let i = 0 ; i < n; i++)
    {
        if(arr[i] !== i+1) {
            flag = false;
            break;
        }
    }
    if(flag) return console.log(0);
    if(arr[0] === n && arr[n-1] === 1) return console.log(3);
    if(arr[0] === 1 || arr[n-1] === n) return console.log(1);
    return console.log(2);
}

function gcd(x, y) {
    if ((typeof x !== 'number') || (typeof y !== 'number'))
      return false;
    x = Math.abs(x);
    y = Math.abs(y);
    while(y) {
      var t = y;
      y = x % y;
      x = t;
    }
    return x;
  }

function get_ints() {
    return readLine().split(' ').map(Number);
}

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

module.exports = b;

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

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

    let testCases = parseInt(readLine());

    while(testCases--) {

        const n = parseInt(readLine());

        const arr = get_ints();

        b(arr);
    }
});

function a(k)
{
    let e = 0;
    let w = 0;
    let pe = k;
    let pw = 100 - k;
    const c = gcd(pe,pw);
    return console.log(pe / c + pw / c);
}

function b(arr)
{
    let peaks = 0;
    for(let i = 0; i < arr.length - 2; i++)
    {
        if(i === 0 && arr[0] !== 1) peaks++;
        if(arr[i] < arr[i+1] && arr[i+1] > arr[i+2]) peaks++;
    }
    return console.log(peaks)
}

function gcd(x, y) {
    if ((typeof x !== 'number') || (typeof y !== 'number'))
      return false;
    x = Math.abs(x);
    y = Math.abs(y);
    while(y) {
      var t = y;
      y = x % y;
      x = t;
    }
    return x;
  }

function get_ints() {
    return readLine().split(' ').map(Number);
}

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

module.exports = b;

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

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

    let testCases = parseInt(readLine());

    while(testCases--) {

        const n = parseInt(readLine());

        const arr = get_ints();

        b(arr);
    }
});

function a(k)
{
    let e = 0;
    let w = 0;
    let pe = k;
    let pw = 100 - k;
    const c = gcd(pe,pw);
    return console.log(pe / c + pw / c);
}

function b(arr)
{
    let peaks = 0;
    for(let i = 0; i < arr.length - 2; i++)
    {
        if(i === 0 && arr[0] !== 1) peaks++;
        if(arr[i] < arr[i+1] && arr[i+1] > arr[i+2]) peaks++;
    }
    return console.log(peaks)
}

function gcd(x, y) {
    if ((typeof x !== 'number') || (typeof y !== 'number'))
      return false;
    x = Math.abs(x);
    y = Math.abs(y);
    while(y) {
      var t = y;
      y = x % y;
      x = t;
    }
    return x;
  }

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

module.exports = b;

//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] = BigInt(next());
		}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 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 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);
		var isOK = true;
		for(var i = 1; i < N; i++){
			if(list[i - 1] + 1 != list[i]){
				isOK = false;
				break;
			}
		}
		if(isOK){
			myout(0);
			continue;
		}
		if(list[0] == 1 || list[N - 1] == N || list[0] == N || list[N - 1] == 0){
			myout(1);
		}else{
			myout(2);
		}

	}
}

//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] = BigInt(next());
		}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 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 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);
		var isOK = true;
		for(var i = 1; i < N; i++){
			if(list[i - 1] + 1 != list[i]){
				isOK = false;
				break;
			}
		}
		if(isOK){
			myout(0);
			continue;
		}
		if(list[0] == 1 || list[N - 1] == N){
			myout(1);
		}else{
			myout(2);
		}

	}
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));

  var min = a[0];
  var max = min;
  var min_i = 0;
  var max_i = min_i;
  var sorted = true;

  for (var i = 1; i < n; i++) {
    if (a[i] < min) {
      min = a[i];
      min_i = i;
    } else if (a[i] > max) {
      max = a[i];
      max_i = i;
    }
    if (a[i] < a[i - 1])
      sorted = false;
  }

  print(sorted? 0: (min_i !== 0 && max_i !== n - 1 && n > 2)? 2: 1);
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));

  var min = a[0];
  var max = min;
  var min_i = 0;
  var max_i = min_i;
  var sorted = true;

  for (var i = 1; i < n; i++) {
    if (a[i] < min) {
      min = a[i];
      min_i = i;
    } else if (a[i] > max) {
      max = a[i];
      max_i = i;
    }
    if (a[i] < a[i - 1])
      sorted = false;
  }

  print(sorted? 0: (min_i !== 0 && max_i !== n - 1)? 2: 1);
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));

  var min = a[0];
  var min_index = 0;
  var sorted = true;

  for (var i = 1; i < n; i++) {
    if (a[i] < min) {
      min = a[i];
      min_index = i;
      sorted = false;
    }
    if (a[i] < a[i - 1])
      sorted = false;
  }

  print(sorted? 0: min_index? 2: 1);
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));

  var min = a[0];
  var min_index = 0;
  var sorted = true;

  for (var i = 1; i < n; i++) {
    if (a[i] < min) {
      min = a[i];
      min_index = i;
    }
    if (a[i] < a[i - 1])
      sorted = false;
  }

  print(sorted? 0: min_index? 2: 1);
}

const cases = readline();
for (var i = 0; i < cases; i++) {
  var size = readline()
  var inp = readline()
  var a = inp.split(' ')
  var temp = inp.split(' ')
  temp = temp.sort((a,b)=>{return a-b})
  var res = 2
  if (temp == a)
    res = 0;
  else if (a[0] == 1 || a[size - 1] == size)
    res = 1;
  else if (a[0] == size && a[size - 1] == 1)
    res = 3;
  print(res)
}

const cases = readline()
for (var i = 0; i < cases; i++) {
  var size = readline()
  var inp = readline()
  var arr = inp.split(' ')
  var temp = inp.split(' ')
  temp = temp.sort((a,b)=>{return a-b})
  var count = 0
  for (var k=0; k < size; k++){
    if(arr[k] != temp[k]){
      count++
    }
  }
  print(Math.floor(count/2))
}


Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task.Two matrices $$$A$$$ and $$$B$$$ are given, each of them has size $$$n \times m$$$. Nastya can perform the following operation to matrix $$$A$$$ unlimited number of times:   take any square square submatrix of $$$A$$$ and transpose it (i.e. the element of the submatrix which was in the $$$i$$$-th row and $$$j$$$-th column of the submatrix will be in the $$$j$$$-th row and $$$i$$$-th column after transposing, and the transposed submatrix itself will keep its place in the matrix $$$A$$$). Nastya's task is to check whether it is possible to transform the matrix $$$A$$$ to the matrix $$$B$$$.    Example of the operation As it may require a lot of operations, you are asked to answer this question for Nastya.A square submatrix of matrix $$$M$$$ is a matrix which consist of all elements which comes from one of the rows with indeces $$$x, x+1, \dots, x+k-1$$$ of matrix $$$M$$$ and comes from one of the columns with indeces $$$y, y+1, \dots, y+k-1$$$ of matrix $$$M$$$. $$$k$$$ is the size of square submatrix. In other words, square submatrix is the set of elements of source matrix which form a solid square (i.e. without holes).

The first line contains two integers $$$n$$$ and $$$m$$$ separated by space ($$$1 \leq n, m \leq 500$$$) — the numbers of rows and columns in $$$A$$$ and $$$B$$$ respectively. Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$A$$$ ($$$1 \leq A_{ij} \leq 10^{9}$$$). Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$B$$$ ($$$1 \leq B_{ij} \leq 10^{9}$$$).

Print "YES" (without quotes) if it is possible to transform $$$A$$$ to $$$B$$$ and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).

NoteConsider the third example. The matrix $$$A$$$ initially looks as follows.$$$$$$ \begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{bmatrix} $$$$$$Then we choose the whole matrix as transposed submatrix and it becomes$$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 8\\ 3 & 6 & 9 \end{bmatrix} $$$$$$Then we transpose the submatrix with corners in cells $$$(2, 2)$$$ and $$$(3, 3)$$$. $$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & \textbf{5} & \textbf{8}\\ 3 & \textbf{6} & \textbf{9} \end{bmatrix} $$$$$$So matrix becomes$$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 6\\ 3 & 8 & 9 \end{bmatrix} $$$$$$and it is $$$B$$$.

const nm = readline().split(" ").map(e => parseInt(e));

const n = nm[0];
const m = nm[1];

readMatrix = () => {
	const result = [];
	for (var i = 0; i < n; i++) {
		result.push(readline().split(" ").map(e => parseInt(e)));
	}
	return result;
};

const a = readMatrix();
const b = readMatrix();

const inA = [];
const inB = [];

for (var i = 0; i < n; i++) {
	for (var j = 0; j < m; j++) {
		if (inA[i + j] === undefined) {
			inA[i + j] = [];
			inB[i + j] = [];
		}
		inA[i + j].push(a[i][j]);
		inB[i + j].push(b[i][j]);
	}
}

const cmp = function(a, b) {
	if (a.length != b.length) {
		return false;
	}
	for (var i in a) {
		if (a[i] !== b[i]) {
			return false;
		}
	}
	return true;
};
var result = true;
for (var i in inA) {
	if (inB[i] === undefined || !cmp(inA[i].sort((a, b) => a - b), inB[i].sort((a, b) => a - b))) {
		result = false;
		break;
	}
}
print(result ? "YES" : "NO");

var inp = readline().split(' ').map(x => parseInt(x));
var n = inp[0], m = inp[1];
var tot = n * m;

var A = new Array(),
	B = new Array(),
	adiag = new Array(),
	bdiag = new Array();

for(var i = 0; i < n; i++){
	inp = readline().split(' ').map(x => parseInt(x));
	A.push(inp);
}
for(var i = 0; i < n; i++){
	inp = readline().split(' ').map(x => parseInt(x));
	B.push(inp);
}

const cmp = (a, b) => (a - b);

var bad = false;
for(var col = 0; col < m; col++){
	var j = col;
	var i = 0;
	adiag = [];
	bdiag = [];
	while(j >= 0 && i < n){
		adiag.push(A[i][j]);
		bdiag.push(B[i][j]);
		j--;
		i++;
	}
	adiag.sort(cmp);
	bdiag.sort(cmp);
	var match = 0;
	adiag.forEach((x, i) => {
		if(x === bdiag[i]) match++;
	});
	if(match === adiag.length) continue;
	else{
		bad = true;
		break;
	}
}
if(bad) print("NO");
else{
	for(var row = 1; row < n; row++){
		var j = m;
		var i = row;
		adiag = [];
		bdiag = [];
		while(j >= 0 && i < n){
			adiag.push(A[i][j]);
			bdiag.push(B[i][j]);
			j--;
			i++;
		}
		adiag.sort(cmp);
		bdiag.sort(cmp);
		var match = 0;
		adiag.forEach((x, i) => {
			if(x === bdiag[i]) match++;
		});
		if(match === adiag.length) continue;
		else{
			bad = true;
			break;
		}
	}
	if(bad) print("NO");
	else print("YES");
}


There is a chess board of size $$$n \times m$$$. The rows are numbered from $$$1$$$ to $$$n$$$, the columns are numbered from $$$1$$$ to $$$m$$$.Let's call a cell isolated if a knight placed in that cell can't move to any other cell on the board. Recall that a chess knight moves two cells in one direction and one cell in a perpendicular direction:   Find any isolated cell on the board. If there are no such cells, print any cell on the board.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 64$$$) — the number of testcases. The only line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 8$$$) — the number of rows and columns of the board.

For each testcase, print two integers — the row and the column of any isolated cell on the board. If there are no such cells, print any cell on the board.

NoteIn the first testcase, all cells are isolated. A knight can't move from any cell of the board to any other one. Thus, any cell on board is a correct answer.In the second testcase, there are no isolated cells. On a normal chess board, a knight has at least two moves from any cell. Thus, again, any cell is a correct answer.In the third testcase, only the middle cell of the board is isolated. The knight can move freely around the border of the board, but can't escape the middle.

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseArray = readline().split(" ");
    var rows = parseInt(caseArray[0]);
    var columns = parseInt(caseArray[1]);
    var result = "1 1";
    if ((rows === 2 || rows === 3) && (columns === 2 || columns == 3))
    {
        result = "2 2";
    }
    print(result);
}

var rl = readline
var toN = function(x) { return +x }
var rn = function() { return toN(rl()) }
var ran = function() {
	return (rl()
		.split(' ')
		.map(toN)
	)
}

var mid = function(x) {
	return Math.floor(x/2)+1
}

var main = function() {
	var t = rn()
	var res = new Array(t).fill([0,0])

	res.forEach(function(x) {
		var nm = ran()
		var n = mid(nm[0])
		var m = mid(nm[1])
		print(n, m)
	})
}

main()

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

let currentLine = 0;
let inputString = "";

process.stdin.on("data", (raw_data) => {
  inputString += raw_data;
});

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

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

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

function readArrayInt() {
  return inputString[currentLine++].split(" ").map(Number);
}

function readArray() {
  return inputString[currentLine++].split(" ");
}

function solve() {
  const T = readInt();

  for (let i = 0; i < T; ++i) {
    const [n, m] = readArrayInt();

    const arr = [];

    let count = 1;
    for (let i = 0; i < n; ++i) {
      const brr = [];
      for (let j = 0; j < m; ++j) {
        brr.push(count);
        ++count;
      }
      arr.push(brr);
    }

    let check = false;
    for (let i = 0; i < n; ++i) {
      for (let j = 0; j < m; ++j) {
        if (!isOk(arr, i, j)) {
          console.log(i + 1, j + 1);
          check = true;
          break;
        }
      }
      if (check) break;
    }

    if (!check) {
      console.log(n, m);
    }

    // # # #
    // # # #
    // # # #
  }
}

// function isOk(arr, i, j) {
//   if (
//     arr?.[i + 2]?.[j + 1] ||
//     arr?.[i + 2]?.[j - 1] ||
//     arr?.[i + -2]?.[j + 1] ||
//     arr?.[i - 2]?.[j - 1] ||
//     arr?.[i + 1]?.[j + 2] ||
//     arr?.[i + 1]?.[j - 2] ||
//     arr?.[i + -1]?.[j + 2] ||
//     arr?.[i - 1]?.[j - 2]
//   ) {
//     return true;
//   }

//   return false;
// }

function isOk(arr, i, j) {
  var _arr, _arr2, _arr3, _arr4, _arr5, _arr6, _arr7, _arr8;

  if (
    (arr !== null &&
      arr !== void 0 &&
      (_arr = arr[i + 2]) !== null &&
      _arr !== void 0 &&
      _arr[j + 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr2 = arr[i + -2]) !== null &&
      _arr2 !== void 0 &&
      _arr2[j + 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr3 = arr[i + 2]) !== null &&
      _arr3 !== void 0 &&
      _arr3[j - 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr4 = arr[i - 2]) !== null &&
      _arr4 !== void 0 &&
      _arr4[j - 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr5 = arr[i + 1]) !== null &&
      _arr5 !== void 0 &&
      _arr5[j + 2]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr6 = arr[i + -1]) !== null &&
      _arr6 !== void 0 &&
      _arr6[j + 2]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr7 = arr[i + 1]) !== null &&
      _arr7 !== void 0 &&
      _arr7[j - 2]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr8 = arr[i - 1]) !== null &&
      _arr8 !== void 0 &&
      _arr8[j - 2])
  ) {
    return true;
  }

  return false;
}

function main() {
  solve();
}

var toN = x => +x

class Input {
	constructor(data)  {
		this.lines = data.split(/\r?\n/)
		this.index = 0
	}

	readL() {
		return this.lines[this.index++]
	}

	readN() {
		return toN(this.readL())
	}

	readAr() {
		return this.readL().split(' ')
	}

	readArN() {
		return this.readAr().map(toN)
	}
}

/*var createInput = (data) => {
	var lines = data.split(/\r?\n/)
	var index = 0;

	var readL = () => lines[index++]
	var readN = () => toN(readL())
	var readAr = () => readL().split(' ')
	var readArN = () => readAr().map(toN)

	return {
		readL, readN, readAr, readArN
	}
}
*/
var input = async () => new Promise(r=>{
	var data = ''
	process.stdin.on('data', chunk=>data+=chunk)
	process.stdin.on('end', () => r(new Input(data)))
})

var mid = x => (x-x%2)/2+1

var main = async () => {
	var inp = await input()
	var t = inp.readN()
	var res = new Array(t).fill(0).map(()=>inp.readArN())
	res.forEach(([n, m]) => console.log(mid(n), mid(m)))
}

main()

var createInput = (data) => {
	var lines = data.replace(/\r/g, '').split('\n')
	var index = 0;

	var toN = x => +x
	var readL = () => lines[index++]
	var readN = () => toN(readL())
	var readAr = () => readL().split(' ')
	var readArN = () => readAr().map(toN)

	return {
		readL, readN, readAr, readArN
	}
}

var input = async () => new Promise(r=>{
	var data = ''
	process.stdin.on('data', chunk=>data+=chunk)
	process.stdin.on('end', () => r(createInput(data)))
})

var mid = x => (x-x%2)/2+1

var main = async () => {
	var {readN, readArN} = await input()
	var t = readN()
	var res = new Array(t).fill(0).map(readArN)
	res.forEach(([n, m]) => console.log(mid(n), mid(m)))
}

main()

process.stdin.resume();
process.stdin.setEncoding("ascii");

_data = "";
process.stdin.on("data", function (data) {
   _data += data;
});

process.stdin.on("end", function () {
   processData(_data);
});

function processData(data) {
    const lines = data.trim().split("\n");
    for (let i = 0; i < lines[0]; i++) {
        processTC(lines, i+1);
    }
}

function processTC(lines, startLine) {
    const [n, m] = lines[startLine].trim().split(" ").map(x => Number(x));
    if (m == 3 && n == 3) {
        return console.log(2, 2);
    } else if (m == 3) {
        return console.log(n, 2);
    } else if (n == 3) {
        return console.log(2, m);
    }
    return console.log(n, m);
}

var readline = require('readline');
var inputString = [], currentLine = 0;
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var rl = readline.createInterface(process.stdin);
rl.on('line', line => { inputString.push(line) });
process.stdin.on('end', () => {  main()  });

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

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

function myFunc(l, c){

    let lr = Math.ceil(l/2);
    let cr = Math.ceil(c/2);
    console.log(lr, cr);

}

// Common Template Starts //
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++];
}
// Common Template Ends //

const getSolution = (n, m) => {

    if( n == 1 || m == 1) return [n,m].join(' ') // all are isolated
    else if( n <= 2 && m <= 2) return [n,m].join(' ') // all are isolated
    else if( n == 3 && m == 3) return [2,2].join(' ') // only 2,2 is isolated
    else if( n > 3 && m > 3) return [1,1].join(' ') // none are isolated
    else {
        let x = Math.floor(n/2) + 1
        let y = Math.floor(m/2) + 1
        return [x,y].join(' ')
    }
}

// Driver Function Starts //
function main() {

    let testcases = parseInt( readline() )
    while(testcases--){

        let arr = readline().split(' ').map(Number)
        let n = arr[0]
        let m = arr[1]

        console.log( getSolution(n,m)  )
    }

}
// Driver Function Ends //

'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 = rn(),
        m = rn();
  if (n === 1 || m === 1) return `1 1`;
  if (n === 2) return `2 ${Math.ceil(m / 2)}`;
  if (m === 2) return `${Math.ceil(n / 2)} 2`;
  return `2 2`;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 100;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      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(/\s+/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

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

let currentLine = 0;
let inputString = "";

process.stdin.on("data", (raw_data) => {
  inputString += raw_data;
});

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

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

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

function readArrayInt() {
  return inputString[currentLine++].split(" ").map(Number);
}

function readArray() {
  return inputString[currentLine++].split(" ");
}

function solve() {
  const T = readInt();

  for (let i = 0; i < T; ++i) {
    const [n, m] = readArrayInt();

    const arr = [];

    let count = 1;
    for (let i = 0; i < n; ++i) {
      const brr = [];
      for (let j = 0; j < m; ++j) {
        brr.push(2000);
        ++count;
      }
      arr.push(brr);
    }

    let check = false;
    for (let i = 0; i < n; ++i) {
      for (let j = 0; j < m; ++j) {
        if (!isOk(arr, i, j)) {
          console.log(i + 1, j + 1);
          check = true;
          break;
        }
      }
    }

    if (!check) {
      console.log(n, m);
    }

    // # # #
    // # # #
    // # # #
  }
}

// function isOk(arr, i, j) {
//   if (
//     arr?.[i + 2]?.[j + 1] ||
//     arr?.[i + 2]?.[j - 1] ||
//     arr?.[i + -2]?.[j + 1] ||
//     arr?.[i - 2]?.[j - 1] ||
//     arr?.[i + 1]?.[j + 2] ||
//     arr?.[i + 1]?.[j - 2] ||
//     arr?.[i + -1]?.[j + 2] ||
//     arr?.[i - 1]?.[j - 2]
//   ) {
//     return true;
//   }

//   return false;
// }

function isOk(arr, i, j) {
  var _arr, _arr2, _arr3, _arr4, _arr5, _arr6, _arr7, _arr8;

  if (
    (arr !== null &&
      arr !== void 0 &&
      (_arr = arr[i + 2]) !== null &&
      _arr !== void 0 &&
      _arr[j + 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr2 = arr[i + -2]) !== null &&
      _arr2 !== void 0 &&
      _arr2[j + 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr3 = arr[i + 2]) !== null &&
      _arr3 !== void 0 &&
      _arr3[j - 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr4 = arr[i - 2]) !== null &&
      _arr4 !== void 0 &&
      _arr4[j - 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr5 = arr[i + 1]) !== null &&
      _arr5 !== void 0 &&
      _arr5[j + 2]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr6 = arr[i + -1]) !== null &&
      _arr6 !== void 0 &&
      _arr6[j + 2]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr7 = arr[i + 1]) !== null &&
      _arr7 !== void 0 &&
      _arr7[j - 2]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr8 = arr[i - 1]) !== null &&
      _arr8 !== void 0 &&
      _arr8[j - 2])
  ) {
    return true;
  }

  return false;
}

function main() {
  solve();
}

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

let currentLine = 0;
let inputString = "";

process.stdin.on("data", (raw_data) => {
  inputString += raw_data;
});

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

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

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

function readArrayInt() {
  return inputString[currentLine++].split(" ").map(Number);
}

function readArray() {
  return inputString[currentLine++].split(" ");
}

function solve() {
  const T = readInt();

  for (let i = 0; i < T; ++i) {
    const [n, m] = readArrayInt();

    const arr = [];

    let count = 1;
    for (let i = 0; i < n; ++i) {
      const brr = [];
      for (let j = 0; j < m; ++j) {
        brr.push(count);
        ++count;
      }
      arr.push(brr);
    }

    let check = false;
    for (let i = 0; i < n; ++i) {
      for (let j = 0; j < m; ++j) {
        if (!isOk(arr, i, j)) {
          console.log(i + 1, j + 1);
          check = true;
          break;
        }
      }
    }

    if (!check) {
      console.log(n, m);
    }

    // # # #
    // # # #
    // # # #
  }
}

// function isOk(arr, i, j) {
//   if (
//     arr?.[i + 2]?.[j + 1] ||
//     arr?.[i + -2]?.[j + 1] ||
//     arr?.[i + 2]?.[j - 1] ||
//     arr?.[i - 2]?.[j - 1] ||
//     arr?.[i + 1]?.[j + 2] ||
//     arr?.[i + -1]?.[j + 2] ||
//     arr?.[i + 1]?.[j - 2] ||
//     arr?.[i - 1]?.[j - 2]
//   ) {
//     return true;
//   }

//   return false;
// }

function isOk(arr, i, j) {
  var _arr, _arr2, _arr3, _arr4, _arr5, _arr6, _arr7, _arr8;

  if (
    (arr !== null &&
      arr !== void 0 &&
      (_arr = arr[i + 2]) !== null &&
      _arr !== void 0 &&
      _arr[j + 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr2 = arr[i + -2]) !== null &&
      _arr2 !== void 0 &&
      _arr2[j + 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr3 = arr[i + 2]) !== null &&
      _arr3 !== void 0 &&
      _arr3[j - 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr4 = arr[i - 2]) !== null &&
      _arr4 !== void 0 &&
      _arr4[j - 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr5 = arr[i + 1]) !== null &&
      _arr5 !== void 0 &&
      _arr5[j + 2]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr6 = arr[i + -1]) !== null &&
      _arr6 !== void 0 &&
      _arr6[j + 2]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr7 = arr[i + 1]) !== null &&
      _arr7 !== void 0 &&
      _arr7[j - 2]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr8 = arr[i - 1]) !== null &&
      _arr8 !== void 0 &&
      _arr8[j - 2])
  ) {
    return true;
  }

  return false;
}

function main() {
  solve();
}

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

let currentLine = 0;
let inputString = "";

process.stdin.on("data", (raw_data) => {
  inputString += raw_data;
});

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

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

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

function readArrayInt() {
  return inputString[currentLine++].split(" ").map(Number);
}

function readArray() {
  return inputString[currentLine++].split(" ");
}

function solve() {
  const T = readInt();

  for (let i = 0; i < T; ++i) {
    const [n, m] = readArrayInt();

    const arr = [];

    let count = 1;
    for (let i = 0; i < n; ++i) {
      const brr = [];
      for (let j = 0; j < m; ++j) {
        brr.push(count);
        ++count;
      }
      arr.push(brr);
    }

    for (let i = 0; i < n; ++i) {
      for (let j = 0; j < m; ++j) {
        if (!isOk(arr, i, j)) {
          console.log(i + 1, j + 1);
          return;
        }
      }
    }
    console.log(n, m);

    // # # #
    // # # #
    // # # #
  }
}

// function isOk(arr, i, j) {
//   if (
//     arr?.[i + 2]?.[j + 1] ||
//     arr?.[i + -2]?.[j + 1] ||
//     arr?.[i + 2]?.[j - 1] ||
//     arr?.[i - 2]?.[j - 1] ||
//     arr?.[i + 1]?.[j + 2] ||
//     arr?.[i + -1]?.[j + 2] ||
//     arr?.[i + 1]?.[j - 2] ||
//     arr?.[i - 1]?.[j - 2]
//   ) {
//     return true;
//   }

//   return false;
// }

function isOk(arr, i, j) {
  var _arr, _arr2, _arr3, _arr4, _arr5, _arr6, _arr7, _arr8;

  if (
    (arr !== null &&
      arr !== void 0 &&
      (_arr = arr[i + 2]) !== null &&
      _arr !== void 0 &&
      _arr[j + 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr2 = arr[i + -2]) !== null &&
      _arr2 !== void 0 &&
      _arr2[j + 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr3 = arr[i + 2]) !== null &&
      _arr3 !== void 0 &&
      _arr3[j - 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr4 = arr[i - 2]) !== null &&
      _arr4 !== void 0 &&
      _arr4[j - 1]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr5 = arr[i + 1]) !== null &&
      _arr5 !== void 0 &&
      _arr5[j + 2]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr6 = arr[i + -1]) !== null &&
      _arr6 !== void 0 &&
      _arr6[j + 2]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr7 = arr[i + 1]) !== null &&
      _arr7 !== void 0 &&
      _arr7[j - 2]) ||
    (arr !== null &&
      arr !== void 0 &&
      (_arr8 = arr[i - 1]) !== null &&
      _arr8 !== void 0 &&
      _arr8[j - 2])
  ) {
    return true;
  }

  return false;
}

function main() {
  solve();
}


You are a game designer and want to make an obstacle course. The player will walk from left to right. You have $$$n$$$ heights of mountains already selected and want to arrange them so that the absolute difference of the heights of the first and last mountains is as small as possible. In addition, you want to make the game difficult, and since walking uphill or flat is harder than walking downhill, the difficulty of the level will be the number of mountains $$$i$$$ ($$$1 \leq i < n$$$) such that $$$h_i \leq h_{i+1}$$$ where $$$h_i$$$ is the height of the $$$i$$$-th mountain. You don't want to waste any of the mountains you modelled, so you have to use all of them. From all the arrangements that minimize $$$|h_1-h_n|$$$, find one that is the most difficult. If there are multiple orders that satisfy these requirements, you may find any.

The first line will contain a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the number of mountains. The second line of each test case contains $$$n$$$ integers $$$h_1,\ldots,h_n$$$ ($$$1 \leq h_i \leq 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th mountain. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output $$$n$$$ integers — the given heights in an order that maximizes the difficulty score among all orders that minimize $$$|h_1-h_n|$$$. If there are multiple orders that satisfy these requirements, you may output any.

NoteIn the first test case:The player begins at height $$$2$$$, next going up to height $$$4$$$ increasing the difficulty by $$$1$$$. After that he will go down to height $$$1$$$ and the difficulty doesn't change because he is going downhill. Finally the player will go up to height $$$2$$$ and the difficulty will increase by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$0$$$ and it's minimal. The difficulty is maximal.In the second test case:The player begins at height $$$1$$$, next going up to height $$$3$$$ increasing the difficulty by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$2$$$ and it's minimal as they are the only heights. The difficulty is maximal.

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++) {
        const n = parseInt(await getLine());
        const arr = (await getLine()).split(' ').map(n => parseInt(n));
        arr.sort((a,b) => a - b);
        let mindiff = arr[arr.length - 1] - arr[0] + 2;
        for(let i = 1; i < arr.length; i++) {
            mindiff = Math.min(mindiff, arr[i] - arr[i-1]);
        }
        const printbest = function(pos) {
            rl.output.write(arr[pos + 1]+ '');
            for(let i = pos + 2; i<arr.length; i++) {
                rl.output.write(' ' + arr[i]);
            }
            for(let i = 0; i<=pos; i++)
                rl.output.write(' ' + arr[i]);
            rl.output.write('\n');
        }
        if (arr[1] - arr[0] === mindiff){
            if (arr.length === 2)
                rl.output.write(arr[0] + ' ' + arr[1]+'\n');
            else
                printbest(0);
        } else if (arr[arr.length - 1] - arr[arr.length - 2] === mindiff) {
            printbest(arr.length - 2);
        } else {
            for(let i = 1; i<arr.length; i++)
                if (arr[i] - arr[i-1] === mindiff){
                    printbest(i-1);
                    break;
                }
        }
    }
}

solve();

process.stdin.resume();
process.stdin.setEncoding('utf8');

var arr = '';
process.stdin.on('data', function (chunk) {
    arr += chunk;
});
process.stdin.on('end', function () {
    arr = arr.split('\n');
    var t = +arr.shift();
    for (var i = 0; i < t; i++) {
        let n = +arr.shift();
        let array = arr.shift().split(' ').map(Number);
        solve(n, array);
    }
});
function solve(n, array) {
    var arr = array.sort((a, b) => (a - b));
    if (n <= 2) {
        console.log(arr.join(" "));
        return;
    }
    let idx = -1;
    let min = Number.MAX_SAFE_INTEGER;
    for (let i = 0; i < n - 1; i++) {
        if (arr[i + 1] - arr[i] < min) {
            idx = i;
            min = arr[i + 1] - arr[i];
        }
    }

    let ans = [];
    let p = 0;
    for (let i = idx + 1; i < n; i++) {
        ans[p++] = arr[i];
    }

    for (let i = 0; i <= idx; i++) {
        ans[p++] = arr[i];
    }

    console.log(ans.join(" "));
}

"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));
    arr.sort((a, b) => a - b);
    let min = Infinity,
      s,
      e;
    for (let i = 0; i < n - 1; i++) {
      let d = arr[i + 1] - arr[i];
      if (d < min) {
        min = d;
        s = i;
        e = i + 1;
      }
    }
    let ans = [];
    ans.push(arr[s]);
    let ind = e + 1;
    for (let i = 0; i < n - 2; i++, ind++) ans.push(arr[ind % n]);
    ans.push(arr[e]);
    console.log(ans.join(" "));
  }
};
solve();

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 = Number.POSITIVE_INFINITY;

function main () {
	let t = rn();
	while (t--) {
		let n = rn();
		let h = rna();

		h.sort((x, y) => x - y);

		let k = 0;
		for (let i = 1; i < n - 1; i++) {
			if (h[i + 1] - h[i] < h[k + 1] - h[k])
				k = i;
		}

		ans = [h[k], ...h.slice(k + 2, n), ...h.slice(0, k), h[k + 1]];

		console.log(ans.join(' '));
	}
}

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 = Number.POSITIVE_INFINITY;

function main () {
	let t = rn();
	while (t--) {
		let n = rn();
		let h = rna();

		h.sort((x, y) => x - y);

		let dif = INF, idx;
		for (let i = 0; i < n - 1; i++) {
			if (h[i + 1] - h[i] < dif) {
				dif = h[i + 1] - h[i];
				idx = i;
			}
		}

		let i = idx;
		ans = [h[i], ...h.slice(i + 2, n), ...h.slice(0, i), h[i + 1]];

		console.log(ans.join(' '));
	}
}

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 n = +lines[l++]
        var arr = lines[l++].split(' ').map(Number)
        console.log(solve(n, arr));
    }
});

function solve(n, arr) {
    arr.sort((a, b) => a - b)

    let min = Infinity
    let p
    for (var i = 1; i < arr.length; i++) {
        const diff = arr[i] - arr[i - 1]
        if (i === 1 || diff < min) {
            min = diff
            p = i
        }
    }
    return [arr[p - 1]]
        .concat(arr.slice(p + 1))
        .concat(arr.slice(0, p - 1))
        .concat([arr[p]])
        .join(' ')
}

var matr = 'haha';

function create(str) {
   var hahaIndexArr = [];
   for (var i = 0; i < str.length; i++) {
      var hasWrong = false;
      for (var j = 0; j < matr.length; j++) {
         if (str[i + j] !== matr[j]) {
            hasWrong = true;
            break;
         }
      }
      if (!hasWrong) {
         hahaIndexArr.push(i);
      }
   }
   if (hahaIndexArr.length === 0) {
      if (str.length < 8) {
         return [str, -1, str];
      }
      return [str.substr(0, 4), 0, str.substr(str.length - 4, 0)];
   }
   var preff = str.substr(0, Math.min(4, hahaIndexArr[0])) || 'ha';
   var suff = str.substr(Math.max(hahaIndexArr[hahaIndexArr.length - 1] + 4, str.length - 4)) || 'ha';
   return [preff, hahaIndexArr.length, suff];
}
function summ(a, b) {
   var createMiddle = create(a[2] + b[0]);
   if (a[1] === -1 && b[1] === -1) {
      return createMiddle;
   }
   var preff = a[1] === -1 ? createMiddle[0] : a[0];
   var suff = b[1] === -1 ? createMiddle[2] : b[2];
   var asum = a[1] === -1 ? 0 : a[1];
   var bsum = b[1] === -1 ? 0 : b[1];
   var midSum = createMiddle[1] === -1 ? 0 : createMiddle[1];
   return [preff, asum + bsum + midSum, suff];
}

function solve() {
   var n = Number(read())
   var arr = readArray(Number);
   arr.sort(sortF);
   if (n === 2) {
      write(arr.join(' '));
      return;
   }
   var closest = 1;
   for (var i = 2; i < n; i++) {
      if (arr[i] - arr[i - 1] < arr[closest] - arr[closest - 1]) {
         closest = i;
      }
   }
   var ans = [];
   for (var i = closest; i < n; i++) {
      ans.push(arr[i]);
   }
   for (var i = 0; i < closest; i++) {
      ans.push(arr[i]);
   }
   write(ans.join(' '));
}

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

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

function readArray(mapF) {
   var res = read().split(' ');
   if (mapF) {
      res = res.map(mapF);
   }
   return res;
}

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

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }
   MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\r\n');
}
init();

function write(value) {
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   if (isNode) {
      return MEMORY;
   }
   var res = [];
   var x;
   while (x = read()) {
      res.push(x);
   }
   return res;
}

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++) {
        const n = parseInt(await getLine());
        const arr = (await getLine()).split(' ').map(n => parseInt(n));
        arr.sort();
        let mindiff = arr[arr.length - 1] - arr[0] + 2;
        for(let i = 1; i < arr.length; i++) {
            mindiff = Math.min(mindiff, arr[i] - arr[i-1]);
        }
        const printbest = function(pos) {
            rl.output.write(arr[pos + 1]+ '');
            for(let i = pos + 2; i<arr.length; i++) {
                rl.output.write(' ' + arr[i]);
            }
            for(let i = 0; i<=pos; i++)
                rl.output.write(' ' + arr[i]);
            rl.output.write('\n');
        }
        if (arr[1] - arr[0] === mindiff){
            if (arr.length === 2)
                rl.output.write(arr[0] + ' ' + arr[1]+'\n');
            else
                printbest(0);
        } else if (arr[arr.length - 1] - arr[arr.length - 2] === mindiff) {
            printbest(arr.length - 2);
        } else {
            for(let i = 1; i<arr.length; i++)
                if (arr[i] - arr[i-1] === mindiff){
                    printbest(i-1);
                    break;
                }
        }
    }
}

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++) {
        const n = parseInt(await getLine());
        const arr = (await getLine()).split(' ').map(n => parseInt(n));
        arr.sort();
        let mindiff = arr[arr.length - 1] - arr[0] + 2;
        for(let i = 1; i < arr.length; i++) {
            mindiff = Math.min(mindiff, arr[i] - arr[i-1]);
        }
        const printbest = function(pos) {
            rl.output.write(arr[pos + 1]+ '');
            for(let i = pos + 2; i<arr.length; i++) {
                rl.output.write(' ' + arr[i]);
            }
            for(let i = 0; i<=pos; i++)
                rl.output.write(' ' + arr[i]);
            rl.output.write('\n');
        }
        if (arr[1] - arr[0] === mindiff){
            if (arr.length === 2)
                console.log(arr[0] + ' ' + arr[1]);
            else
                printbest(0);
        } else if (arr[arr.length - 1] - arr[arr.length - 2] === mindiff) {
            printbest(arr.length - 2);
        } else {
            for(let i = 1; i<arr.length; i++)
                if (arr[i] - arr[i-1] === mindiff){
                    printbest(i-1);
                    break;
                }
        }
    }
}

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++) {
        const n = parseInt(await getLine());
        const arr = (await getLine()).split(' ').map(n => parseInt(n));
        arr.sort();
        let mindiff = arr[arr.length - 1] - arr[0] + 2;
        for(let i = 1; i < arr.length; i++) {
            mindiff = Math.min(mindiff, arr[i] - arr[i-1]);
        }
        const printbest = function(pos) {
            rl.output.write(arr[pos + 1]+ '');
            for(let i = pos + 2; i<arr.length; i++) {
                rl.output.write(' ' + arr[i]);
            }
            for(let i = 0; i<=pos; i++)
                rl.output.write(' ' + arr[i]);
            rl.output.write('\n');
        }
        if (arr[1] - arr[0] === mindiff){
            printbest(0);
        } else if (arr[arr.length - 1] - arr[arr.length - 2] === mindiff) {
            printbest(arr.length - 2);
        } else {
            for(let i = 1; i<arr.length; i++)
                if (arr[i] - arr[i-1] === mindiff){
                    printbest(i-1);
                    break;
                }
        }
    }
}

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 = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    arr.sort((a, b) => a - b);
    let obj = {},
      flag = true;
    for (let i = 0; i < n - 1; i++) {
      if (arr[i] === arr[i + 1]) {
        flag = false;
        obj[i] = i;
        obj[i + 1] = i + 1;
        break;
      }
    }
    if (flag) {
      obj[0] = 0;
      obj[1] = 1;
    }
    let [s, e] = Object.keys(obj);
    let ans = [];
    ans.push(arr[obj[s]]);
    let ind = obj[e] + 1;
    for (let i = 0; i < n - 2; i++, ind++) ans.push(arr[ind % n]);
    ans.push(arr[obj[e]]);
    console.log(ans.join(" "));
  }
};
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 n = +lines[l++]
        var arr = lines[l++].split(' ').map(Number)
        console.log(solve(n, arr));
    }
});

function solve(n, arr) {
    arr.sort((a, b) => a - b)

    let min = Infinity
    let p
    for (var i = 1; i < arr.length; i++) {
        const diff = arr[i] - arr[i - 1]
        if (i === 1 || diff < min) {
            min = diff
            p = i
        }
    }
    return [arr[p - 1]]
        .concat(arr.slice(p + 1))
        .concat(arr.slice(0, p - 1))
        .concat([arr[p]])
}


$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map.  The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.

NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.

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

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

		const aa = [], bb = [];
        for (let i = 0; i < n; i++) aa[i] = [a[i], i];
        for (let i = 0; i < n; i++) bb[i] = [b[i], i];

        aa.sort((x, y) => y[0] - x[0]);
        bb.sort((x, y) => y[0] - x[0]);

        q = new Set();
        for (let i = 0; i < n; i++) {
            q.add(aa[i][1]);
            q.add(bb[i][1]);
            if (q.size == i + 1) {
                break;
            }
        }

        const answer = Array(n).fill(0);
        for (let e of q) {
            answer[e] = '1';
        }

        console.log(answer.join(""));
	}
}


Valera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve.The camera's memory is d megabytes. Valera's camera can take photos of high and low quality. One low quality photo takes a megabytes of memory, one high quality photo take b megabytes of memory. For unknown reasons, each client asks him to make several low quality photos and several high quality photos. More formally, the i-th client asks to make xi low quality photos and yi high quality photos.Valera wants to serve as many clients per day as possible, provided that they will be pleased with his work. To please the i-th client, Valera needs to give him everything he wants, that is, to make xi low quality photos and yi high quality photos. To make one low quality photo, the camera must have at least a megabytes of free memory space. Similarly, to make one high quality photo, the camera must have at least b megabytes of free memory space. Initially the camera's memory is empty. Valera also does not delete photos from the camera so that the camera's memory gradually fills up.Calculate the maximum number of clients Valera can successfully serve and print the numbers of these clients.

The first line contains two integers n and d (1 ≤ n ≤ 105, 1 ≤ d ≤ 109) — the number of clients and the camera memory size, correspondingly. The second line contains two integers a and b (1 ≤ a ≤ b ≤ 104) — the size of one low quality photo and of one high quality photo, correspondingly.  Next n lines describe the clients. The i-th line contains two integers xi and yi (0 ≤ xi, yi ≤ 105) — the number of low quality photos and high quality photos the i-th client wants, correspondingly.  All numbers on all lines are separated by single spaces.

On the first line print the answer to the problem — the maximum number of clients that Valera can successfully serve. Print on the second line the numbers of the client in any order. All numbers must be distinct. If there are multiple answers, print any of them. The clients are numbered starting with 1 in the order in which they are defined in the input data.

print(function(n, d, a, b) {

	var p = [];
	for (var i = 0; i < n; i++)
		p.push(readline().split(' ').reduce(function(x, y) {
			return [x * a + y * b, i];
		}));

	p.sort(function(a, b) {
		return a[0] - b[0];
	});

	var ans = [];
	for (var i = 0, sum = 0; i < n; i++) {
		sum += p[i][0];
		if (sum <= d) {
			ans.push(p[i][1] + 1);
		} else {
			break;
		}
	}

	return ans.length + '\n' + ans.join(' ');

}.apply(0, readline().split(' ').map(Number).concat(readline().split(' ').map(Number))));


The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$ — the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$) — the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints.

aeren
ari
arousal
around
ari
monogon
monogamy
monthly
kevinvu
kuroni
kurioni
korone
anton
loves
adhoc
problems

NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are:  Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$  Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$  Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$  Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$

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));
    let str = "a".repeat(50).split("");

    console.log(str.join(""));
    for (let i = 0; i < len; i++) {
      for (let j = arr[i]; j < 50; j++) {
        if (str[j] === "a") str[j] = "b";
        else str[j] = "a";
      }
      console.log(str.join(""));
    }
  }
}

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() {
    const t = Number(readLine())
    for (let _i = 0; _i < t; _i++) {
        const n = Number(readLine())
        const as = readLine().split(/\s/).map(Number)
        let previous = Array(as[0] + 1).fill('a')
        console.log(previous.join(''))
        for (let i = 0; i < n; i++) {
          let nextCharCode = previous[as[i]].charCodeAt(0) + 1
          if (nextCharCode > 122) {
            nextCharCode = 97
          }
          previous = [...previous.slice(0, as[i]), ...Array(i === n - 1 ? 1 : Math.max(0, as[i + 1] - as[i] + 1)).fill(String.fromCharCode(nextCharCode))]
          console.log(previous.join(''))
        }
    }
}

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));
    let charCode = 97;

    if (arr[0] === 0) {
      console.log(`${String.fromCharCode(charCode)}`.repeat(1));
      charCode = (charCode + 1) % 123;
    } else {
      console.log(`${String.fromCharCode(charCode)}`.repeat(arr[0]));
    }
    for (let i = 0; i < len - 1; i++) {
      let max = Math.max(arr[i], arr[i + 1]);
      max = max === 0 ? 1 : max;

      if (arr[i] === 0 && i > 0) {
        charCode = (charCode + 1) % 123;
        console.log(`${String.fromCharCode(charCode)}`.repeat(max));
      } else {
        console.log(`${String.fromCharCode(charCode)}`.repeat(max));
      }
    }
    if (arr[len - 1] === 0) {
      charCode = (charCode + 1) % 123;
      console.log(`${String.fromCharCode(charCode)}`.repeat(1));
    } else {
      console.log(`${String.fromCharCode(charCode)}`.repeat(arr[len - 1]));
    }
  }
}

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));
    let charCode = 97;

    if (arr[0] === 0) {
      console.log(`${String.fromCharCode(charCode)}`.repeat(1));
      charCode++;
      charCode = charCode > 123 ? 97 : charCode;
    } else {
      console.log(`${String.fromCharCode(charCode)}`.repeat(arr[0]));
    }
    for (let i = 0; i < len - 1; i++) {
      let max = Math.max(arr[i], arr[i + 1]);
      max = max === 0 ? 1 : max;

      if (arr[i] === 0 && i > 0) {
        charCode++;
        charCode = charCode > 123 ? 97 : charCode;
        console.log(`${String.fromCharCode(charCode)}`.repeat(max));
      } else {
        console.log(`${String.fromCharCode(charCode)}`.repeat(max));
      }
    }
    if (arr[len - 1] === 0) {
      charCode++;
      charCode = charCode > 123 ? 97 : charCode;
      console.log(`${String.fromCharCode(charCode)}`.repeat(1));
    } else {
      console.log(`${String.fromCharCode(charCode)}`.repeat(arr[len - 1]));
    }
  }
}

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() {
    const t = Number(readLine())
    for (let _i = 0; _i < t; _i++) {
        const n = Number(readLine())
        const as = readLine().split(/\s/).map(Number)
        let previous = Array(as[0] + 1).fill('a')
        console.log(previous.join(''))
        for (let i = 0; i < n; i++) {
          let nextCharCode = previous[as[i]].charCodeAt(0) + 1
          if (nextCharCode > 122) {
            nextCharCode = 97
          }
          previous = [...previous.slice(0, as[i]), ...Array(i === n - 1 ? 0 : Math.max(0, as[i + 1] - as[i] + 1)).fill(String.fromCharCode(nextCharCode))]
          console.log(previous.join(''))
        }
    }
}


A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, "abc", "ab", and "c" are substrings of the string "abc", while "ac" and "d" are not.Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string "aaa" is $$$6$$$ because all its substrings are palindromes, and the palindromic count of the string "abc" is $$$3$$$ because only its substrings of length $$$1$$$ are palindromes.You are given a string $$$s$$$. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the length of string $$$s$$$. The second line contains string $$$s$$$ that consists of exactly $$$n$$$ lowercase characters of Latin alphabet.

Print string $$$t$$$, which consists of the same set of characters (and each characters appears exactly the same number of times) as string $$$s$$$. Moreover, $$$t$$$ should have the maximum possible value of palindromic count among all such strings strings. If there are multiple such strings, print any of them.

NoteIn the first example, string "ololo" has $$$9$$$ palindromic substrings: "o", "l", "o", "l", "o", "olo", "lol", "olo", "ololo". Note, that even though some substrings coincide, they are counted as many times as they appear in the resulting string.In the second example, the palindromic count of string "abccbaghghghgdfd" is $$$29$$$.

readline();
var word = readline().split('').sort().join('');
print(word);

//var input = readline()
var t = Number(readline())

var str = readline()
var s = str.split('').sort().join('')
print(s)

    var n = parseInt(readline());
    var s = readline();
    print(s.split('').sort().join(''));


A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5, 1].This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2 = p. If there are several such q find any of them.

The first line contains integer n (1 ≤ n ≤ 106) — the number of elements in permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of permutation p.

If there is no permutation q such that q2 = p print the number "-1". If the answer exists print it. The only line should contain n different integers qi (1 ≤ qi ≤ n) — the elements of the permutation q. If there are several solutions print any of them.

!function(r){function __webpack_require__(t){if(e[t])return e[t].exports;var a=e[t]={exports:{},id:t,loaded:!1};return r[t].call(a.exports,a,a.exports,__webpack_require__),a.loaded=!0,a.exports}var e={};return __webpack_require__.m=r,__webpack_require__.c=e,__webpack_require__.p="",__webpack_require__(0)}([function(r,e,t){r.exports=t(1)},function(r,e){"use strict";function solve(r,e){function calculate(r,e){for(var t=[],a=[],n=0;r>n;n++)if(void 0===a[n]){var o=t.length;a[n]=o;var _=1,i=n,u=!0;t.push({});for(var s=0,c=n;r>s;s++){if(c=e[c]-1,u=!u,u&&(i=e[i]-1),void 0!==a[c]){t[o]=u?{l:_,s:n}:{l:_,s:n,h:i};break}++_,a[c]=o}}t.sort(function(r,e){return r.l-e.l});for(var l=[],s=0,f=t.length;f>s;s++){var p=t[s].l;if(0===p%2){if(!(f-1>s&&p===t[s+1].l))return-1;for(var n=0,v=t[s].s,d=t[s+1].s;p>n;n++){var b=e[v],k=e[d];l[v]=d+1,l[d]=b,v=b-1,d=k-1}s+=1}else{var v=t[s].s,d=t[s].h,q=(p-1)/2;l[d]=v+1;for(var n=0;q>n;n++){var b=e[v],k=e[d];l[v]=k,l[k-1]=b,v=b-1,d=k-1}}}return l}function resout(r){print(-1===r?"-1":r.join(" "))}var t=calculate(r,e);resout(t)}var t=parseInt(readline()),a=readline().split(" ").map(function(r){return parseInt(r)});solve(t,a)}]);