const processData = (lines) => {
  const num = +lines[0]
  const restLines = lines.slice(1)
  let mark = 1
  for (let i =0; i<num; i++){
    const n = +lines[mark]
    const cur = mark + 1
    mark = mark + n + 1
    let restPrincess = null
    let princeList = Array(n).fill(false)
    for (let j = 0; j<n; j++) {
      const pList = lines[cur+j].split(' ').slice(1).map(x => x-1)
      let choose = false
      for (const chosenPrince of pList) {
        if (!princeList[chosenPrince]) {
          princeList[chosenPrince] = true
          choose = true
          break
        }
      }
      if (!choose)
        restPrincess = j+1
    }
    const restPrince = princeList.findIndex(x => !x)
    if (restPrince>=0) {
      console.log('IMPROVE')
      console.log((restPrincess) + ' ' + (restPrince+1))
    } else {
      console.log('OPTIMAL')
    }
  }
}

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

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

let input = ''
let ptr = 0
process.stdin.on('data', (i) => {
  input += i
})

process.stdin.on('end', () => {
  input = input.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main()
})

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

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

function readInt() {
  return parseInt(input[ptr++])
}

function readString() {
  return input[ptr++]
}

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

function readInts() {
  return input[ptr++].split(' ').map(a => parseInt(a))
}

function main() {
  let t = readInt()
  while(t--) {
    const n = readInt()
    let ks = new Array(n)
    let d = {}
    let book = {}
    for(let i = 0; i < n; i++) {
      ks[i] = readInts()
    }
    for(let i = 0; i < n; i++) {
      let kD = ks[i]
      // wr(i + 1, kD)
      let s = 1
      let b = kD[0]
      for(let j = 1; j <= kD[0]; j++) {
        if(!book[kD[j]]) {
          // wr('b', b)
          // wr(book)
          book[kD[j]] = i + 1
          d[i + 1] = kD[j]
          break
        }
      }
    }
    // wr(d)
    // wr(book)
    let nD = -1
    let nK = -1
    for(let i = 1; i <= n; i++) {
      if(!d[i]) {
        nD = i
        break
      }
    }
    for(let i = 1; i <= n; i++) {
      if(!book[i]) {
        nK = i
        break
      }
    }
    if(nD !== -1) {
      wr('IMPROVE')
      wr(nD, nK)
    }
    else wr('OPTIMAL')
  }
}

var len = readline()

for (var i = 0;i < len;i ++) {
  var dnum = readline();
  var nomarry = 0
  var obj = {}
  for(var j = 0;j < dnum; j ++) {
    var arr = readline().split(' ')
    var nomarryflag = true
    for (var p = 1;p <= arr[0];p ++) {
      if (!obj[arr[p]]) {
        nomarryflag = false
        obj[arr[p]] = 1
        break
      }

    }
    if (nomarryflag == true) {
      nomarry = j + 1
    }
  }
  for (var q = 1;q <= dnum; q ++) {
    if (!obj[q] && nomarry != 0) {
      print('IMPROVE')
      print(nomarry + ' ' + q)
      break
    }
    if (q == dnum) {
      print('OPTIMAL')
    }
  }
}

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

let input = ''
let ptr = 0
process.stdin.on('data', (i) => {
  input += i
})

process.stdin.on('end', () => {
  input = input.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main()
})

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

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

function readInt() {
  return parseInt(input[ptr++])
}

function readString() {
  return input[ptr++]
}

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

function readInts() {
  return input[ptr++].split(' ').map(a => parseInt(a))
}

function main() {
  let t = readInt()
  while(t--) {
    const n = readInt()
    let ks = new Array(n)
    let d = {}
    let book = {}
    for(let i = 0; i < n; i++) {
      ks[i] = readInts()
    }
    for(let i = 0; i < n; i++) {
      let kD = ks[i]
      let s = 1
      let b = kD[0]
      while(s < b) {
        let m = Math.floor((s + b) / 2)
        if(!book[kD[m]]) {
          b = m
        }
        else {
          s = m + 1
        }
      }
      if(b !== 0 && !book[kD[b]]) {
        book[kD[b]] = true
        d[i + 1] = true
      }
    }
    // wr(d)
    // wr(book)
    let nD = -1
    let nK = -1
    for(let i = 1; i <= n; i++) {
      if(!d[i]) {
        nD = i
        break
      }
    }
    for(let i = 1; i <= n; i++) {
      if(!book[i]) {
        nK = i
        break
      }
    }
    if(nD !== -1) {
      wr('IMPROVE')
      wr(nD, nK)
    }
    else wr('OPTIMAL')
  }
}

const processData = (lines) => {
  const num = +lines[0]
  const restLines = lines.slice(1)
  let mark = 1
  for (let i =0; i<num; i++){
    const n = +lines[mark]
    const cur = mark + 1
    mark = mark + n + 1
    let restPrincess = null
    let princeList = Array(n).fill(false)
    let rest = n
    while(rest) {
      const pList = lines[cur+n-rest].split(' ').slice(1).map(x => x-1)
      for (const chosenPrince of pList) {
        if (!princeList[chosenPrince]) {
          princeList[chosenPrince] = true
          break
        }
        restPrincess = n-rest + 1
      }
      rest--
    }
    const restPrince = princeList.findIndex(x => !x)
    if (restPrince>=0) {
      console.log('IMPROVE')
      console.log((restPrincess || '1') + ' ' + (restPrince+1))
    } else {
      console.log('OPTIMAL')
    }
  }
}

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

var len = readline()

for (var i = 0;i < len;i ++) {
  var dnum = readline();
  var nomarry = 0
  var obj = {}
  for(var j = 0;j < dnum; j ++) {
    var arr = readline().split(' ')
    var nomarryflag = true
    for (var p = 1;p <= arr[0];p ++) {
      if (obj[arr[p]] == 0) {
        nomarryflag = false
        obj[arr[p]] = 1
        break
      }

    }
    if (nomarryflag == true) {
      nomarry = j + 1
    }
  }
  for (var q = 1;q <= dnum; q ++) {
    if (!obj[q] && nomarry != 0) {
      print('IMPROVE')
      print(nomarry + ' ' + q)
      break
    }
    if (q == dnum) {
      print('OPTIMAL')
    }
  }
}

var len = readline()
var obj = {}
for (var i = 0;i < len;i ++) {
  var dnum = readline();
  var nomarry = 0

  for(var j = 0;j < dnum; j ++) {
    var arr = readline().split(' ')
    var nomarryflag = true
    for (var p = 1;p < arr[0];p ++) {
      if (obj[arr[p]] == 0) {
        nomarryflag = false
      }
      obj[arr[p]] = 1
    }
    if (nomarryflag == true) {
      nomarry = j + 1
    }
  }
  for (var q = 0;q < dnum; q ++) {
    if (!obj[q] && nomarry != 0) {
      print('IMPROVE')
      print(nomarry + ' ' + q)
      break
    }
    if (q == dnum - 1) {
      print('OPTIMAL')
    }
  }
}

var len = readline()

for (var i = 0;i < len;i ++) {
  var dnum = readline();
  var nomarry = 0
  var obj = {}
  for(var j = 0;j < dnum; j ++) {
    var arr = readline().split(' ')
    var nomarryflag = true
    for (var p = 1;p < arr[0];p ++) {
      if (obj[arr[p]] == 0) {
        nomarryflag = false
      }
      obj[arr[p]] = 1
    }
    if (nomarryflag == true) {
      nomarry = j + 1
    }
  }
  for (var q = 0;q < dnum; q ++) {
    if (!obj[q] && nomarry != 0) {
      print('IMPROVE')
      print(nomarry + ' ' + q)
      break
    }
    if (q == dnum - 1) {
      print('OPTIMAL')
    }
  }
}

var len = readline()

for (var i = 0;i < len;i ++) {
  var dnum = readline();
  var nomarry = 0
  var obj = {}
  for(var j = 0;j < dnum; j ++) {
    var arr = readline().split(' ')
    var nomarryflag = true
    for (var p = 1;p < arr[0];p ++) {
      if (obj[arr[p]] == 0) {
        nomarryflag = false
        obj[arr[p]] = 1
        break
      }

    }
    if (nomarryflag == true) {
      nomarry = j + 1
    }
  }
  for (var q = 1;q <= dnum; q ++) {
    if (!obj[q] && nomarry != 0) {
      print('IMPROVE')
      print(nomarry + ' ' + q)
      break
    }
    if (q == dnum) {
      print('OPTIMAL')
    }
  }
}

var len = readline()

for (var i = 0;i < len;i ++) {
  var dnum = readline();
  var nomarry = 0
  var obj = {}
  for(var j = 0;j < dnum; j ++) {
    var arr = readline().split(' ')
    var nomarryflag = true
    for (var p = 1;p < arr[0];p ++) {
      if (obj[arr[p]] == 0) {
        nomarryflag = false
        obj[arr[p]] = 1
        break
      }

    }
    if (nomarryflag == true) {
      nomarry = j + 1
    }
  }
  for (var q = 0;q < dnum; q ++) {
    if (!obj[q] && nomarry != 0) {
      print('IMPROVE')
      print(nomarry + ' ' + q)
      break
    }
    if (q == dnum - 1) {
      print('OPTIMAL')
    }
  }
}


let input = '';
process.stdin.on('data', chunk => input += chunk);
process.stdin.on('end', () => {
  const {EOL} = require('os');
  const lines = input.split(EOL);
  const count = parseInt(lines.shift());
  for (let i = 1; i <= count; ++i) {
    const n = parseInt(lines.shift());
    const my = lines.shift().split(/\s+/).filter(x => x.match(/^\d+$/)).map(x => parseInt(x));
    const his = lines.shift().split(/\s+/).filter(x => x.match(/^\d+$/)).map(x => parseInt(x));
    console.log(solve(n, my, his));
  }
});

function solve(n, my, his) {
  my.sort((a, b) => b - a);
  his.sort((a, b) => b - a);
  let count = n - Math.floor(n / 4);
  let myScore = my.slice(0, count).reduce((acc, val) => acc + val);
  let hisScore = his.slice(0, count).reduce((acc, val) => acc + val);
  let idx = count - 1;
  for (let added = 0; ; ++added) {
    if (myScore >= hisScore) {
      return added;
    }
    let newSize = n + added + 1;
    let newCount = newSize - Math.floor(newSize / 4);
    myScore += 100;
    if (newCount === count) {
      if (idx >= 0) {
        myScore -= my[idx];
        --idx;
      } else {
        myScore -= 100;
      }
    } else { // newCount === count + 1
      if (count < n) {
        hisScore += his[count];
      }
    }
    count = newCount;
  }
}

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--) {
		let n = rn();
		let a = rna();
		let b = rna();

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

		k = Math.floor(n / 4) - 1;

		let asum = 0, bsum = 0;
		for (let i = k + 1; i < n; i++) {
			asum += a[i];
			bsum += b[i];
		}

		let stage = n;
		let i = j = k;
		while (asum < bsum) {
			stage++;
			if (stage % 4 == 0) {
				asum += 100 - a[++i];
			} else {
				asum += 100;
				if (j >= 0) bsum += b[j];
				--j;
			}
			//console.log('asm', asum, 'bsum', bsum, stage);
		}

		ans = stage - n;

		console.log(ans);
	}
}


