process.stdin.setEncoding('utf-8')
const readline = require('readline')

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

let count = -1
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data * 2
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        inputArr = inputArr.map(i => i.split(' ').map(j => +j))
        main()
        process.exit(0)
    }
})

function solve([n], arr) {
    let ans = 0, summ = 0
    for (let i = 0; i < n; ++i) {
        if (arr[i] > (i + 1 + summ)) {
            summ += (arr[i] - i - 1 - summ)
        }
    }
    console.log(summ)
}

function main() {
    for (let i = 0; i < inputArr.length; i += 2) solve(inputArr[i], inputArr[i + 1])
}

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 x = 0;
	        var ans = 0;
	        for(j = 0; j < n; j++){
	            if(a[j] > j + 1){
	                x = Math.abs((j + 1) - a[j]);
	                ans = Math.max(ans, x);
	            }
	        }
	        console.log(ans);
        }
    }
});

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 x = 0;
	        var ans = 0;
	        for(j = 0; j < n; j++){
	            if(k[j] > j + 1){
	                x = Math.abs((j + 1) - k[j]);
	                ans = Math.max(ans, x);
	            }
	        }
	        console.log(ans);
	    }
	}
});

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var output = 0;
		for(var i = 0; i < N; i++){
			output = Math.max(output, list[i] - (i + 1));
		}
		myout(output);
	}
}

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

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

// Codeforces Round #752 (Div. 2)

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

  for (let testCaseNum = 0; testCaseNum < t; testCaseNum += 1) {
    const n = +readLine();

    const sequence = readLine()
      .split(' ')
      .map(str => +str);

    let shift = 0;

    for (let numIx = 0; numIx < n; numIx += 1) {
      const num = sequence[numIx];

      const diff = num - numIx - shift - 1;

      shift += diff > 0 ? diff : 0;
    }

    console.log(shift);
  }
};

const readline = require('readline')

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

function solve(n, arr) {
    let cur = 0
    let ans = 0
    arr.forEach((x, i) => {
        cur++
        if (x > cur) {
            ans += x - cur
            cur += x - cur
        }
    })
    return ans
}

const numTestCases = parseInt(readline());
for (var i = 0; i < numTestCases; i++) {
    var initialLength = parseInt(readline());
    var sequence = readline().split(' ');
    var changes = 0;
    var an = 1;
    for (var j = 0; j < sequence.length; j++) {
        sequence[j] = parseInt(sequence[j]);
    }

    for (var t = 0; t < sequence.length; t++) {
        if (an < sequence[t]) {
            var changesNeeded = sequence[t] - an;
            an += changesNeeded;
            changes += changesNeeded;
        }
        an++;
    }

    print(changes);
}

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 x = 0;
	        var ans = 0;
	        for(j = 0; j < n; j++){
	            if(a[j] > j + 1){
	                x = Math.abs((j + 1) - a[j]);
	                ans = Math.max(ans, x);
	            }
	        }
	        console.log(ans);
        }
    }
});

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var index = 0;
		var max = 0;
		for(var i = 0; i < N; i++){
			if(max < list[i] && i + 1 < list[i]){
				max = list[i];
				index = i + 1;
			}
		}
		myout(Math.max(0, max - index));
	}
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var index = -1;
		var max = 0;
		for(var i = 0; i < N; i++){
			if(max < list[i]){
				max = list[i];
				index = i + 1;
			}
		}
		myout(Math.max(0, max - index));
	}
}


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

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

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

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

		//console.log({d})
		let ans = true, ssum = 0;
		for (let i = 0; i < 2*n; i += 2) {
			cur = (d[i]- 2*ssum) / (2*n-i);
			if (d[i] != d[i-1] && d[i] == d[i+1]  && cur > 0 && cur%1 == 0) ;
			else ans = false;
			//console.log({ssum, cur})
			ssum += cur;
		}

		console.log(ans ? 'YES' : 'NO');
	}
}

function solve(a){
    a.sort((x, y) => x-y);
    var d = [], sum = 0;
    for(var i = 0; i < a.length; i++){
        if(a[i] != a[i+1]) return 'NO';
        if(a[i] == a[i+2]) return 'NO';
        d.push(a[i]);
        i++;
    }
    for(var i = 2; i < d.length+1; i++){
        var dii1 = d[i-1]-d[i-2];
        var xi =  dii1 / (2*i-2);
        if(xi%1 != 0) return 'NO';
        else{
            sum += (d.length-i+1)*xi;
        }
    }
    if(d[0]-2*sum <= 0 || ((d[0]-2*sum)%(2*d.length))) return 'NO';
    return 'YES';
}

var a = [];
var t = Number(readline());
for (var i = 0; i<t;i++){
    var n = Number(readline());
    a = readline().split(' ').map((x) => Number(x));
    write(solve(a)+'\n');
}

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

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

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

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

		//console.log({d})
		let ans = true, ssum = 0;
		for (let i = 0; i < 2*n; i += 2) {
			cur = (d[i]- 2*ssum) / (2*n-i);
			if (d[i] != d[i+1] || cur == 0 || cur%1) ans = false;
			//console.log({ssum, cur})
			ssum += cur;
		}

		console.log(ans ? 'YES' : 'NO');
	}
}

function solve(a){
    a.sort((x, y) => x-y);
    var d = [], sum = 0;
    for(var i = 0; i < a.length; i++){
        if(a[i] != a[i+1]) return 'NO';
        d.push(a[i]);
        i++;
    }
    for(var i = 2; i < d.length+1; i++){
        var dii1 = d[i-1]-d[i-2];
        var xi =  dii1 / (2*i-2);
        if(xi%1 != 0) return 'NO';
        else{
            sum += (d.length-i+1)*xi;
        }
    }
    if(d[0]-2*sum <= 0 || ((d[0]-2*sum)%(2*d.length))) return 'NO';
    return 'YES';
}