"use strict";

let input = readline().split(' ').map(e => +e);
let R = input[0] - 1, C = input[1];

while ( R-- > 0 )
	readline(); //ignore

let walls = readline().split('.').filter(e => e != '').length;
write(walls);

var array = readline().split(' ').map(Number);
var r = array[0];
var c = array[1];
var quantity = 0;
for (var i = 0; i < r -1; i++){
    readline();
}
var string = readline();

var flag = false;
for (var i = 0; i < string.length; i++){
    if (string[i] === 'B' && flag === false){
        flag = true;
        quantity++;
    } else if (string[i] === '.' && flag === true) {
        flag = false;
    }
}

print(quantity);


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 MOD = 1e9 + 7;

function fast_pow(a, p)
{
	let res = 1;
	while (p) {
		if (p % 2 == 0) {
			a = Number(BigInt(a) * BigInt(a) % BigInt(MOD));
			p /= 2;
		} else {
			res = Number(BigInt(res) * BigInt(a)  % BigInt(MOD));
			p--;
		}
	}
	return res;
}

function mmi (n) {
	return fast_pow(n, MOD-2);
}

function fact (n) {
	let res = 1;
	for (let i = 1; i <= n; i++)
		res = Number(BigInt(res)*BigInt(i) % BigInt(MOD));
	return res;
}

function c(n, r) {
	return Number(BigInt(fact(n))
		* BigInt(mmi(fact(n-r))) % BigInt(MOD)
		* BigInt(mmi(fact(r))) % BigInt(MOD));
}

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

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

		let cntl = 0, cntr = 0;
		for (let i = 0; i < k; i++)
			cntl += a[i] == a[k-1];
		for (let i = k; i < n; i++)
			cntr += a[i] == a[k-1];

		const ans = c(cntl + cntr, cntl);

		console.log(ans);
	}
}

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

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

const MOD = 1000000007n;

function fast_pow(a, p)
{
	let res = 1n;
	while (p) {
		if (p % 2n == 0) {
			a = a * a % MOD;
			p /= 2n;
		} else {
			res = res * a % MOD;
			p--;
		}
	}
	return res;
}

function mmi (n) {
	return fast_pow(n, MOD - 2n);
}

function fact (n) {
	let res = 1n;
	for (let i = 1n; i <= n; i++)
		res = res * i % MOD;
	return res;
}

function c(n, r) {
	return fact(n) * mmi(fact(n-r)) % MOD * mmi(fact(r)) % MOD;
}

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

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

		let cntl = 0, cntr = 0;
		for (let i = 0; i < k; i++)
			cntl += a[i] == a[k-1];
		for (let i = k; i < n; i++)
			cntr += a[i] == a[k-1];

		const ans = c(cntl + cntr, cntl);

		console.log(ans.toString());
	}
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

// Make a Snippet for the code above this and then write your logic in main();
var mod = 1000000000n + 7n
var maxN = 1002

var binom = new Array(maxN)
binom[0] = new Array(maxN).fill(1n)
binom[1] = new Array(maxN).fill(1n)

for (var i = 2; i < maxN; i++){
    binom[i] = new Array(maxN).fill(1n)

    for (var j = 1; j < i; j++){
        binom[i][j] = (binom[i - 1][j - 1] + binom[i - 1][j]) % mod;
    }
}
// console.log(binom)
function main() {
    const x = readline();

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        // var n = parseInt(readline())
        // var x = new Array(n)
        var [n, k] = readline().split(' ').map((x, iii) => {
            return x
        })
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        a = a.sort((a, b) => b - a)

        var add = a[k - 1]
        var ii = k - 1
        var count = 0
        for (let i = 0; i < n; i++) {
            if (a[i] === a[k - 1]) count++
        }
        while (a[k - 1] === a[ii]) ii++

        // var number =
        //     console.log(ii - k, count)

        // console.log(binom[3][2].toString())
        console.log(binom[count][ii - k].toString())
        // var res = []
    })
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

// Make a Snippet for the code above this and then write your logic in main();
var mod = 1000000000n + 7n
var maxN = 10n

var iv = new Array(maxN + 1n).fill(0n)
iv[1] = 1n
for (let i = 2n; i <= maxN; i++) {
    iv[i] = (iv[i - 1n] * i) % mod
}
function main() {
    const x = readline();

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        // var n = parseInt(readline())
        // var x = new Array(n)
        var [n, k] = readline().split(' ').map((x, iii) => {
            return x
        })
        var a = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        a = a.sort((a, b) => b - a)

        var add = a[k - 1]
        var ii = k - 1
        while (a[k - 1] === a[ii]) ii++

        var number =
            // console.log(ii - k)
        console.log(iv[ii - k + 1].toString())
        // var res = []
    })
}

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 fact (n) {
	if (n <= 1) return 1;
	return n * fact(n-1);
}

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

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

		let cntl = 0, cntr = 0;
		for (let i = 0; i < k; i++)
			cntl += a[i] == a[k-1];
		for (let i = k; i < n; i++)
			cntr += a[i] == a[k-1];

		const ans = fact(cntl+cntr) / (fact(cntl) * fact(cntr));

		console.log(ans);
	}
}


const readNum = () => +readline();
const readStr = () => readline();
const readNumArr = () => readline().split(' ').map(item => +item);
const createEmptyArr = (number) => new Array(number).fill(0);

const n = readNum();

for(var i = 0; i < n; i++) {
  var k = readNum();
  var arr = readNumArr();
  for(var j = 1; j < k && arr[j - 1] < arr[j]; j++) {}
  var temp = [];
  var count = 0;
  if(j !== k) {
    if((arr[0]+arr[k-1])%2===0) arr[0] = arr[k-1];
               else arr[k-1] = arr[0];
               count++;
               temp.push([1,k]);
               for(var j=1;j<k-1;j++){
                    if((arr[0]+arr[j])%2===1) temp.push([1,j+1]);
                    else temp.push([j+1,k]);
                    count++;
               }
  }
  print(count);
  for(var j = 0; j < temp.length; j++) {
    print(temp[j][0], temp[j][1]);
  }
}

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

const N = 100010;
const a = new Array(N);
      new Array(N);
function solve(read) {
  const rn = () => Number(read());
  const n = rn();
  let flag = true;
  for (let i = 0; i < n; i++) {
    a[i] = rn();
    if (i && a[i] < a[i - 1]) flag = false;
  }
  if (flag) return 0;
  let res = [];
  if (a[0] & 1) {
    const odd = [],
          even = [];
    let last = 0;
    for (let i = 0; i < n; i++) {
      if (a[i] & 1) {
        odd.push(i);
        last = i;
      } else even.push(i);
    }
    for (let i of odd) {
      if (i !== last) res.push([i, last]);
    }
    for (let i of even) {
      res.push([0, i]);
    }
  } else {
    const odd = [],
          even = [];
    let last = 0;
    for (let i = 0; i < n; i++) {
      if (a[i] & 1) {
        odd.push(i);
      } else {
        even.push(i);
        last = i;
      }
    }
    for (let i of even) {
      if (i !== last) res.push([i, last]);
    }
    for (let i of odd) {
      res.push([0, i]);
    }
  }
  return `${res.length}\n${res.map(([x, y]) => `${x + 1} ${y + 1}`).join('\n')}`;
}

function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      res[i] = s;
    }
    return res.join('\n');
    if (t >= 100) {
      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);
}();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
     let t = parseInt(readline());
     while(t--){
          let n = parseInt(readline());
          let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
          let count = 0,res = [];
          if(n===1){
               console.log(0);
               continue;
          }
          else{
               if((arr[0]+arr[n-1])%2==0) arr[0] = arr[n-1];
               else arr[n-1] = arr[0];
               count++;
               res.push([1,n]);
               for(let i=1;i<n-1;i++){
                    if((arr[0]+arr[i])%2===1) res.push([1,i+1]);
                    else res.push([i+1,n]);
                    count++;
               }
               console.log(count);
               for(let i=0;i<res.length;i++) console.log(res[i].join(" "));
          }
     }
};
solve();

const readNum = () => +readline();
const readStr = () => readline();
const readNumArr = () => readline().split(' ').map(item => +item);
const createEmptyArr = (number) => new Array(number).fill(0);

const n = readNum();

for(var i = 0; i < n; i++) {
  var k = readNum();
  var arr = readNumArr();
  for(var j = 1; j < k && arr[j - 1] < arr[j]; j++) {}
  var temp = [];
  var count = 0;
  if(j !== k) {
    if((arr[0]+arr[n-1])%2==0) arr[0] = arr[n-1];
               else arr[n-1] = arr[0];
               count++;
               temp.push([1,k]);
    for(var j = 1; j < k - 1; j++) {
        if((arr[0] + arr[j]) % 2 > 0) {
          temp.push([1, j + 1]);
        } else {
          temp.push([j + 1, k]);
        }
        count++;
      }
  }
  print(count);
  for(var j = 0; j < temp.length; j++) {
    print(temp[j][0], temp[j][1]);
  }
}

const readNum = () => +readline();
const readStr = () => readline();
const readNumArr = () => readline().split(' ').map(item => +item);
const createEmptyArr = (number) => new Array(number).fill(0);

const n = readNum();

for(var i = 0; i < n; i++) {
  var k = readNum();
  var arr = readNumArr();
  for(var j = 1; j < k && arr[j - 1] < arr[j]; j++) {}
  var temp = [];
  var count = 0;
  if(j !== k) {
    for(var j = 1; j < k - 1; j++) {
        if((arr[0] + arr[j]) % 2 > 0) {
          temp.push([1, j + 1]);
        } else {
          temp.push([j + 1, k]);
        }
        count++;
      }
  }
  print(count);
  for(var j = 0; j < temp.length; j++) {
    print(temp[j][0], temp[j][1]);
  }
}

const readNum = () => +readline();
const readStr = () => readline();
const readNumArr = () => readline().split(' ').map(item => +item);
const createEmptyArr = (number) => new Array(number).fill(0);

const n = readNum();

for(var i = 0; i < n; i++) {
  var k = readNum();
  var arr = readNumArr();
  for(var j = 1; j < k && arr[j - 1] < arr[j]; j++) {}
  var temp = [];
  var count = 0;
  if(j !== k) {
    for(var j = 0; j < k - 1; j++) {
        if((arr[j] + arr[j + 1]) % 2 > 0) {
          arr[j + 1] = arr[j];
          count++;
          temp.push([j, j + 1]);
        }
      }
  }
  print(count);
  for(var j = 0; j < temp.length; j++) {
    print(temp[j][0] + 1, temp[j][1] + 1);
  }
}

const readNum = () => +readline();
const readStr = () => readline();
const readNumArr = () => readline().split(' ').map(item => +item);
const createEmptyArr = (number) => new Array(number).fill(0);

const n = readNum();

for(var i = 0; i < n; i++) {
  var k = readNum();
  var arr = readNumArr();
  for(var j = 1; j < k && arr[j - 1] < arr[j]; j++) {}
  var temp = [];
  var count = 0;
  if(j !== k) {
    for(var j = 0; j < k - 1; j++) {
        if((arr[j] + arr[j + 1]) % 2 > 0) {
          arr[j + 1] = arr[j];
          count++;
          temp.push([j, j + 1]);
        }
      }
      print(arr);
  }
  print(count);
  for(var j = 0; j < temp.length; j++) {
    print(temp[j][0] + 1, temp[j][1] + 1);
  }
}

const readNum = () => +readline();
const readNumArr = () => readline().split(' ').map(item => +item);

const n = readNum();

for(var i = 0; i < n; i++) {
  var k = readNum();
  var arr = readNumArr();
  for(var j = 1; j < k && arr[j - 1] < arr[j]; j++) {}
  var temp = [];
  var count = 0;
  if(j !== k) {
    for(var j = 0; j < k - 1; j++) {
      for(var jj = j + 1; jj < k; jj++) {
        if(arr[jj - 1] > arr[jj]) {
          break;
        }
        if((arr[j] + arr[jj]) % 2 > 0) {
          arr[jj] = arr[j];
          count++;
          temp.push([j, jj]);
        }
      }
    }
  }
  print(count);
  for(var j = 0; j < temp.length; j++) {
    print(temp[j][0], temp[j][1]);
  }
}

const readNum = () => +readline();
const readStr = () => readline();
const readNumArr = () => readline().split(' ').map(item => +item);
const createEmptyArr = (number) => new Array(number).fill(0);

const n = readNum();

for(var i = 0; i < n; i++) {
  var k = readNum();
  var arr = readNumArr();
  var temp = [];
  var count = 0;
  for(var j = 0; j < k - 1; j++) {
    for(var jj = j + 1; jj < k; jj++) {
      if(arr[jj - 1] > arr[jj]) {
        break;
      }
      if((arr[j] + arr[jj]) % 2 > 0) {
        arr[jj] = arr[j];
        count++;
        temp.push([j, jj]);
      }
    }
  }
  print(count);
  for(var j = 0; j < temp.length; j++) {
    print(temp[j][0], temp[j][1]);
  }
}

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

const N = 100010;
const a = new Array(N),
      even = new Array(N),
      odd = new Array(N);
function solve(read) {
  const rn = () => Number(read());
  const n = rn();
  let flag = true;
  for (let i = 0; i < n; i++) {
    a[i] = rn();
    if (i && a[i] < a[i - 1]) flag = false;
  }
  if (flag) return 0;
  let res = [];
  if (a[0] & 1) {
    let last = 0,
        ido = 0,
        ide = 0;
    for (let i = 0; i < n; i++) {
      if (a[i] & 1) {
        odd[ido++] = i;
        last = i;
      } else even[ide++] = i;
    }
    for (let i = 0; i < ido; i++) {
      const j = odd[i];
      if (j !== last && a[j] !== a[last]) res.push(`${j + 1} ${last + 1}`);
    }
    for (let i = 0; i < ide; i++) {
      const j = even[i];
      res.push(`${1} ${j + 1}`);
    }
  } else {
    let p = 0;
    for (let i = 1; i < n; i++) {
      even[i] = p;
      if (a[i] % 2 === 0) p = i;
    }
    for (let i = n - 1; i > 0; i--) {
      if (a[i] & 1) {
        res.push(`${even[i] + 1} ${i + 1}`);
      } else {
        if (a[even[i]] > a[i]) res.push(`${even[i] + 1} ${i + 1}`);
      }
    }
  }
  return `${res.length}\n${res.join('\n')}`;
}

function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      res[i] = s;
    }
    return res.join('\n');
    if (t >= 100) {
      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);
}();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
     let t = parseInt(readline());
     while(t--){
          let n = parseInt(readline());
          let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
          let count = 0,res = [];
          if(n===1){
               console.log(0);
               continue;
          }
          else{
               if((arr[0]+arr[n-1])%2==0) arr[0] = arr[n-1];
               else arr[n-1] = arr[0];
               count++;
               res.push([1,n]);
               for(let i=1;i<n-1;i++){
                    if((arr[0]+arr[i])%2===1) res.push([1,i+1]);
                    else res.push([i+1,n-1]);
                    count++;
               }
               console.log(count);
               for(let i=0;i<res.length;i++) console.log(res[i].join(" "));
          }
     }
};
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));
          let count = 0,res = [];
          if(n===1){
               console.log(0);
               continue;
          }
          while(true){
               for(let i=0;i<n-1;i++){
                    if(arr[i]>arr[i+1]){
                         if((arr[i]+arr[i+1])%2===0) arr[i] = arr[i+1]
                         else arr[i+1] = arr[i];
                         count++;
                         res.push([i+1,i+2]);
                    }
               }
               let flag = 0;
               for(let i=0;i<n-1;i++){
                    if(arr[i]>arr[i+1]){
                         flag = 1;
                         break;
                    }
               }
               if(flag===0){
                    console.log(count);
                    if(count!==0){
                         for(let i=0;i<res.length;i++) console.log(res[i].join(" "));
                    }
                    break;
               }
               for(let i=n-1;i>=1;i--){
                    if(arr[i-1]>arr[i]){
                         if((arr[i-1]+arr[i])%2==0) arr[i-1] = arr[i];
                         else arr[i] = arr[i-1];
                         count++;
                         res.push([i,i+1]);
                    }
               }
          }
     }
};
solve();


process.stdin.resume();
process.stdin.setEncoding('utf8');
let standardInputString = '';
let curLine = 0;

const readLine = () => {
  return standardInputString[curLine++];
};

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

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

  main();
});

/**
 *
 */
// https://codeforces.com/contest/1566/problem/D1

// Return right boundary.
const binSearchR = (num, arr) => {
    let l = -1;
    let r = arr.length;

    while (r - l > 1) {
        const mid = Math.floor(
            (r + l) / 2,
        );

        if (arr[mid] > num) {
            r = mid;
        } else {
            l = mid;
        }
    }

    return r;
};

const main = () => {
    const t = +readLine();

    for (let testCaseIx = 0; testCaseIx < t; testCaseIx += 1) {
        const [, m] = readLine()
            .split(' ')
            .map(item => +item);

        const eyeLvlsInOrder = readLine()
            .split(' ')
            .map(eyeLvl => +eyeLvl);
        const peoplePos = eyeLvlsInOrder
            .slice()
            .sort(
                (a, b) => a - b,
            );

        const wasEyeLvl = new Map();

        const inconvIfSitTo = {};

        let inconvenience = 0;
        for (const eyeLvl of eyeLvlsInOrder) {
            let pos = binSearchR(eyeLvl, peoplePos) - 1;

            const wasEyeLvlOld = wasEyeLvl.get(eyeLvl) || 0;
            pos -= wasEyeLvlOld;
            wasEyeLvl.set(eyeLvl, wasEyeLvlOld + 1);

            const inconvIfSitToOld = inconvIfSitTo[pos] || 0;
            inconvenience += inconvIfSitToOld;

            while (pos < 300) {
                inconvIfSitTo[pos] = (inconvIfSitTo[pos] || 0) + 1;

                pos += 1;
            }
        }

        console.log(inconvenience);
    }
};

"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 [m, n] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let cnt = 0;
    for (let i = 0; i < n; i++) {
      for (let j = 0; j < i; j++) {
        if (arr[j] < arr[i]) cnt++;
      }
    }
    console.log(cnt);
  }
};
solve();


var main=function(){

    var first_line = readline().split(' ').map(Number);

    var n = parseInt(first_line[0]);
    var d = parseInt(first_line[1]);

    var x = readline().split(' ').map(Number);
    var cnt = 2;
    for (var i=0; i<x.length-1; i++){
    	if(x[i]+d <= x[i+1]-d){
    		cnt++;
    		var csr = x[i]+d;
    		if(csr<x[i+1]-d){
    			cnt++;
    		}
    	}
    }

    print(cnt);

};

/// IO ///
if(typeof process!=='undefined'){
	//node.js
	var print=function(x){
		console.log(x);
	}
	var readline=(function(){
		var T=[],cnt=0;
		var stdin = process.openStdin();
		stdin.setEncoding('utf8');

		var input_fragment="";
		stdin.on('data', function(input) {
			var ref=(input_fragment+input).split("\n");
			input_fragment=ref.pop();
			for(var i=0;i<ref.length;i++){
				if(ref[i]=='')continue;
				T.push(ref[i]);
			}
		});
		stdin.on('end', function(z) {
			if(input_fragment){
				var ref=(input_fragment+"\n").split("\n");
				input_fragment=ref.pop();
				for(var i=0;i<ref.length;i++){
					if(ref[i]=='')continue;
					T.push(ref[i]);
				}
			}
			main();
		});

		return function(){
			if(T.length<=cnt)return null;
			return T[cnt++];
		};
	})();
}else{
	//v8
	main();
}

var a = [];
var io;
var ans,n,d;
io = readline().split(" ").map(function(x) { return parseInt(x); });
n = io[0]; d = io[1]*2;
io = readline().split(" ").map(function(x) { return parseInt(x); });
a = io;
ans = 0;
for (var i=0;i<n-1;i++){
    if (Math.abs(a[i]-a[i+1])>d){
        ans+=2;
    } else
    if (Math.abs(a[i]-a[i+1])==d){
        ans++;
    }
}
ans+=2;
print(ans);

var l = readline().split(' ').map(v => parseInt(v, 10));
var n = l[0];
var d = l[1];
var a = readline().split(' ').map(v => parseInt(v, 10));

var ans = 2;

for (var i = 0; i < n - 1; i ++) {
    var q = a[i + 1] - a[i];
    if (q > 2 * d) {
        ans+=2;
    } else if (q === 2 * d) {
        ans++;
    }
}
print(ans);

const numbers = readline().split(' ').map(function(v){return +v;});
const n = numbers[0];
const b = numbers[1];
const arr = readline().split(' ').map(function(v){return +v;});

var count = 2;
var result = [arr[0]-b, arr[n-1]+b];

if(arr[0]+b+b<=arr[1]) result.push(arr[0]+b)
if(arr[n-1]-b-b>=arr[n-2]) result.push(arr[n-1]-b)

for (var i=1; i<n-1; i++) {
    if(arr[i]+b+b<=arr[i+1]) {
        result.push(arr[i]+b)
    }
    if(arr[i]-b-b>=arr[i-1]) {
        result.push(arr[i]-b)
    }
}

uniqueArray = result.filter(function(item, pos) {
    return result.indexOf(item) == pos;
})

print(uniqueArray.length);

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n')
  const in1 = arr.shift().split(' ')
  const a = arr.shift().split(' ')
  const n = parseInt(in1[0])
  const d = parseInt(in1[1])

  var c = 2
  for(let i = 1; i < n; i ++) {
    if((a[i] - a[i - 1]) > 2 * d){
      // console.log(a[i], a[i - 1])
      c += 2
    }
    else if((a[i] - a[i - 1]) == 2 * d) {
      c ++
    }
  }
  console.log(c)
})

const numbers = readline().split(' ').map(function(v){return +v;});
const n = numbers[0];
const b = numbers[1];
const arr = readline().split(' ').map(function(v){return +v;});