var a = [];
var t = Number(readline());
for (var i = 0; i<t;i++){
    var n = Number(readline());
    a = readline().split(' ').map((x) => Number(x));
    write(solve(a)+'\n');
}


"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 flush() {
  process.stdout.clearLine();
  process.stdout.cursorTo(0);
}
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, m] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    n = (n << 1) - 1;
    let arr = [],
      ans = new Array(m).fill(0);
    for (let i = 0; i < n; i++) arr.push(readline().trim());
    for (let i = 0; i < m; i++) {
      for (let j = 0; j < n; j++) ans[i] ^= arr[j].charCodeAt(i);
    }
    let res = "";
    for (let i = 0; i < m; i++) res += String.fromCharCode(ans[i]);
    console.log(res);
  }
};
solve();

const aCharCode = 'a'.charCodeAt(0);
const zCharCode = 'z'.charCodeAt(0);

function solve() {
   const [n, m] = readArray(Number);
   const xxx = 'x'.repeat(zCharCode - aCharCode + 1).split('').map((x) => 0);
   const counter = 'x'.repeat(m).split('').map(() => xxx.slice(0));
   let str;
   for (let i = 0; i < n; i++) {
      str = read();
      for (let j = 0; j < m; j++) {
         counter[j][str.charCodeAt(j) - aCharCode]++;
      }
   }
   for (let i = 0; i < n - 1; i++) {
      str = read();
      for (let j = 0; j < m; j++) {
         counter[j][str.charCodeAt(j) - aCharCode]++;
      }
   }
   ans = '';
   for (let i = 0; i < m; i++) {
      for (let j = 0; j <= zCharCode - aCharCode; j++) {
         if (counter[i][j] & 1) {
            ans += String.fromCharCode(aCharCode + j);
            break;
         }
      }
   }
   write(ans);
}

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack.split('\n').join(' '));
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

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

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

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

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

"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, m] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr1 = [];
    for (let i = 0; i < n; i++) arr1.push(readline().trim().split(""));
    let arr2 = [];
    for (let i = 0; i < n - 1; i++) arr2.push(readline().trim().split(""));
    for (let i = 0; i < m; i++) {
      let obj = {};
      for (let j = 0; j < n - 1; j++) obj[arr2[j][i]] = 1;
      let flag = false,
        ind = -1;
      for (let j = 0; j < n; j++) {
        if (!obj[arr1[j][i]]) {
          flag = true;
          ind = j;
          break;
        }
      }
      if (flag) {
        console.log(arr1[ind].join(""));
        break;
      }
    }
  }
};
solve();

const aCharCode = 'a'.charCodeAt(0);
const zCharCode = 'z'.charCodeAt(0);

function solve() {
   const [n, m] = readArray(Number);
   const xxx = 'x'.repeat(zCharCode - aCharCode + 1).split('').map((x) => 0);
   const counter = 'x'.repeat(m).split('').map(() => xxx.slice(0));
   let str;
   for (let i = 0; i < n; i++) {
      str = read();
      for (let j = 0; j < m; j++) {
         counter[j][str.charCodeAt(j) - aCharCode]++;
      }
   }
   for (let i = 0; i < n - 1; i++) {
      str = read();
      for (let j = 0; j < m; j++) {
         counter[j][str.charCodeAt(j) - aCharCode]++;
      }
   }
   ans = '';
   for (let i = 0; i < m; i++) {
      for (let j = 0; j <= zCharCode - aCharCode; j++) {
         if (counter[i][j] & 1) {
            ans += String.fromCharCode(aCharCode + j);
            break;
         }
      }
   }
   write(ans);
}

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

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

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

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

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

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

const letters = [];
const aCharCode = 'a'.charCodeAt(0);
const zCharCode = 'z'.charCodeAt(0);
for (let i = aCharCode; i <= zCharCode; i++) {
   letters.push(String.fromCharCode(i));
}

function solve() {
   const [n, m] = readArray(Number);
   const counter = 'x'.repeat(m).split('').map(() => new Map());
   let str;
   for (let i = 0; i < n; i++) {
      str = read();
      for (let j = 0; j < m; j++) {
         const currentCounter = counter[j];
         if (currentCounter.has(str[j])) {
            currentCounter.set(str[j], currentCounter.get(str[j]) + 1);
         } else {
            currentCounter.set(str[j], 1);
         }
      }
   }
   for (let i = 0; i < n - 1; i++) {
      str = read();
      for (let j = 0; j < m; j++) {
         const currentCounter = counter[j];
         if (currentCounter.has(str[j])) {
            currentCounter.set(str[j], currentCounter.get(str[j]) + 1);
         } else {
            currentCounter.set(str[j], 1);
         }
      }
   }
   ans = '';
   for (let i = 0; i < m; i++) {
      const currentCounter = counter[i];
      for (let j = 0; j < letters.length; j++) {
         if (!currentCounter.has(letters[j])) {
            continue;
         }
         const num = currentCounter.get(letters[j]);
         if (num & 1) {
            ans += letters[j];
            break;
         }
      }
   }
   write(ans);
}

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

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

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

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

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

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


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 data = tokenizeIntegers(readline()),
		numTrees = data[0], fruitPerDay = data[1],
		days = new Array(3003);
	for (var i = 0; i <= 3002; ++i) {
		days[i] = [0, 0];
	}
	for (var i = 0; i < numTrees; ++i) {
		data = tokenizeIntegers(readline());
		var day = data[0], fruit = data[1];
		days[day][0] += fruit;
		days[day+1][1] += fruit;
	}
	var result = 0;
	for (var i = 1; i <= 3001; ++i) {
		var yesterday = Math.min(fruitPerDay, days[i][1]),
			total = Math.min(fruitPerDay, yesterday + days[i][0]),
			today = total - yesterday;
		days[i+1][1] = Math.max(0, days[i+1][1] - today);
		result += total;
	}
	print(result);
}