var count = 2;
var result = [arr[0]-b, arr[n-1]+b];

function first() {
    if(arr[0]+b+b<=arr[1]) result.push(arr[0]+b)
    if(arr[n-1]-b-b>=arr[n-2]) result.push(arr[n-1]-b)

    for (var i=1; i<n-1; i++) {
        if(arr[i]+b+b<=arr[i+1]) {
            result.push(arr[i]+b)
        }
        if(arr[i]-b-b>=arr[i-1]) {
            result.push(arr[i]-b)
        }
    }
}

first();

uniqueArray = result.filter(function(item, pos) {
    return result.indexOf(item) == pos;
})

print(uniqueArray.length);

var main=function(){
	var a=readline().split(' ').map(Number);
	print(a[0]+a[1]+' '+readline());
};

/// IO ///
if(typeof process!=='undefined'){
	//node.js
	var print=function(x){
		console.log(x);
	}
	var readline=(function(){
		var T=[],cnt=0;
		var stdin = process.openStdin();
		stdin.setEncoding('utf8');

		var input_fragment="";
		stdin.on('data', function(input) {
			var ref=(input_fragment+input).split("\n");
			input_fragment=ref.pop();
			for(var i=0;i<ref.length;i++){
				if(ref[i]=='')continue;
				T.push(ref[i]);
			}
		});
		stdin.on('end', function(z) {
			if(input_fragment){
				var ref=(input_fragment+"\n").split("\n");
				input_fragment=ref.pop();
				for(var i=0;i<ref.length;i++){
					if(ref[i]=='')continue;
					T.push(ref[i]);
				}
			}
			main();
		});

		return function(){
			if(T.length<=cnt)return null;
			return T[cnt++];
		};
	})();
}else{
	//v8
	main();
}

/**

function Main(input) {
    var data = input.split("\n");

    var first_line = data[0].split(" ");

    var n = parseInt(first_line[0]);
    var d = parseInt(fisrt_line[1]);

    var x = data[1].split(" ");
    var cnt = 2;
    for (var i=0; i<x.length-1; i++){
    	if(x[i]+d < x[i+1]-d){
    		var csr = x[i]+d;
    		while(csr<=x[i+1]-d){
    			cnt++;
    			csr++;
    		}
    	}
    }

    console.log(cnt);
    console.log("\n");
}

Main(require("fs").readFileSync("/dev/stdin").toString);
*/

function Main(input) {
    // inputにはすべての入力の文字列が与えられるので必要に応じて input.split("\n") などで分割する。

    var data = input.split("\n");

    var first_line = data[0].split(" ");

    var n = parseInt(first_line[0]);
    var d = parseInt(fisrt_line[1]);

    var x = data[1].split(" ");
    var cnt = 2;
    for (var i=0; i<x.length-1; i++){
    	if(x[i]+d < x[i+1]-d){
    		var csr = x[i]+d;
    		while(csr<=x[i+1]-d){
    			cnt++;
    			csr++;
    		}
    	}
    }

    console.log(cnt);
    console.log("\n");
}

var main=function(){

    var first_line = readline().split(' ').map(Number);

    var n = parseInt(first_line[0]);
    var d = parseInt(first_line[1]);

    var x = readline().split(' ').map(Number);
    var cnt = 2;
    for (var i=0; i<x.length-1; i++){
    	if(x[i]+d < x[i+1]-d){
    		var csr = x[i]+d;
    		while(csr<=x[i+1]-d){
    			cnt++;
    			csr++;
    		}
    	}
    }

    print(cnt);

};

/// IO ///
if(typeof process!=='undefined'){
	//node.js
	var print=function(x){
		console.log(x);
	}
	var readline=(function(){
		var T=[],cnt=0;
		var stdin = process.openStdin();
		stdin.setEncoding('utf8');

		var input_fragment="";
		stdin.on('data', function(input) {
			var ref=(input_fragment+input).split("\n");
			input_fragment=ref.pop();
			for(var i=0;i<ref.length;i++){
				if(ref[i]=='')continue;
				T.push(ref[i]);
			}
		});
		stdin.on('end', function(z) {
			if(input_fragment){
				var ref=(input_fragment+"\n").split("\n");
				input_fragment=ref.pop();
				for(var i=0;i<ref.length;i++){
					if(ref[i]=='')continue;
					T.push(ref[i]);
				}
			}
			main();
		});

		return function(){
			if(T.length<=cnt)return null;
			return T[cnt++];
		};
	})();
}else{
	//v8
	main();
}

const numbers = readline().split(' ').map(function(v){return +v;});
const n = numbers[0];
const b = numbers[1];
const arr = readline().split(' ').map(function(v){return +v;});

var count = 2;

if(arr[0]+b+3<arr[1]) count++
if(arr[n-1]-b-3>arr[n-2]) count++

for (var i=1; i<n-1; i++) {
    if(arr[i]+b+b<=arr[i+1]) {
        count++
    }
    if(arr[i]-b-b>=arr[i-1]) {
        count++
    }
}

print(count);

const numbers = readline().split(' ').map(function(v){return +v;});
const n = numbers[0];
const b = numbers[1];
const arr = readline().split(' ').map(function(v){return +v;});

var count = 2;

if(arr[0]+b+b<arr[1]) count++
if(arr[n-1]-b-b>arr[n-2]) count++

for (var i=1; i<n-1; i++) {
    if(arr[i]+b+b<=arr[i+1]) {
        count++
    }
    if(arr[i]-b-b>=arr[i-1]) {
        count++
    }
}

print(count);

const numbers = readline().split(' ').map(function(v){return +v;});
const n = numbers[0];
const b = numbers[1];
const arr = readline().split(' ').map(function(v){return +v;});

var count = 2;

if(arr[0]+b+b<=arr[1]) count++
if(arr[n-1]-b-b>=arr[n-2]) count++

for (var i=1; i<n-1; i++) {
    if(arr[i]+b+b<=arr[i+1]) {
        count++
    }
    if(arr[i]-b-b>=arr[i-1]) {
        count++
    }
}

print(count);


const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  let stairs = 1;
  let ans = [];

  for (let i = 1; i < arr.length; i++) {
    if (arr[i - 1] >= arr[i]) {
      stairs++;
      ans.push(arr[i - 1]);
    }
  }

  ans.push(arr[arr.length - 1]);

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

  c++;
});

function main() {
  const is = new Scanner();
  const n = is.nextInt();
  const numbers = is.nextArray().map(Number);
  numbers.push(0);
  const steps = [];
  let stairways = 0;
  for (let i = 0; i < n; i++)
    if (numbers[i] >= numbers[i + 1]) {
      stairways++;
      steps.push(numbers[i]);
    }

  console.log(stairways);
  console.log(steps.join(' '));
}

/*
 *  api stdin
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n');
  }

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

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', input => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
    // write code here:
    const n = Number(stdin[0]);
    var arr = stdin[1].split(' ').map(Number);
    var obj1 = {1: 0};
    var newArr = [];
    for (let i = 0; i < n; i++) {
        if (arr[i] === 1) {
            obj1[1]++;
            if (i !== 0) {
                newArr.push(arr[i - 1]);
            }
        }
    }
    newArr.push(arr[n - 1]);
    console.log(obj1[1] + '\n' + newArr.join(' '));
}

const readline = require('readline');
const rl = readline.createInterface({input: process.stdin});
var stdin = [];
rl.on('line', function (line) {
    stdin.push(line);
});
rl.on('close', main);

var firstLine = +readline();
var secondLine = readline().split(' ').map(function(v){return +v;});

var stairsCount = firstLine;
var strairs = secondLine;
var result = [];
var temp = 0;

for (var i = 1; i < stairsCount; i++) {
    if (strairs[i] === 1) {
        if (result.length > 0) {
            result.push(i - temp);
        } else {
            result.push(i);
        }
        temp = i;
    }
}

result.push(stairsCount - temp);

print(result.length);
print(result.join(' '));

//Don't have to see. start------------------------------------------
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↑入力 ↓出力');
  Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : 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){
  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';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//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 N = nextInt();
  var list = nextIntArray();
  var output = [0];
  for(var i = 0; i < N; i++){
    if(output[output.length - 1] < list[i]){
      output[output.length - 1] = list[i];
    }else{
      output.push(list[i]);
    }
  }
  myout(output.length);
  myout(myconv(output, 8));
}

var numbers = +readline();
var steps = readline().split(' ').map(Number);

if (numbers === 1) {
    print(1);
    print(1);
} else {
    var stepsStairway = [];
    for (var i = 1; i < numbers; i++) {
        if (steps[i] === 1) {
            stepsStairway.push(steps[i - 1]);
        }
    }

    stepsStairway.push(steps.pop());
    print(stepsStairway.length);
    print(stepsStairway.join(' '));
}

var n = readline();
var arr = readline().split(' ').map(Number);
var start = 0;
var count = 0;
var result = [];

for (var i=1; i<n; i++) {
    if (arr[i] <= arr[i-1]) {
        count++;
        result.push(i - start);
        start = i;
    }
}
count++;
result.push(n - start);
print(count);
print(result.join(" ")); //readline()

let input = [];

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

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

RL.on('close', () => {
    let flag = false, count = 0, answer = [], len = 0;
    let n = parseInt(input[0]);
    let num = []; input[1].split(' ').forEach(i => num.push(parseInt(i)));
    for (let i = 0; i < n; i++){
        len++;
        if(num[i] === 1 && !flag){
            flag = true;
        } else if(num[i] === 1 && flag) {
            answer.push(len-1);
            len = 1;
        }
    }
    answer.push(len);

    console.log(answer.length);
    let answer_string = ''; answer.forEach(i => answer_string+= `${i} `)
    console.log(answer_string);
});

/*
n = +readline();
a = readline().split(" ").map(Number);
var res = 0 , add = 0;
for (i = 0 ; i < n ; i ++){
    a[i] -= add;
    add += a[i];
    res += Math.abs(a[i]);

}

write(res);
*/
n = +readline();
a = readline().split(' ').map(Number);
var res = 0;
for (var i = 0 ; i < n ; i ++)
{
    if (a[i] == 1){
        res ++;
    }
}
write(res);
write("\n");
var lengthes = new Array(4);
var cur = 0;
for (var i = 0 ; i < n ; i ++)
{
    if (a[i] == 1){
        var j = i ;
        while (j < n && a[j] - a[i] == j - i){
            j ++;
        }
        lengthes[cur ] = j - i;
        i = j - 1;
        cur += 1;
    }
}
for (var i = 0 ; i < res ; i ++)
{
    write(lengthes[i]);
    write(" ");
}

const n = readline();
var arr = readline().split(' ').map(function(v){return +v;});

var start = 0;
var count = 0;
var result = [];

for (var i=1; i<n; i++) {
    if (arr[i] <= arr[i-1]) {
        count++;
        result.push(i - start);
        start = i;
    }
}
count++;
result.push(n - start);

print(count);
print(result.join(' '));

const process = require('process');

let inp = "";
process.stdin.on('data', chunk => inp += chunk);
process.stdin.on('end', () => {
    inp = inp.split('\n');
    const n = +inp[0];
    const a = inp[1].split(' ').map(s => +s);
    const ans = [];
    for (let i = 0; i < n; ++i) {
        if (i === n - 1 || a[i + 1] === 1)
            ans.push(a[i]);
    }
    console.log(ans.length);
    console.log(ans.join(' '));
});

var last = 1,
    floor = [];

var total = +readline();
if (total == 1) {
    write(1 + '\n' + 1);
} else {
    readline().split(' ').forEach((step, index) => {
        if( index ) {
        if(parseInt(step) == 1) floor.push(last);
        if( index == total - 1) floor.push(step)
        last = parseInt(step); }
    });
    write(floor.length + '\n' + floor.join(' '));
}

var n = +readline();
var a = readline().split(' ').map(Number);
var les = 0;
var j = -1;
var b = [];

for (var i=0; i<n; i++){
	if (a[i] == 1) {
		les++;
		j++;
		b[j] = 1;
	} else b[j]++;

}

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

var line1 = readline().split(" ").map(function (x) { return parseInt(x); });
var line2 = readline().split(" ").map(function (x) { return parseInt(x); });

var stairs = [];
var stairsIndex = -1;
for (index = 0; index < line2.length; index++) {
    var line_2number = line2[index];
    if (line_2number == "1") {
        stairs.push(1);
        stairsIndex++;
    } else {
        stairs[stairsIndex]++;
    }
}
print(stairs.length);
print(stairs.join(' '));

var g = readline();
var k = readline().split(" ");

var lens_arr = [1];

var len_count = 1;
for(i=1,b=0;i<k.length;i++){
    if(k[i]==1){
        len_count++;
        b++;
        lens_arr[b] = 1;
    }else{
            lens_arr[b]++;
    }
}
print(len_count);
print(lens_arr.join(" "));

n=+readline()
a=readline().split(' ').map(function(x){return +x;})
a.push(1)
res=''
m=0
for (i=0;i<n;i++)
{
    if (a[i+1]==1)
    {
        ++m
        res+=a[i]
        res+=' '
    }
}
print(m)
print(res)

var firstLine = +readline();
var secondLine = readline().split(' ').map(function(v){return +v;});

var stairsCount = firstLine;
var strairs = secondLine;
var result = [];
var temp = 0;

for (var i = 1; i < stairsCount; i++) {
    if (strairs[i] === 1) {
        if (result.length > 0) {
            result.push(i - temp);
        } else {
            result.push(i);
        }
        temp = i;
    }
}

result.push(stairsCount - temp);

print(result.length);
print(result);

var n = +readline();
var str = readline().split(' ').map(Number);
var res = 1;
var mas = [];
var temp = 0;
for (var i = 1; i < n; i++)
{
	temp++;
	if (str[i]==1)
	{
		res++;
		mas.push(temp);
		temp = 0;
	}
	else if (i+1==n)
		mas.push(temp+1);
	//else if (i==str.length[)
}
print(res);
print(mas.join(' '));

var n = +readline();
var str = readline().split(' ').map(Number);
var res = 1;
var mas = [];
var temp = 0;
for (var i = 1; i < n; i++)
{
	temp++;
	if (str[i]==1)
	{
		res++;
		mas.push(temp);
		temp = 0;
	}
	else if (i+1==n)
		mas.push(temp+1);
	//else if (i==str.length[)
}
print(res);
print(mas);

var last = 1,
    floor = [];

var total = +readline();
readline().split(' ').forEach((step, index) => {
    if( index ) {
    if(parseInt(step) == 1) floor.push(last);
    if( index == total - 1) floor.push(step)
    last = parseInt(step); }
});

write(floor.length + '\n' + floor.join(' '));

var last = 0,
    floor = [];

var total = +readline();
readline().split(' ').forEach((step, index) => {
    if( index ) {
    if(parseInt(step) == 1) floor.push(last);
    if( index == total - 1) floor.push(step)
    last = parseInt(step); }
});

write(floor.length + '\n' + floor.join(' '));

var numbers = readline().split(" ").map(function(x) { return parseInt(x); });
var numbers2 = readline().split(" ").map(function(x) { return parseInt(x); });
print(numbers);
print(numbers2);

var numbers = readline().split(" ").map(function(x) { return parseInt(x); });
print(numbers);


'use strict';

function solve(n, a) {
  const map = new Map();
  for (let num of a) {
    var _map$get;
    map.set(num, ((_map$get = map.get(num)) !== null && _map$get !== void 0 ? _map$get : 0) + 1);
  }
  for (let [i, count] of map) if (count & 1) return -1;
  let nums = [...a];
  const ops = [],
        res = [];
  for (let i = n - 1, j = n - 1; i >= 0; i = j) {
    j = i - 1;
    while (nums[j] !== nums[i]) {
      j--;
    }
    let t = j;
    while (i > t) {
      const num = nums[i];
      if (num !== nums[j]) {
        ops.push([j + 1, num]);
        nums.splice(j + 1, 0, num, num);
        i += 2;
        j += 2;
        t += 2;
      }
      i--;
      j--;
    }
    res.push((i - j) * 2);
  }
  res.reverse();
  let str = '';
  if (ops.length) {
    str += `${ops.length}\n${ops.map(arr => arr.join(' ')).join('\n')}`;
  } else {
    str += 0;
  }
  str += `\n${res.length}\n${res.join(' ')}`;
  return str;
}

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

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

let context = {}
context["throw"] = function(a) { throw a }
context["makeDict"] = function() { let ret = {}; for (let i = 0; i < arguments.length; i += 2) { ret[arguments[i]] = arguments[i + 1]; } return ret; }
context["dictKeys"] = function(dict) { return Object.keys(dict) }
context["parseInt"] = parseInt
context["nullCheck"] = function(a) { return a; }

function main(input) {
let lines = (input).split("\n");
let ret = "";
let line_ord = 0;
let nt = context.parseInt(lines[line_ord]);
line_ord = context.parseInt(line_ord+1);
for (let t = 0; t<nt; t = context.parseInt(t+1)) {
let n = context.parseInt(lines[line_ord]);
line_ord = context.parseInt(line_ord+1);
let tokens = (lines[line_ord]).split(" ");
line_ord = context.parseInt(line_ord+1);
let arr = [];
for (let i = 0; i<(tokens).length; i = context.parseInt(i+1)) {
(arr).push(context.parseInt(tokens[i]));

}
let offset = 0;
let ok = true;
let insertions = [];
let splits = [];
while ((arr).length>0&&ok) {
let idx = context.parseInt(0-1);
for (let i = 1; i<(arr).length; i = context.parseInt(i+1)) {
if (arr[i]==arr[0]) {
idx = i;
break;
}

}
if (idx==context.parseInt(0-1)) {
ok = false;
break;
}
let new_arr = [];
for (let j = 1; j<idx; j = context.parseInt(j+1)) {
(insertions).push([context.parseInt(context.parseInt(offset+idx)+j),arr[j]]);

}
for (let j = context.parseInt(idx-1); j>0; j = context.parseInt(j-1)) {
(new_arr).push(arr[j]);

}
for (let j = context.parseInt(idx+1); j<(arr).length; j = context.parseInt(j+1)) {
(new_arr).push(arr[j]);

}
(splits).push(context.parseInt(idx*2));
offset = context.parseInt(offset+context.parseInt(idx*2));
arr = new_arr;

}
if (!ok) {
ret = ret+"-1\n";
} else {ret = ret+("" + ((insertions).length))+"\n";
for (let i = 0; i<(insertions).length; i = context.parseInt(i+1)) {
ret = ret+("" + (insertions[i][0]))+" "+("" + (insertions[i][1]))+"\n";

}
ret = ret+("" + ((splits).length))+"\n";
for (let i = 0; i<(splits).length; i = context.parseInt(i+1)) {
ret = ret+("" + (splits[i]))+"\n";

}
}

}
return ret;
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8')
console.log(main(input));

'use strict';

function solve(n, a) {
  const map = new Map();
  for (let num of a) {
    var _map$get;
    map.set(num, ((_map$get = map.get(num)) !== null && _map$get !== void 0 ? _map$get : 0) + 1);
  }
  for (let [i, count] of map) if (count & 1) return -1;
  let nums = [...a];
  const ops = [],
        res = [];
  for (let i = 0, j = 0; i < n; i = j) {
    j = i + 1;
    while (nums[j] !== nums[i]) {
      j++;
    }
    let t = j;
    while (i < t) {
      const num = nums[i];
      if (num !== nums[j]) {
        ops.push([j, num]);
        nums.splice(j, 0, num, num);
      }
      i++;
      j++;
    }
    res.push((j - i) * 2);
  }
  let str = '';
  if (ops.length) {
    str += `${ops.length}\n${ops.map(arr => arr.join(' ')).join('\n')}`;
  } else {
    str += 0;
  }
  str += `\n${res.length}\n${res.join(' ')}`;
  return str;
}

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

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

let context = {}
context["throw"] = function(a) { throw a }
context["makeDict"] = function() { let ret = {}; for (let i = 0; i < arguments.length; i += 2) { ret[arguments[i]] = arguments[i + 1]; } return ret; }
context["dictKeys"] = function(dict) { return Object.keys(dict) }
context["parseInt"] = parseInt
context["nullCheck"] = function(a) { return a; }

function main(input) {
let lines = (input).split("\n");
let ret = "";
let line_ord = 0;
let nt = context.parseInt(lines[line_ord]);
line_ord = context.parseInt(line_ord+1);
for (let t = 0; t<nt; t = context.parseInt(t+1)) {
let n = context.parseInt(lines[line_ord]);
line_ord = context.parseInt(line_ord+1);
let tokens = (lines[line_ord]).split(" ");
line_ord = context.parseInt(line_ord+1);
let arr = [];
for (let i = 0; i<(tokens).length; i = context.parseInt(i+1)) {
(arr).push(context.parseInt(tokens[i]));

}
let offset = 0;
let ok = true;
let insertions = [];
let splits = [];
while ((arr).length>0&&ok) {
let idx = context.parseInt(0-1);
for (let i = 1; i<(arr).length; i = context.parseInt(i+1)) {
if (arr[i]==arr[0]) {
idx = i;
break;
}

}
if (idx==context.parseInt(0-1)) {
ok = false;
break;
}
let new_arr = [];
for (let j = 1; j<idx; j = context.parseInt(j+1)) {
(insertions).push([context.parseInt(context.parseInt(offset+context.parseInt(idx*2))-j),arr[j]]);

}
for (let j = context.parseInt(idx-1); j>0; j = context.parseInt(j-1)) {
(new_arr).push(arr[j]);

}
for (let j = context.parseInt(idx+1); j<(arr).length; j = context.parseInt(j+1)) {
(new_arr).push(arr[j]);

}
(splits).push(context.parseInt(idx*2));
offset = context.parseInt(offset+context.parseInt(idx*2));
arr = new_arr;

}
if (!ok) {
ret = ret+"-1\n";
} else {ret = ret+("" + ((insertions).length))+"\n";
for (let i = 0; i<(insertions).length; i = context.parseInt(i+1)) {
ret = ret+("" + (insertions[i][0]))+" "+("" + (insertions[i][1]))+"\n";

}
ret = ret+("" + ((splits).length))+"\n";
for (let i = 0; i<(splits).length; i = context.parseInt(i+1)) {
ret = ret+("" + (splits[i]))+"\n";

}
}

}
return ret;
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8')
console.log(main(input));

let context = {}
context["throw"] = function(a) { throw a }
context["makeDict"] = function() { let ret = {}; for (let i = 0; i < arguments.length; i += 2) { ret[arguments[i]] = arguments[i + 1]; } return ret; }
context["dictKeys"] = function(dict) { return Object.keys(dict) }
context["parseInt"] = parseInt
context["nullCheck"] = function(a) { return a; }

function main(input) {
let lines = (input).split("\n");
let ret = "";
let line_ord = 0;
let nt = context.parseInt(lines[line_ord]);
line_ord = context.parseInt(line_ord+1);
for (let t = 0; t<nt; t = context.parseInt(t+1)) {
let n = context.parseInt(lines[line_ord]);
line_ord = context.parseInt(line_ord+1);
let tokens = (lines[line_ord]).split(" ");
line_ord = context.parseInt(line_ord+1);
let arr = [];
for (let i = 0; i<(tokens).length; i = context.parseInt(i+1)) {
(arr).push(context.parseInt(tokens[i]));

}
let offset = 0;
let ok = true;
let insertions = [];
let splits = [];
while ((arr).length>0&&ok) {
let idx = context.parseInt(0-1);
for (let i = 1; i<(arr).length; i = context.parseInt(i+1)) {
if (arr[i]==arr[0]) {
idx = i;
break;
}

}
if (idx==context.parseInt(0-1)) {
ok = false;
break;
}
let new_arr = [];
for (let j = context.parseInt(idx-1); j>0; j = context.parseInt(j-1)) {
(insertions).push([context.parseInt(context.parseInt(offset+context.parseInt(idx*2))-j),arr[j]]);
(new_arr).push(arr[j]);

}
for (let j = context.parseInt(idx+1); j<(arr).length; j = context.parseInt(j+1)) {
(new_arr).push(arr[j]);

}
(splits).push(context.parseInt(idx*2));
offset = context.parseInt(offset+context.parseInt(idx*2));
arr = new_arr;

}
if (!ok) {
ret = ret+"-1\n";
} else {ret = ret+("" + ((insertions).length))+"\n";
for (let i = 0; i<(insertions).length; i = context.parseInt(i+1)) {
ret = ret+("" + (insertions[i][0]))+" "+("" + (insertions[i][1]))+"\n";

}
ret = ret+("" + ((splits).length))+"\n";
for (let i = 0; i<(splits).length; i = context.parseInt(i+1)) {
ret = ret+("" + (splits[i]))+"\n";

}
}

}
return ret;
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8')
console.log(main(input));


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

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i = 0; i< t; i++){
		let n = nl.num();
		let s = nl.nums().reduce((a, b) => a + b, 0);
		ans.push(s%n > 0?1:0);
	}
	console.log(ans.join('\n'));
};

process.stdin.on('end', sol);

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 sum = 0;
	        for(j = 0; j < n; j++){
	            sum += a[j];
	        }
	        var min = Math.floor(sum / n);
	        var max = Math.ceil(sum / n);
	        console.log(max - min);
	    }
	}
});

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 k = lines[i].split(' ').map(Number);
	        var sum = 0;
	        for(j = 0; j < n; j++){
	            sum += k[j];
	        }
	        var min = Math.floor(sum / n);
	        var max = Math.ceil(sum / n);
	        console.log(max - min);
	    }
	}
});

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

    for (let i = 2; i < lines.length; i+=2) {
        if (!lines[i]) continue;

        let sum = lines[i].split(' ').reduce((a, b) => parseInt(a) + parseInt(b), 0);

        console.log(sum % lines[i-1] ? 1 : 0)
    }
})

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