main();

var nextToken = new function() {
    var line = [];
    var lineIndex = 0;

    return function() {
        while (lineIndex >= line.length) {
            line = readline().split(/\s+/);
            lineIndex = 0;
        }

        return line[lineIndex++];
    }
}();

var nextInt = function() {
    return parseInt(nextToken(), 10);
};

var main = function () {
    var n = nextInt();
    var v = nextInt();
    var ans = 0;
    var i, a, b, cur;

    var cnt = [];
    for (i = 0; i < n; ++i) {
            var a, b;
            a = nextInt();
            b = nextInt();

            while (cnt.length <= a) {
                cnt.push(0);
            }

            cnt[a] += b;
    }
    cnt.push(0);

    var left = 0;

    for (i = 0; i < cnt.length; ++i) {
            var cur = v;
            if (left <= cur) {
                ans += left;
                cur -= left;
                left = 0;
            } else {
                ans += cur;
                left -= cur;
                cur = 0;
            }

            ans += Math.min(cur, cnt[i]);
            left = Math.max(0, cnt[i] - cur);
    }

    print(ans);
};

main();

var nextToken = new function() {
    var line = [];
    var lineIndex = 0;

    return function() {
        while (lineIndex >= line.length) {
            line = readline().split(/\s+/);
            lineIndex = 0;
        }

        return line[lineIndex++];
    }
}();

var nextInt = function() {
    return parseInt(nextToken(), 10);
};

var main = function () {
    var n = nextInt();
    var v = nextInt();
    var ans = 0;
    var i, a, b, cur;

    var cnt = [];
    for (i = 0; i < n; ++i) {
            var a, b;
            a = nextInt();
            b = nextInt();

            while (cnt.length <= a) {
                cnt.push(0);
            }

            cnt[a] += b;
    }
    cnt.push(0);

    var left = 0;

    for (i = 0; i < cnt.length; ++i) {
            var cur = v;
            if (left <= cur) {
                ans += left;
                cur -= left;
                left = 0;
            } else {
                ans += cur;
                left -= cur;
                cur = 0;
            }

            ans += Math.min(cur, cnt[i]);
            left += Math.max(0, cnt[i] - cur);
    }

    print(ans);
};

main();


//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');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
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 s = nextCharArray();
  var count = 0;
  for(var i = 0; i < N; i += 2){
    if(s[i] == s[i + 1]){
      if(s[i] == "a"){
        s[i] = "b";
      }else{
        s[i] = "a";
      }
      count++;
    }
  }
  myout(count);
  myout(myconv(s, 0));
}

// const readline = require('readline');
//
// const rl = readline.createInterface({ input: process.stdin , output: process.stdout });
//
// const getLine = (function () {
//     const getLineGen = (async function* () {
//         for await (const line of rl) {
//             yield line;
//         }
//     })();
//     return async () => ((await getLineGen.next()).value);
// })();
//
// async function main() {
//     let n = Number(await getLine());
//     let s = await getLine();
//     let c = 0;
//     let result = "";
//
//     for (let i = 0; i < n; i += 2){
//         if (s[i] == s[i + 1]) {
//             c++;
//             result += s[i] == 'a' ? 'b' : 'a';
//             result += s[i + 1];
//         }
//         else{
//             result += s[i] + s[i + 1];
//         }
//     }
//
//     console.log(c);
//     console.log(result);
//     process.exit(0);
// }
//
// main();

var n = parseInt(readline());
var s = readline();
var c = 0;
var result = "";

for (var i = 0; i < n; i += 2) {
    if (s[i] == s[i + 1]) {
        c++;
        result += s[i] == 'a' ? 'b' : 'a';
        result += s[i + 1];
    } else {
        result += s[i] + s[i + 1];
    }
}

print(c);
print(result);

'use strict'

const n = parseInt(readline());
const s = readline();

let r = 0;
let S = '';
for (let i = 0; i < n; i+=2) {
    const x = s[i] + s[i+1];
    if (x !== 'ab' && x !== 'ba') { r++; S += 'ab';}
    else { S += x };
}
write(r + '\n' + S);

n = +readline()
s = readline()
op = 0
ans = ''
for (i = 1; i < s.length; i += 2) {
  x = s.charAt(i - 1), y = s.charAt(i)
  if (x == y) {
    op++
    ans += 'ab'
  }
  else
    ans += x + y
}
print(op + '\n' + ans)

n = +readline()
s = readline()
op = 0
ans = ''
for (i = 1; i < s.length; i += 2) {
  if (s[i - 1] == s[i]) {
    op++
    ans += 'ab'
  }
  else
    ans += s[i - 1] + s[i]
}
print(op + '\n' + ans)

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    var q = 0;
    var n = readline();
    var s = readline();
    s = s.split('');
    for (var i = 1; i < s.length; i+=2) {
      if(s[i]==s[i-1]){
          q++;
          if(s[i]=='a')
              s[i]='b';
          else
              s[i]='a';
      }
    }
    console.log(q);
    console.log(s.join(''));
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (oldStr, length) {
        let count = 0;
        let data = oldStr.split('');
        let index = 0;
        while (index <  (length)) {
            let pair = data.slice(index, index + 2);
            if (pair[0] === pair[1]) {
                count++;
                data[index] = data[index] === 'a' ? 'b' : 'a';
            }
            index = index + 2;
        }

        return {count, newStr: data.join('')};
    }

    let length = +lines[0];
    let oldStr = lines[1];

    let result = foo(oldStr, length);

    let answer = '';
    answer += result.count + "\n";
    answer += result.newStr;

    console.log(answer);
})

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

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

  let ans = 0;
  let obj = {
    'a': 'b',
    'b': 'a',
  };
  const arr = str.split('');

  for (let i = 0; i < arr.length; i += 2) {
    if (arr[i] === arr[i + 1]) {
      ans++;
      arr[i] = obj[arr[i]];
    }
  }

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

  c++;
});

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 l = parseInt(arr.shift())
  let str = arr.shift()
  let str2 = ''
  let no = 0

  for(let i = 0; i < l; i += 2) {
    if(str[i] == str[i + 1]) {
      no ++
      str2 += 'ab'
    }

    else {
      str2 = str2 + str[i] + str[i + 1]
    }

  }

  console.log(no)
  console.log(str2)

})

function replace(a, index, char) {
  return a.substr(0, index) + char + a.substr(index + 1)
}

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 l = parseInt(arr.shift())
  let str = arr.shift()
  let str2 = ''
  let no = 0

  for(let i = 0; i < l; i += 2) {
    str2 += 'ab'
    if(str[i] == str[i + 1]) {
      no ++
    }
  }

  console.log(no)
  console.log(str)

})

function replace(a, index, char) {
  return a.substr(0, index) + char + a.substr(index + 1)
}

'use strict'

const n = parseInt(readline());
const s = readline();

let r = 0;
let S = '';
for (let i = 0; i < n / 2; i++) {
    const x = s.slice(i, i+2);
    if (x !== 'ab' && x !== 'ba') { r++; S += 'ab';}
    else { S += x };
}
write(r + '\n' + S + (n % 2) ? s[n-1] : '');

'use strict'

const n = parseInt(readline());
const s = readline();

let r = 0;
let S = '';
for (let i = 0; i < n / 2; i++) {
    const x = s[i] + s[i+1];
    if (x !== 'ab' && x !== 'ba') { r++; S += 'ab';}
    else { S += x };
}
write(r + '\n' + S + (n % 2 ? s[n-1] : ''));

'use strict'

const n = parseInt(readline());
const s = readline();

let r = 0;
let S = '';
for (let i = 0; i < n / 2; i+=2) {
    const x = s[i] + s[i+1];
    if (x !== 'ab' && x !== 'ba') { r++; S += 'ab';}
    else { S += x };
}
write(r + '\n' + S);

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 l = parseInt(arr.shift())
  let str = arr.shift()
  let str2 = ''
  let no = 0

  for(let i = 0; i < l; i += 2) {
    str2 += 'ab'
    if(str[i] == str[i + 1]) {
      no ++
    }
  }

  console.log(no)
  console.log(str2)

})

function replace(a, index, char) {
  return a.substr(0, index) + char + a.substr(index + 1)
}


const main = (input) => {
  input = input.split('\n')

  const t = Number(input[0])
  for (let i = 0; i < t; i++) {
    const n = parseInt(input[1 + i * 2])
    const a = input[1 + i * 2 + 1].split(' ').map((x) => parseInt(x))

    const mySet = new Set(a)
    const ans = mySet.size - ((n - mySet.size) & 1)

    console.log(ans)
  }
}

main(require('fs').readFileSync(0).toString())

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 = Number(lines[i]);
        }else{
            var a = lines[i].split(' ').map(Number);
            var s = new Map();
            for(j = 0; j < n; j++){
                if(s.has(a[j])){
                    var te = s.get(a[j]);
                    te++;
                    s.set(a[j], te);
                }else{
                    s.set(a[j], 1);
                }
            }
            console.log(s.size - ((n - s.size) % 2));
        }
    }
});

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
let data = [];
let dataIdx = 0;

rl.on('line', function (line) {
  //input,
  data.push(...line.trim().split(' '));
}).on('close', function () {
  //output
  main();
  process.exit();
});

function input() {
  return data[dataIdx++];
}

function output(value) {
  // try {
  process.stdout.write(String(value));
  // } catch (err) {
  //   process.stdout.write(value.toString());
  // }
}
//////////////////////////////////////////////////////////

function main() {
  let t = Number(input());
  while (t--) {
    let n = Number(input());
    const set = new Set();

    let rest = 0;
    for (let i = 0; i < n; i++) {
      const value = Number(input());

      if (set.has(value)) {
        rest++;
      } else {
        set.add(value);
      }
    }

    output(set.size - (rest % 2));
    output('\n');
  }
}

function Solution() {
  let t = 0;
  const n = Number(lines[t++]);
  const res = [];
  for (let i = 0; i < n; i++) {
    const num = Number(lines[t++]);
    const arr = lines[t++].split(' ').map((item) => Number(item));
    const set = new Set(arr);
    res[i] =  (num - set.size) % 2 === 0 ? set.size : set.size - 1;
  }
  return res.join('\n');
}

const readline = require('readline')

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
const lines = []
rl.on('line', (input) => {
  lines.push(input);
})
rl.on('close', () => {
  console.log(Solution());
});

function Solution() {
  let t = 0;
  const n = Number(lines[t++]);
  const res = [];
  for (let i = 0; i < n; i++) {
    const num = Number(lines[t++]);
    const arr = lines[t++].split(' ').map((item) => Number(item));
    const set = new Set(arr);
    const last = num - set.size;
    if (last % 2 === 0) res[i] = set.size;
    else res[i] = set.size - 1;
  }
  return res.join('\n');
}

const readline = require('readline')

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
const lines = []
rl.on('line', (input) => {
  lines.push(input);
})
rl.on('close', () => {
  console.log(Solution());
});