var maxN = 2 * 1e5 + 10
var mod = BigInt(1e9 + 7)

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

  // console.log(array)
  Array(Number(xx)).fill(1).map((t, i) => {
    const n = Number(readline());

    // var [a, k] = readline().split(' ').map((x, iii) => {
    //   return parseInt(x)
    // })
    var sum = 0
    var a = readline().split(' ').map((x, iii) => {
      sum+=Number(x)
      return Number(x)
    })
    // console.log(sum)
    if(sum %n ===0) return console.log(0)
    return console.log(1)
// console.log(a)
// console.log(n)
    // if(i===(string.length-2)) return console.log(string)
  })
}

var total = parseInt(readline());

for(var i=0; i<total; i++){
    var n = parseInt(readline());
    var height = readline().split(" ");
    var sums=0;
    var a = 0;
    while(a<height.length){
        sums += parseInt(height[a]);
        a++;
    }
    if (sums%n===0){
        print(0);
    }
    else{
        print(1);
    }
}


;(function () {
	print(function (a, b, n) {
		while (n-- > 0) {
			var flag = true;
			for (var i = 0; i < 10; i++) {
				if ((+(a + '' + i)%b) === 0) {
					a = +(a + '' + i);
					flag = false;

					if (i === 0) {
						a = a.toString();
						while (n-- > 0){
							a += '0';
						}
					}

					break;
				}
			}

			if (flag) return -1;
		}

		return a;
	}.apply(null, readline().split(' ').map(Number)));
}.call(this));

print(function(a, b, n) {

	var i, ans = [];

	n--;
	for (i = 0; i <= 9; i++)
		if ((a * 10 + i) % b === 0) {
			ans.push(a * 10 + i);
			break;
		}

	if (ans.length === 0)
		return -1;

	while (n--)
		ans.push(0);

	return ans.join('');

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

print(function(a, b, n) {

	var i, ans = [];

	n--;
	for (i = 0; i < 9; i++)
		if ((a * 10 + i) % b === 0) {
			ans.push(a * 10 + i);
			break;
		}

	if (ans.length === 0)
		return -1;

	while (n--)
		ans.push(0);

	return ans.join('');

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

;(function () {
	print(function (a, b, n) {
		while (n--) {
			if (a%10) {
				var flag = true;
				for (var i = 0; i < 10; i++) {
					if ((+(a + '' + i)%b) === 0) {
						a = +(a + '' + i);
						flag = false;
						break;
					}
				}

				if (flag) return -1;
			} else {
				n++;
				break;
			}
		}

		a = a.toString();
		while (n-- > 0) a += '0';

		return a;
	}.apply(null, readline().split(' ').map(Number)));
}.call(this));

;(function () {
	print(function (a, b, n) {
		while (n--) {
			var flag = true;
			for (var i = 0; i < 10; i++) {
				if ((+(a + '' + i)%b) === 0) {
					a = +(a + '' + i);
					flag = false;
					break;
				}
			}

			if (flag) return -1;
		}

		return a;
	}.apply(null, readline().split(' ').map(Number)));
}.call(this));

;(function () {
	print(function (a, b, n) {
		while (n--) {
			if (a%10) {
				var flag = true;
				for (var i = 0; i < 10; i++) {
					if ((+(a + '' + i)%b) === 0) {
						a = +(a + '' + i);
						flag = false;
						break;
					}
				}

				if (flag) return -1;
			} else break;
		}

		a = a.toString();
		while (n--) a += '0';

		return a;
	}.apply(null, readline().split(' ').map(Number)));
}.call(this));


function main()
{
    var n = parseInt(readline());
    var str = readline();
    if(str.length % n != 0){print(-1); return;}
    var mas = new Array(26);
    for(var i = 0; i < 26; ++i)
    {
        mas[i] = 0;
    }
    for(var i = 0; i < str.length; ++i)
    {
        mas[str.charCodeAt(i)-97] ++;
    }
    for(var i = 0; i < 26; ++i)
    {
        if(mas[i] != 0 && mas[i] % n != 0){print(-1); return;}
    }
    var new_str = "";
    for(var i = 0; i < n; ++i)
    {
        for(var j = 0; j < 26; ++j)
        {
            if(mas[j] != 0)
            {
                for(var h = mas[j] / n; h > 0; --h)
                {
                    new_str = new_str + String.fromCharCode(j + 97);
                }
            }
        }
    }
    print(new_str);
}
main();

var k=+readline();
var s={};
readline().split('').forEach(function(c){
	if( s[c] ){
		s[c]++;
	}else{
		s[c]=1;
	}
});
var f=false;
Object.keys(s).forEach(function(c){
	if( s[c]%k===0 ){
		s[c]=repeat(s[c]/k, c);
	}else{
		f=true;
	}
});
if(f){
	print(-1);
	quit();
}
s = Object.keys(s).map(function(c){return s[c];}).join('');
var ans='';
for(var i=0; i<k; i++){
	ans+=s;
}
print(ans);

function repeat(n, c){
	var ret = '';
	while(n--){
		ret+=c;
	}
	return ret;
}

;(function () {

	var k = +readline();
	var m = readline().split('').reduce(function (p, e) { p[e] = p[e] ? p[e] + 1 : 1; return p; }, {});

	var str = '';
	for(var key in m) {
		if (m[key] % k) {
			print(-1);
			return;
		} else {
			var l = m[key] / k;
			while (l--) str += key;
		}
	}

	var r = '';
	for (var i = 0; i < k; i++) r += str;
	print(r);

}).call(this)

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() {
  const n = +readLine();
  const str = readLine();
  const map = str.split("").reduce((obj, char) => {
    obj[char] = (obj[char] || 0) + 1;
    return obj;
  }, {});
  const keys = Object.keys(map);
  const imPossible = Object.values(map).some((val) => val % n !== 0);

  if (n === 1) {
    console.log(str);
  } else if (!imPossible) {
    let pattern = ``;
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      pattern += key.repeat(map[key] / n);
    }
    console.log(pattern.repeat(n));
  } else {
    console.log(-1);
  }
}

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], 10);
	};
	return tokens;
}

function main() {
	var k = parseInt(readline()),
		s = trim(readline()),
		n = s.length,
		letters = [],
		letterCount = {};
	for (var i = 0; i < n; ++i) {
		var ch = s.charAt(i);
		if (letterCount[ch] === undefined) {
			letters.push(ch);
			letterCount[ch] = 0;
		}
		letterCount[ch] += 1;
	}
	letters.sort();
	var word = [], result = [];
	for (var i = 0; i < letters.length; ++i) {
		var letter = letters[i], count = letterCount[letter];
		if (count % k != 0) {
			print(-1);
			return;
		}
		for (var j = count / k; j != 0; --j) {
			word.push(letter);
		}
	}
	word = word.join('');
	for (var i = 0; i < k; ++i) {
		result.push(word);
	}
	print(result.join(''));
}

main();

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

var dp = {};

function fibonacci(n) {
	if (n === 0) return 0;
	if (n === 1) return 1;

	if (dp[n] !== undefined) return dp[n];
	let result = fibonacci(n - 1) + fibonacci(n - 2);
	return (dp[n] = result);
}

function gcd(a, b) {
	if (b === 0) return a;
	return gcd(b, a % b);
}

function gcdArr() {
	let args = arguments;
	let res = args[0];
	let { length } = args;
	for (let i = 1; i < length; i++) {
		res = gcd(res, args[i]);
	}
	return res;
}