const rdline = require('readline');

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

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];

solve = () => {
    const t = parseInt(readline());
    for (let i = 0; i < t; i++) {
        const n = parseInt(readline());
        const b = readline().split(" ").map(Number);
        var c = {};
        var d = 0; //количество уникальных чисел в строке входных данных
        var ans;
        for (let j = b.length - 1; j >= 0; j--) {
            if (!c[b[j]]) {
                c[b[j]] = true;
                d++;
            }
        }
        if (d % 2 !== n % 2) {
            ans = d - 1;
        } else {
            ans = d;
        }
        console.log(ans);
    }
}

/*
** 799B
*/

// Common Template Starts //
//*
process.stdin.resume();
process.stdin.setEncoding("utf-8");

let is = "";
let cl = 0;

process.stdin.on("data", (inp) => {
    is += inp;
});

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

const readline = () => is[cl++];

// Common Template Ends //

function main() {
    let nLines = parseInt(readline());
    while (nLines--) {
        const dataLength = parseInt(readline());
        const data = readline().split(' ');
        const unique = data.filter((n, i) => data.indexOf(n) === i).length;
        console.log(unique % 2 === dataLength % 2 ? unique : unique - 1);
    }
}

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

function findKthLargest(nums, k) {
    k = nums.length - k;
    const quickSelect = (l, r) => {
        let pivot = nums[r];
        let p = l;
        for (let i = l; i < r; i++) {
            if (nums[i] <= pivot) {
                swapper(nums, p, i);
                p++;
            }
        }
        swapper(nums, p, r);

        if (p > k) return quickSelect(l, p - 1);
        else if (p < k) return quickSelect(p + 1, r);
        else return nums[p];
    };

    return quickSelect(0, nums.length - 1);
};

function swapper(array, a, b) {
    const temp = array[b];
    array[b] = array[a];
    array[a] = temp;
};

function main() {
    const n = parseInt(readline());
    for(var i=0; i<n; i++){
        const m = (readline());
        const s = new Set();
        var c =0;
        const d = readline();
        d.split(" ").map(r => {
            const x = parseInt(r);
            if(s.has(x)){
                c++;
            }
            s.add(x);
        });
        if(c % 2){
            c++;
        }
        foo(String(m-c));
    }
}
function foo(x) {
    process.stdout.write(x);   // without auto '\n' (newline)
    console.log();  // with auto '\n' (newline)
}

let ryan = '';//.map(Numaer).sort(function(a, a){return a - a})
process.stdin.on('data', c => ryan += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = ryan.split(EOL);
    var n = lines[0]
    for(j = 1; j <= n * 2; j++){
        if(j % 2 == 1){
            var e = lines[j], a = new Map()
        }else{
            k = lines[j].split(' ').map(Number)
            a = new Map()
            for(l = 0; l < e; l++){
                if(a.has(k[l])){
                    te = a.get(k[l]);
                    te++;
                    a.set(k[l], te);
                }else{
                    a.set(k[l], 1);
                }
            }
                console.log(a.size - ((e - a.size) % 2));

        }
    }

});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

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

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);

        let hash = {};
        for (let i = 0; i < arr.length; i++) {
            hash[arr[i]] = true;
        }

        let uniq = Object.keys(hash).length;
        let diff = arr.length - uniq;
        let res;
        if (diff % 2 === 0) {
            res = uniq;
        } else {
            res = uniq - 1;
        }
        output(res);
    }
}

const solve = (arr)=>{
     let obj = {},cnt = 0;
     for(let i=0;i<arr.length;i++){
          if(obj[arr[i]]) cnt++;
          else obj[arr[i]] = 1;
     }
     if(cnt===0) return arr.length;
     else return (arr.length-cnt) - cnt%2;

}

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

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var map = getCountMap(list);
		for(var i = 0; i < N; i++){
			for(var j = i + 1; j < N; j++){
				if(list[i] != -1 && list[j] != -1 && list[i] != list[j]){
					if(map[list[i]] > 1 && map[list[j]] > 1){
						map[list[i]]--;
						map[list[j]]--;
						list[i] = -1;
						list[j] = -1;
					}
				}
			}
		}
		for(var i = 0; i < N; i++){
			for(var j = i + 1; j < N; j++){
				if(list[i] != -1 && list[j] != -1 && list[i] == list[j]){
					if(map[list[i]] >= 2){
						map[list[i]] -= 2;
						list[i] = -1;
						list[j] = -1;
					}
				}
			}
		}
		var output = 0;
		for(var i = 0; i < N; i++){
			if(list[i] != -1){
				output++;
			}
		}
		myout(output);
	}
}

/**
 * Author : Fazlul Hoque
 * Node.js version : 12.16.3
 * command : node fileName.js <input.txt >output.txt
 */
"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");
let inputString = ""; //An array of  raw inputs (includes 'n,\r , not usable. need to process before use)
let currentLine = 0; //input sequence controller variable.

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main(); // after input
});

/********** Utility Functions Start **********/
/**
 *  read row Input
 * @returns string
 */
function _readRawLine() {
    return inputString[currentLine++];
}
function readLine(){
    // return _readRawLine().replace(/\s+$/g, '');
    return _readRawLine().replace('\r', '');
}

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

function readSingleInt() {
    const p = readLine();
    return parseInt(p);
}

function readIntArray() {
    return readLine().split(" ").map((v) => parseInt(v));
}

function readArray() {
    return readLine().split(" ");
}

function int(n) {
    return parseInt(n);
}
/********** Utility Functions End **********/
/**
 * Don't Touch this fucntion at all , unless you know what are you doing!
 */
function main() {
    solve();
}

// ********** actual Code Starts from here **********