function main() {
	let k = readLine() >> 0;
	let s = readLine().split('');
	let store = {};
	s.forEach(ch => (store[ch] = (store[ch] || 0) + 1));
	let keys = Object.keys(store);
	let l = keys.length;
	let str = '';
	for (let i = 0; i < l; i++) {
		if (store[keys[i]] % k !== 0) {
			console.log(-1);
			return;
		}
		str += keys[i].repeat(store[keys[i]] / k);
	}
	console.log(str.repeat(k));
}

var n = +readline();
var s = readline().split('').sort();
s.push('0');
var k = 1;
var ans = [];
var anst = [];
for (var i=0; i<s.length-1; i++) {
	if (s[i] == s[i+1]) {
		k++;
	} else if (k%n == 0) {
		for (var j=0; j<k/n; j++) ans.push(s[i]);
		k = 1;
	} else {
		print(-1);
		k = -1;
		break;
	}
}
if (k != -1) {
	for (var j=0; j<n; j++) anst = anst.concat(ans);
	print (anst.join(''));
	}

//var input = "2\naaaa";
//var index = 0;
//
//function readline(){
//    var data = input.split('\n');
//    if(index < data.length)
//        return data[index++];
//}
//
//function print(output){
//    console.log(output);
//}

function test(arr, k){
    for(var i = 0; i < arr.length; i++){
        if(arr[i] % k !=0)
            return false;
    }
    return true;
}

function main(){
    var k = parseInt(readline());
    var str = readline();
    var a = new Array(26);
    for(var i = 0; i < a.length; i++)
        a[i] = 0;
    for(var i = 0; i < str.length; i++)
        a[str.charCodeAt(i) - 'a'.charCodeAt(0)]++;
    if(test(a, k)){
        var ans = "";
        var contact = "";
        for(var i = 0; i < a.length; i++)
            for(var j = 0; j < a[i] / k; j++)
                contact += String.fromCharCode(i + 'a'.charCodeAt(0));
        while(k > 0){
            ans += contact;
            k--;
        }
        print(ans);
    }else
        print(-1);
}
main();

;(function () {

	var k = +readline();
	var m = readline().split('').reduce(function (p, e) { p[e] = p[e] ? p[e] + 1 : 1; return p; }, {});

	var str = '';
	for(var key in m) {
		if (m[key] % k) {
			print(-1);
			return;
		} else {
			var l = m[key] / k;
			while (l--) str += key;
		}
	}

	for (var i = 0; i < k -1 ; i++) str += str;
	print(str);

}).call(this)

;(function () {

	var k = +readline();
	var m = readline().split('').reduce(function (p, e) { p[e] = p[e] ? p[e] + 1 : 1; return p; }, {});

	var str = '';
	for(var key in m) {
		if (m[key] % k) {
			print(-1);
			return;
		} else {
			var l = m[key] / k;
			while (l--) str += key;
		}
	}

	var r = '';
	for (var i = 0; i < k; i++) r += str;
	print(str);

}).call(this)

;(function () {

	var k = +readline();
	var m = readline().split('').reduce(function (p, e) { p[e] = p[e] ? p[e] + 1 : 1; return p; }, {});

	var str = '';
	for(var key in m) {
		if (m[key] % k) {
			print(-1);
			return;
		} else {
			var l = m[key] / k;
			while (l--) str += key;
		}
	}

	var r = '';
	for (var i = 0; i < k -1 ; i++) r += str;
	print(str);

}).call(this)

function main()
{
    var n = parseInt(readline());
    var str = readline();
    if(str.length % n != 0){print(-1); return;}
    var mas = new Array(26);
    for(var i = 0; i < 26; ++i)
    {
        mas[i] = 0;
    }
    for(var i = 0; i < str.length; ++i)
    {
        mas[str.charCodeAt(i)-97] ++;
    }
    var memory = -1;
    for(var i = 0; i < 26; ++i)
    {
        if(memory == -1 && mas[i] != 0){memory = mas[i];}
        if(mas[i] != 0 && mas[i] != memory){print(-1); return;}
    }
    var new_str = "", p = 0;
    for(var i = 0; i < memory; ++i)
    {
        for(var j = 0; j < 26; ++j)
        {
            if(mas[j] != 0)
            {
                new_str = new_str + String.fromCharCode(j + 97);
            }
        }
    }
    print(new_str);
}
main();

var n = +readline();
var s = readline().split('').sort();
var k = 1;
var ans = [];
var anst = [];
for (var i=0; i<s.length-1; i++) {
	if (s[i] == s[i+1]) {
		k++;
		if (i == s.length-2 && k%n == 0) {
			for (var j=0; j<k/n; j++) ans.push(s[i]);
		}
	} else if (k%n == 0) {
		for (var j=0; j<k/n; j++) ans.push(s[i]);
		k = 1;
	} else {
		print(-1);
		k = -1;
		break;
	}
}
if (k != -1) {
	if (k != s.length) {
		for (var j=0; j<n; j++) anst = anst.concat(ans);
		print (anst.join(''));
	}
	else if (k%n == 0) print (s.join(''));
	else print(-1);
}

//var input = "2\naaaa";
//var index = 0;
//
//function readline(){
//    var data = input.split('\n');
//    if(index < data.length)
//        return data[index++];
//}
//
//function print(output){
//    console.log(output);
//}

function test(arr, k){
    var n = k;
    for(var i = 0; i < arr.length; i++){
        if(arr[i] != 0)
            n--;
        if(arr[i] % k !=0)
            return false;
    }
    if(n == k - 1){
        for(var i = 0; i < arr.length; i++){
            if(arr[i] != 0 && arr[i] % k != 0)
                return false;
        }
    }else if(n != 0)
        return false;
    return true;
}

function main(){
    var k = parseInt(readline());
    var str = readline();
    var a = new Array(26);
    for(var i = 0; i < a.length; i++)
        a[i] = 0;
    for(var i = 0; i < str.length; i++)
        a[str.charCodeAt(i) - 'a'.charCodeAt(0)]++;
    if(test(a, k)){
        var n = k;
        var ans = "";
        while(k > 0){
            for(var i = 0; i < a.length; i++){
                if(a[i] != 0){
                    for(var j = 0; j < a[i] / n; j++)
                        ans += String.fromCharCode(i + 'a'.charCodeAt(0));
                }
            }
            k--;
        }
        print(ans);
    }else
        print(-1);
}
main();

//var input = "2\naazz";
//var index = 0;
//
//function readline(){
//    var data = input.split('\n');
//    if(index < data.length)
//        return data[index++];
//}
//
//function print(output){
//    console.log(output);
//}

function test(arr, k){
    var n = k;
    for(var i = 0; i < arr.length; i++){
        if(arr[i] != 0)
            n--;
        if(arr[i] % k !=0)
            return false;
    }
    if(n != 0)
        return false;
    return true;
}

function main(){
    var k = parseInt(readline());
    var str = readline();
    var a = new Array(26);
    for(var i = 0; i < a.length; i++)
        a[i] = 0;
    for(var i = 0; i < str.length; i++)
        a[str.charCodeAt(i) - 'a'.charCodeAt(0)]++;
    if(test(a, k)){
        var ans = "";
        while(k > 0){
            for(var i = 0; i < a.length; i++){
                if(a[i] != 0)
                    ans += String.fromCharCode(i + 'a'.charCodeAt(0));
            }
            k--;
        }
        print(ans);
    }else
        print(-1);
}
main();

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

var dp = {};

function fibonacci(n) {
	if (n === 0) return 0;
	if (n === 1) return 1;

	if (dp[n] !== undefined) return dp[n];
	let result = fibonacci(n - 1) + fibonacci(n - 2);
	return (dp[n] = result);
}

function gcd(a, b) {
	if (b === 0) return a;
	return gcd(b, a % b);
}

function gcdArr() {
	let args = arguments;
	let res = args[0];
	let { length } = args;
	for (let i = 1; i < length - 1; i++) {
		res = gcd(res, args[i]);
	}
	return res;
}

function main() {
	let k = readLine() >> 0;
	let s = readLine().split('');
	let store = {};
	if (s.length % k !== 0) {
		console.log(-1);
		return;
	}
	if (k === 1) {
		console.log(s.join(''));
		return;
	}

	s.forEach(ch => (store[ch] = (store[ch] || 0) + 1));
	let g = gcdArr(...Object.values(store));

	let str = '';
	if (g > 1) {
		Object.entries(store).forEach(([ch, cnt]) => {
			str += ch.repeat(cnt / g);
		});
		console.log(str.repeat(k));
	} else {
		console.log(-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++];
}

var dp = {};

function fibonacci(n) {
	if (n === 0) return 0;
	if (n === 1) return 1;

	if (dp[n] !== undefined) return dp[n];
	let result = fibonacci(n - 1) + fibonacci(n - 2);
	return (dp[n] = result);
}

function gcd(a, b) {
	if (b === 0) return a;
	return gcd(b, a % b);
}

function gcdArr() {
	let args = arguments;
	let res = args[0];
	let { length } = args;
	for (let i = 1; i < length; i++) {
		res = gcd(res, args[i]);
	}
	return res;
}

function main() {
	let k = readLine() >> 0;
	let s = readLine().split('');
	let store = {};
	if (s.length % k !== 0) {
		console.log(-1);
		return;
	}
	if (k === 1) {
		console.log(s.join(''));
		return;
	}

	s.forEach(ch => (store[ch] = (store[ch] || 0) + 1));

	if (Object.keys(store).length === 1) {
		console.log(s.join(''));
		return;
	}

	let g = gcdArr(...Object.values(store));

	let str = '';
	if (g > 1) {
		Object.entries(store).forEach(([ch, cnt]) => {
			str += ch.repeat(cnt / g);
		});
		console.log(str.repeat(k));
	} else {
		console.log(-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++];
}

var dp = {};

function fibonacci(n) {
	if (n === 0) return 0;
	if (n === 1) return 1;

	if (dp[n] !== undefined) return dp[n];
	let result = fibonacci(n - 1) + fibonacci(n - 2);
	return (dp[n] = result);
}

function gcd(a, b) {
	if (b === 0) return a;
	return gcd(b, a % b);
}

function gcdArr() {
	let args = arguments;
	let res = args[0];
	let { length } = args;
	for (let i = 1; i < length; i++) {
		res = gcd(res, args[i]);
	}
	return res;
}

function main() {
	let k = readLine() >> 0;
	let s = readLine().split('');
	let store = {};
	if (s.length % k !== 0) {
		console.log(-1);
		return;
	}
	if (k === 1) {
		console.log(s.join(''));
		return;
	}

	s.forEach(ch => (store[ch] = (store[ch] || 0) + 1));
	let g = gcdArr(...Object.values(store));

	let str = '';
	if (g > 1) {
		Object.entries(store).forEach(([ch, cnt]) => {
			str += ch.repeat(cnt / g);
		});
		console.log(str.repeat(k));
	} else {
		console.log(-1);
	}
}


function nextInt() { return parseInt(nextString()); }
function nextFloat() { return parseFloat(nextString()); }
let input_stdin = "";
let input_cursor = 0;
function nextString() {
    let next_string = "";
    clearWhitespaces();
    while (input_cursor < input_stdin.length && !isWhitespace(input_stdin[input_cursor]))next_string += input_stdin[input_cursor], input_cursor += 1;
    return next_string;
}
function nextChar() {
    clearWhitespaces();
    if (input_cursor < input_stdin.length) return input_stdin[input_cursor++]; else return '\0';
}
process.stdin.resume();
process.stdin.setEncoding('ascii');
process.stdin.on('data', function (data) { input_stdin += data; });
process.stdin.on('end', function () { main(); });
function isWhitespace(character) { return ' \t\n\r\v'.indexOf(character) > -1; }
function clearWhitespaces() { while (input_cursor < input_stdin.length && isWhitespace(input_stdin[input_cursor])) input_cursor += 1; }

const N = 2e5 + 2;
let fd = new Array(N);
let a = new Array(N);

function solve(){
    let n = nextInt();
    fd.fill(-1);
    for (let i = 0; i < n; i++)a[i] = nextInt();
    let an = N + 2, flg = false;
    for (let i = 0; i < n; i++){
        if (fd[a[i]] !== -1){
            an = Math.min(an, i - fd[a[i]] + 1);
            flg = true;
        }
        fd[a[i]] = i;
    }
    console.log(flg ? an : -1);
}

function main() {
    let t = nextInt();
    while(t--)solve();
}

function nextInt() { return parseInt(nextString()); }
function nextFloat() { return parseFloat(nextString()); }
let input_stdin = "";
let input_cursor = 0;
function nextString() {
    let next_string = "";
    clearWhitespaces();
    while (input_cursor < input_stdin.length && !isWhitespace(input_stdin[input_cursor])) {
        next_string += input_stdin[input_cursor];
        input_cursor += 1;
    }
    return next_string;
}
function nextChar() {
    clearWhitespaces();
    if (input_cursor < input_stdin.length) return input_stdin[input_cursor++]; else return '\0';
}
process.stdin.resume();
process.stdin.setEncoding('ascii');
process.stdin.on('data', function (data) { input_stdin += data; });
process.stdin.on('end', function () { main(); });
function isWhitespace(character) { return ' \t\n\r\v'.indexOf(character) > -1; }
function clearWhitespaces() { while (input_cursor < input_stdin.length && isWhitespace(input_stdin[input_cursor])) input_cursor += 1; }

const N = 2e5 + 2;
let frq = new Array(N);
let a = new Array(N);

function solve(){
    let n = nextInt();
    frq.fill(0);
    for (let i = 0; i < n; i++)a[i] = nextInt();
    if (n === 1){
        console.log(-1);
        return;
    }
    let l = 0, an = N + 2, flg = false;
    for (let r = 0; r < n; r++){
        frq[a[r]]++;
        while(frq[a[r]] > 1){
            flg = true;
            frq[a[l]]--;
            an = Math.min(an, r - l + 1);
            l++;
        }
    }
    console.log(flg ? an : -1);
}

function main() {
    let t = nextInt();
    while(t--)solve();
}

function nextInt() { return parseInt(nextString()); }
function nextFloat() { return parseFloat(nextString()); }
let input_stdin = "";
let input_cursor = 0;
function nextString() {
    let next_string = "";
    clearWhitespaces();
    while (input_cursor < input_stdin.length && !isWhitespace(input_stdin[input_cursor])) {
        next_string += input_stdin[input_cursor];
        input_cursor += 1;
    }
    return next_string;
}
function nextChar() {
    clearWhitespaces();
    if (input_cursor < input_stdin.length) return input_stdin[input_cursor++]; else return '\0';
}
process.stdin.resume();
process.stdin.setEncoding('ascii');
process.stdin.on('data', function (data) { input_stdin += data; });
process.stdin.on('end', function () { main(); });
function isWhitespace(character) { return ' \t\n\r\v'.indexOf(character) > -1; }
function clearWhitespaces() { while (input_cursor < input_stdin.length && isWhitespace(input_stdin[input_cursor])) input_cursor += 1; }

const N = 200000 + 2;
let frq = new Array(N);
let a = new Array(N);

function solve(){
    let n = nextInt();
    frq.fill(0);
    for (let i = 0; i < n; i++)a[i] = nextInt();
    if (n === 1){
        console.log(-1);
        return;
    }
    let l = 0, an = N + 2, flg = false;
    for (let r = 0; r < n; r++){
        frq[a[r]]++;
        while(frq[a[r]] > 1){
            flg = true;
            frq[a[l]]--;
            an = Math.min(an, r - l + 1);
            l++;
        }
    }
    console.log(flg ? an : -1);
}

function main() {
    let t = nextInt();
    while(t--)solve();
}

function nextInt() { return parseInt(nextString()); }
function nextFloat() { return parseFloat(nextString()); }
let input_stdin = "";
let input_cursor = 0;
function nextString() {
    let next_string = "";
    clearWhitespaces();
    while (input_cursor < input_stdin.length && !isWhitespace(input_stdin[input_cursor])) {
        next_string += input_stdin[input_cursor];
        input_cursor += 1;
    }
    return next_string;
}
function nextChar() {
    clearWhitespaces();
    if (input_cursor < input_stdin.length) return input_stdin[input_cursor++]; else return '\0';
}
process.stdin.resume();
process.stdin.setEncoding('ascii');
process.stdin.on('data', function (data) { input_stdin += data; });
process.stdin.on('end', function () { main(); });
function isWhitespace(character) { return ' \t\n\r\v'.indexOf(character) > -1; }
function clearWhitespaces() { while (input_cursor < input_stdin.length && isWhitespace(input_stdin[input_cursor])) input_cursor += 1; }

const N = 200000 + 2;
let frq = new Array(N);

function solve(){
    let n = nextInt();
    let a = new Array(n + 1);
    frq.fill(0);
    for (let i = 0; i < n; i++)a[i] = nextInt();
    if (n === 1){
        console.log(-1);
        return;
    }
    let l = 0, an = N + 2, flg = false;
    for (let r = 0; r < n; r++){
        frq[a[r]]++;
        while(frq[a[r]] > 1){
            flg = true;
            frq[a[l]]--;
            an = Math.min(an, r - l + 1);
            l++;
        }
    }
    console.log(flg ? an : -1);
}

function main() {
    let t = nextInt();
    while(t--)solve();
}

function nextInt() { return parseInt(nextString()); }
function nextFloat() { return parseFloat(nextString()); }
let input_stdin = "";
let input_cursor = 0;
function nextString() {
    let next_string = "";
    clearWhitespaces();
    while (input_cursor < input_stdin.length && !isWhitespace(input_stdin[input_cursor])) {
        next_string += input_stdin[input_cursor];
        input_cursor += 1;
    }
    return next_string;
}
function nextChar() {
    clearWhitespaces();
    if (input_cursor < input_stdin.length) return input_stdin[input_cursor++]; else return '\0';
}
process.stdin.resume();
process.stdin.setEncoding('ascii');
process.stdin.on('data', function (data) { input_stdin += data; });
process.stdin.on('end', function () { main(); });
function isWhitespace(character) { return ' \t\n\r\v'.indexOf(character) > -1; }
function clearWhitespaces() { while (input_cursor < input_stdin.length && isWhitespace(input_stdin[input_cursor])) input_cursor += 1; }

const N = 20002;

function solve(){
    let n = nextInt();
    let a = new Array(n + 1);
    let frq = new Array(N);
    frq.fill(0);
    for (let i = 0; i < n; i++)a[i] = nextInt();
    if (n === 1){
        console.log(-1);
        return;
    }
    let l = 0, an = N + 2;
    for (let r = 0; r < n; r++){
        frq[a[r]]++;
        while(frq[a[r]] > 1){
            frq[a[l]]--;
            an = Math.min(an, r - l + 1);
            l++;
        }
    }
    console.log(an);
}

function main() {
    let t = nextInt();
    while(t--)solve();
}

function nextInt() { return parseInt(nextString()); }
function nextFloat() { return parseFloat(nextString()); }
let input_stdin = "";
let input_cursor = 0;
function nextString() {
    let next_string = "";
    clearWhitespaces();
    while (input_cursor < input_stdin.length && !isWhitespace(input_stdin[input_cursor])) {
        next_string += input_stdin[input_cursor];
        input_cursor += 1;
    }
    return next_string;
}
function nextChar() {
    clearWhitespaces();
    if (input_cursor < input_stdin.length) return input_stdin[input_cursor++]; else return '\0';
}
process.stdin.resume();
process.stdin.setEncoding('ascii');
process.stdin.on('data', function (data) { input_stdin += data; });
process.stdin.on('end', function () { main(); });
function isWhitespace(character) { return ' \t\n\r\v'.indexOf(character) > -1; }
function clearWhitespaces() { while (input_cursor < input_stdin.length && isWhitespace(input_stdin[input_cursor])) input_cursor += 1; }

const N = 20002;

function solve(){
    let n = nextInt();
    let a = new Array(n + 1);
    let frq = new Array(N);
    frq.fill(0);
    for (let i = 0; i < n; i++)a[i] = nextInt();
    if (n === 1){
        console.log(n);
        return;
    }
    let l = 0, an = N + 2;
    for (let r = 0; r < n; r++){
        frq[a[r]]++;
        while(frq[a[r]] > 1){
            frq[a[l]]--;
            an = Math.min(an, r - l + 1);
            l++;
        }
    }
    console.log(an);
}

function main() {
    let t = nextInt();
    while(t--)solve();
}

function nextInt() { return parseInt(nextString()); }
function nextFloat() { return parseFloat(nextString()); }
let input_stdin = "";
let input_cursor = 0;
function nextString() {
    let next_string = "";
    clearWhitespaces();
    while (input_cursor < input_stdin.length && !isWhitespace(input_stdin[input_cursor])) {
        next_string += input_stdin[input_cursor];
        input_cursor += 1;
    }
    return next_string;
}
function nextChar() {
    clearWhitespaces();
    if (input_cursor < input_stdin.length) return input_stdin[input_cursor++]; else return '\0';
}
process.stdin.resume();
process.stdin.setEncoding('ascii');
process.stdin.on('data', function (data) { input_stdin += data; });
process.stdin.on('end', function () { main(); });
function isWhitespace(character) { return ' \t\n\r\v'.indexOf(character) > -1; }
function clearWhitespaces() { while (input_cursor < input_stdin.length && isWhitespace(input_stdin[input_cursor])) input_cursor += 1; }

const N = 20002;

function solve(){
    let n = nextInt();
    let a = new Array(n + 1);
    let frq = new Array(N);
    frq.fill(0);
    for (let i = 0; i < n; i++)a[i] = nextInt();
    if (n === 1){
        console.log(-1);
        return;
    }
    let l = 0, an = N + 2, flg = false;
    for (let r = 0; r < n; r++){
        frq[a[r]]++;
        while(frq[a[r]] > 1){
            flg = true;
            frq[a[l]]--;
            an = Math.min(an, r - l + 1);
            l++;
        }
    }
    console.log(flg ? an : -1);
}

function main() {
    let t = nextInt();
    while(t--)solve();
}