function solve() {
    let t = readSingleInt();

    while(t--)
    {
        let cnt = 0;
        let cntEven = 0;
        let n  = readSingleInt();
        let tempAr = readIntArray();
        let arMap = {};

        tempAr.forEach( v=>{
            if(arMap[v]){
                arMap[v]++;
            }else{
                arMap[v]=1;
            }
        })

        for(let a in arMap){
            // console.log(`${a} = ${arMap[a]}`) key = value

            if(arMap[a]==1 || arMap[a]&1){
                cnt++;
            }
            if(arMap[a]%2==0){
                cntEven++;
            }
        }
        if(cntEven){
            if(cntEven&1){
                cntEven--;
            }
            cnt += cntEven;
        }
        console.log(cnt);

    }

}

process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let q = parseInt(readline());
  for (let i = 0; i < q; i++) {
    let n = readline();
    let input = readline().split(" ").map(Number);
    print(R(input));
  }
}

function R(arr) {
  let set = new Set();
  let dup = 0;
  for (let item of arr) {
    if (!set.has(item)) set.add(item);
    else dup++;
  }
  if (dup & 1) dup++;
  return arr.length - dup;
}

'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);
  }
  let even = 0;
  for (let [, count] of map) {
    if (count > 1 && !(count & 1)) even++;
  }
  if (even & 1) {
    return map.size - 1;
  } else {
    return map.size;
  }
}

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

const readline = require('readline')

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

function solve(n, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = (o[x] || 0) + 1
        return o
    }, {})
    let ans = 0
    for (let k in map) {
        const v = map[k]
        if (v > 1) {
            ans += v - 1
        }
    }
    return n - 2 * Math.ceil(ans / 2)
}

var input1 = Array();
var limitString = readline();
var limit = parseInt(limitString) * 2;
for (var i = 0; i < limit; i++) {
    input1.push(readline());
}
var output1 = calc(input1);
output1.forEach(function (value) { print(value); });
function calc(input) {
    var result = Array();
    for (var i = 0; i < input.length; i += 2) {
        var caseLength = parseInt(input[i]);
        var caseArray = input[i + 1].split(" ");
        var caseMap = new Map();
        for (var j = 0; j < caseLength; j++) {
            var currentValue = parseInt(caseArray[j]);
            if (caseMap.has(currentValue)) {
                var count = caseMap.get(currentValue);
                count++;
                caseMap.set(currentValue, count);
            }
            else {
                caseMap.set(currentValue, 1);
            }
        }
        var resultValue = 0;
        if ((caseLength % 2) == 0) {
            if (caseMap.size % 2 == 0) {
                resultValue = caseMap.size;
            }
            else {
                resultValue = (caseMap.size - 1);
            }
        }
        else {
            if (caseMap.size % 2 == 0) {
                resultValue = caseMap.size - 1;
            }
            else {
                resultValue = caseMap.size;
            }
        }
        result.push(resultValue);
    }
    return result;
}

var test_cases = readline();
var nbr,arrayy;
var _set = new Set();
var zdeg = [];

while(test_cases--){
    _set.clear();
    nbr = readline();
    zdeg = readline().split(" ").map((el)=> {
        _set.add(parseInt(el))
        return 1;
        });
    if(_set.size == 1)
        if( nbr % 2 == 0) print(0)
        else print(1)
    else if(nbr == _set.size) print(_set.size)
    else if(nbr % 2 == 0)
        if(_set.size % 2 == 0) print(_set.size)
        else print(_set.size - 1)
    else if(nbr % 2 != 0)
        if(_set.size % 2 == 0) print(_set.size - 1)
        else print(_set.size)
}

T = readline()

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

  set = new Set(h)
    ans = set.size
  if((n - set.size)%2 != 0)
    ans --
  print(ans)
}

var t = +readline();

for(var i = 0; i< t; i ++) {
    var a = readline();
    var b = readline().split(' ').map((t) => +t);

    print(Task2(b));
}

function Task2 (arr){

   var obj = {};
   for(var each of arr){
      if (obj.hasOwnProperty(each)) {
         obj[each]++;
      }else {
         obj[each] = 1;
      }
   }

   var count = 0;
   var extras = 0;
   for(var n in obj){
      count++;
      extras += obj[n]-1;
   }

   return extras % 2 === 0 ? arr.length - extras : arr.length-extras-1;

}

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 m = new Map();
	        var a = lines[i].split(' ').map(Number);
	        for(j = 0; j < n; j++){
	            m.set(a[j], 1);
	        }
	        if(n - m.size > 1 && n % 2 == 1){
	            console.log(m.size - 1);
	        }else{
	            console.log(m.size);
	        }
	    }
	}
});

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
let data = [];
let dataIdx = 0;

rl.on('line', function (line) {
  //input,
  data.push(...line.trim().split(' '));
}).on('close', function () {
  //output
  main();
  process.exit();
});

function input() {
  return data[dataIdx++];
}

function output(value) {
  try {
    process.stdout.write(value);
  } catch (err) {
    process.stdout.write(value.toString());
  }
}
//////////////////////////////////////////////////////////

function main() {
  let t = Number(input());
  while (t--) {
    let n = Number(input());
    const set = new Set();

    let rest = 0;
    for (let i = 0; i < n; i++) {
      const value = Number(input());

      if (set.has(value)) {
        rest++;
      } else {
        set.add(value);
      }
    }

    output(set.size - (rest % 2));
    output('\n');
  }
}

const rdline = require('readline');

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

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];
/**
 * План подзадачи:
 *
 * идя по циклу удалять одинаковые значения
 */
solve = () => {
    const t = parseInt(readline());
    for (let i = 0; i < t; i++) {
        const n = parseInt(readline());
        const b = readline().split(" ").map(Number);
        var c = [];
        for (let i = 0; i < n; i++) {
            b.sort(function(a, b) {
                return a - b;
              });
            if (b[i] !== b[i + 1]) {
                c.push(b[i]);
            }
        }
            if (c.length % 2 !== n % 2){
                ans = 1
            } else {
            ans = c.length;}

        console.log(ans);
    }
}

const readline = require('readline');
async function main() {

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

  let n = 0;
  let dataLength = 0;
  let data = [];
  for await (const line of rl) {
    if (!n) {
        n = parseInt(line);
        continue;
    }

    if (!dataLength) {
        dataLength = parseInt(line);
    } else {
        data = line.split(' ').map((n) => parseInt(n));
        const unique = data.filter((n, i) => data.indexOf(n) === i).length;
        process.stdout.write(`${unique - dataLength % 2}\n`);
        dataLength = 0;
    }
  }
}

main();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function findKthLargest(nums, k) {
    k = nums.length - k;
    const quickSelect = (l, r) => {
        let pivot = nums[r];
        let p = l;
        for (let i = l; i < r; i++) {
            if (nums[i] <= pivot) {
                swapper(nums, p, i);
                p++;
            }
        }
        swapper(nums, p, r);

        if (p > k) return quickSelect(l, p - 1);
        else if (p < k) return quickSelect(p + 1, r);
        else return nums[p];
    };

    return quickSelect(0, nums.length - 1);
};

function swapper(array, a, b) {
    const temp = array[b];
    array[b] = array[a];
    array[a] = temp;
};

function main() {
    const n = parseInt(readline());
    for(var i=0; i<n; i++){
        const m = (readline());
        const s = new Set();
        var c =0;
        const d = readline();
        console.log(d);
        d.split(" ").map(r => {
            const x = parseInt(r);
            if(s.has(x)){
                c++;
            }
            s.add(x);
        });
        if(c % 2){
            c++;
        }
        foo(String(m-c));
    }
}
function foo(x) {
    process.stdout.write(x);   // without auto '\n' (newline)
    console.log();  // with auto '\n' (newline)
}

var input1 = Array();
var limitString = readline();
var limit = parseInt(limitString) * 2
for (var i = 0; i < limit; i++) {
    input1.push(readline());
}
var output1 = calc(input1);
output1.forEach(function (value) { print(value); });
function calc(input) {
    var result = Array();
    for (var i = 0; i < input.length; i += 2) {
        var caseLength = parseInt(input[i]);
        var caseArray = input[i + 1].split(" ");
        var caseMap = new Map();
        for (var j = 0; j < caseLength; j++) {
            var currentValue = parseInt(caseArray[j]);
            if (caseMap.has(currentValue)) {
                var count = caseMap[currentValue];
                count++;
                caseMap[currentValue] = count;
            }
            else {
                caseMap[currentValue] = 1;
            }
        }
        var resultValue = 0;
        if ((caseLength % 2) == 0) {
            if (caseMap.size % 2 == 0) {
                resultValue = caseMap.size;
            }
            else {
                resultValue = (caseMap.size - 1);
            }
        }
        else {
            if (caseMap.size % 2 == 0) {
                resultValue = caseMap.size - 1;
            }
            else {
                resultValue = caseMap.size;
            }
        }
        result.push(resultValue);
    }
    return result;
}

var test_cases = readline();
var nbr,arrayy;
var _set = new Set();
var zdeg = [];

while(test_cases--){
    _set.clear();
    nbr = readline();
    zdeg = readline().split(" ").map((el)=> {
        _set.add(parseInt(el))
        return 1;
        });

    print(_set.size == 1 ? nbr % 2 == 0 ? 0 : 1 : nbr == _set.size || nbr % 2 == 0 ? _set.size : _set.size - 1 )
}

var test_cases = readline();
var nbr,arrayy;
var _set = new Set();
var zdeg = [];

while(test_cases--){
    _set.clear();
    nbr = readline();
    zdeg = readline().split(" ").map((el)=> {
        _set.add(parseInt(el))
        return 1;
        });

    print(nbr === _set.size || nbr % 2 === 0 ? _set.size : _set.size - 1 )
}

var test_cases = 4
var nbr,arrayy;
var _set = new Set();
var zdeg = [];

while(test_cases--){
    nbr = readline();
    zdeg = readline().split(" ").map((el)=> {
        _set.add(el)
        return 1;
        });
    print(zdeg.length === _set.size || zdeg.length % 2 === 0 ? _set.size : _set.size -1 )
}

var test_cases = readline();
var nbr,arrayy;
var _set = new Set();
var zdeg = [];

while(test_cases--){
    nbr = readline();
    zdeg = readline().split(" ").map((el)=> {
        _set.add(el)
        return 1;
        });
    print(zdeg.length % 2 === 0 ? _set.size : _set.size -1 )
}

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

   result = {}

   for( i=0; i<n; i++){
      a = x[i]
      if(result[a] != undefined)
         ++result[a]
      else
         result[a] = 1
   }

   maxKey = 0

   for(key in result){
      maxKey = Math.max(result[key], maxKey)
   }

   if(maxKey!= 1)
       ans = n - (maxKey-1) * 2
   else
      ans = n
   print(ans)
}

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

   result = {}

   for( i=0; i<n; i++){
      a = x[i]
      if(result[a] != undefined)
         ++result[a]
      else
         result[a] = 1
   }

   maxKey = 0

   for(key in result){
      maxKey = Math.max(result[key], maxKey)
   }

   if(maxKey!= 1)
       ans = n - (maxKey-1) * 2
   else
      ans = 0
   print(ans)
}

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

   result = {}

   for( i=0; i<n; i++){
      a = x[i]
      if(result[a] != undefined)
         ++result[a]
      else
         result[a] = 1
   }

   maxKey = 0

   for(key in result){
      maxKey = Math.max(result[key], maxKey)
   }

   ans = n - (maxKey-1) * 2
   print(ans)
}


const readline = require('readline')

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

function solve(n, arr) {
    const m = arr.reduce((o, x, i) => {
        o[x] = i
        return o
    }, {})
    const cp = Array(1e3 + 1)
    for (let i = 1; i <= 1e3; i++) {
        cp[i] = -1
        for (let j = 1; j <= 1e3; j++) {
            if ((j in m) && gcd(i, j) === 1) {
                cp[i] = Math.max(cp[i], m[j])
            }
        }
    }
    let r = -1
    for (let i = 0; i < arr.length; i++) {
        const x = arr[i]
        if (cp[x] >= 0) {
            r = Math.max(r, i + cp[x] + 2)
        }
    }
    return r
}
function gcd(a, b) {
    if (a === 0) return b
    if (b === 0) return a

    while (a) {
        const r = b % a
        b = a
        a = r
    }
    return b
}

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    // console.log(line);
    let gcd=(a,b) => {
        if(!b) return a;
        return gcd(b,a%b);
    }
    for(let i=1;i<=t;i++)
    {
        let n=parseInt(line[2*i-1]);
        let a=line[2*i].split(' ').map(x=>{ return parseInt(x); });
        let ans=-1;
        let pos=new Array(1010);
        for(let i=0;i<n;i++) pos[a[i]]=i+1;
        for(let k=1;k<=1000;k++) {
            let x=k;
            if(!pos[k]) continue;
            for(let i=1;i<=1000;i++) {
                if(pos[i]&&gcd(x,i)===1) {
                    ans=Math.max(ans,pos[k]+pos[i]);
                }
            }
        }
        console.log(ans);
    }
})

/*
* auther yeling
*
*
*/
'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
function print(str) {
    console.log(str);
}

//TLE o(n^2)
function begin2(n, nums) {
    var gcd = function (a, b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    let max = -1;
    for(let i = 0; i < n; i++) {
        for(let j = 0; j < n; j++) {
            if(gcd(nums[i], nums[j]) == 1) {
                max = Math.max(max, i+j+2);
            }
        }
    }
    print(max);
}

function begin(n, nums) {
    var gcd = function (a, b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }
    let cache = new Array(1001).fill(-1);
    for(let i = 0; i < n; i++) {
        cache[nums[i]] = Math.max(cache[nums[i]], i+1);
    }

    let max = -1
    for(let i = 1; i <= 1000; i++) {
        for(let j = 1; j <= 1000; j++) {
            if(cache[i] != -1 && cache[j] != -1 && gcd(i, j) == 1) {
                max = Math.max(max, cache[i]+cache[j]);
            }
        }
    }
    print(max);
}

function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = parseInt(readline(), 10);
        var x = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        begin(n, x);
    }
}

/**
 * 10/13/22 morning
 * https://codeforces.com/contest/1742/problem/D
 */

const pr = console.log;

const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);

const solve = (n, a) => {
    let m = new Map(), res = -1;
    for (let i = 0; i < n; i++) {
        if (!m.has(a[i])) m.set(a[i], []);
        m.get(a[i]).push(i + 1);
    }
    for (const [x, ax] of m) {
        for (let y = 1; y <= 1000; y++) {
            if (m.has(y) && gcd(x, y) == 1) {
                let ay = m.get(y), i = ax[ax.length - 1], j = ay[ay.length - 1];
                // pr(x, ax, y, ay);
                res = Math.max(res, i + j);
            }
        }
    }
    pr(res);
};

const main = () => {
    const readLine = () => input[currentLine++];
    const ni = () => readLine() - '0';
    const nas = () => readLine().split(" ");
    const nai = () => nas().map(Number);
    const nal = () => nas().map(BigInt);
    let input = '', currentLine = 0;
    process.stdin.on('data', (stdin) => input += stdin)
    process.stdin.on('end', () => {
        input = input.split('\n');
        let t = ni();
        while (t--) {
            let n = ni(), a = nai();
            solve(n, a);
        }
    });
};

main()

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var map = {};
	for(var i = 1; i <= 1000; i++){
		for(var j = 1; j <= 1000; j++){
			if(gcd(i, j) == 1){
				if(map[i] == null){
					map[i] = [];
				}
				map[i].push(j);
			}
		}
	}
	while(hasNext()){
		var N = nextInt();
		var list = nextStrArray(N);
		var index = {};
		for(var i = 0; i < N; i++){
			if(index[list[i]] == null){
				index[list[i]] = 0;
			}
			index[list[i]] = i + 1;
		}
		var output = -1;
		for(var i = 0; i < N; i++){
			var s = map[list[i]];
			for(var j = 0; j < s.length; j++){
				if(index[s[j]] != null){
					output = Math.max(output, i + 1 + index[s[j]]);
				}
			}
		}
		myout(output);
	}
}
function gcd(m, n) {return n != 0 ? gcd(n, m % n) : m;}

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        N = 1005;
  let res = -1,
      cnt = new Array(N);
  for (let i = 1; i <= n; i++) {
    cnt[rn()] = i;
  }
  for (let i = 0; i <= N; i++) {
    if (cnt[i] === undefined) continue;
    for (let j = i; j <= N; j++) {
      if (cnt[j] === undefined) continue;
      if (gcd(i, j) === 1) res = Math.max(res, cnt[i] + cnt[j]);
    }
  }
  return res;
}
function gcd(a, b) {
  return b ? gcd(b, a % b) : a;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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