We call two numbers $$$x$$$ and $$$y$$$ similar if they have the same parity (the same remainder when divided by $$$2$$$), or if $$$|x-y|=1$$$. For example, in each of the pairs $$$(2, 6)$$$, $$$(4, 3)$$$, $$$(11, 7)$$$, the numbers are similar to each other, and in the pairs $$$(1, 4)$$$, $$$(3, 12)$$$, they are not.You are given an array $$$a$$$ of $$$n$$$ ($$$n$$$ is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.For example, for the array $$$a = [11, 14, 16, 12]$$$, there is a partition into pairs $$$(11, 12)$$$ and $$$(14, 16)$$$. The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains an even positive integer $$$n$$$ ($$$2 \le n \le 50$$$) — length of array $$$a$$$. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$).

For each test case print:   YES if the such a partition exists,  NO otherwise.  The letters in the words YES and NO can be displayed in any case.

NoteThe first test case was explained in the statement.In the second test case, the two given numbers are not similar.In the third test case, any partition is suitable.

var t = parseInt(readline());
for (var tc = 0; tc < t; tc++) {
  var n = parseInt(readline());
  var arr = readline()
    .split(" ")
    .map((val) => parseInt(val));

  var flag = false;
  arr = arr.sort((a, b) => a - b);
  for (var i = 1; i < arr.length; i++) {
    if (Math.abs(arr[i] - arr[i - 1] == 1) == 1) {
      arr = arr.slice(0, i - 1).concat(arr.slice(i + 1));
      i -= 2;
      flag = true;
    }
  }
  if (arr.length == 0) print("Yes");
  else {
    var odd = arr.filter((val) => val % 2 != 0);
    var even = arr.filter((val) => val % 2 == 0);

    if (odd.length % 2 == 0 && even.length % 2 == 0) print("Yes");
    else if (flag) {
      print("Yes");
    } else print("NO");
  }
}

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var n = +readline();
    var arr = readNumArray().sort((a, b) => a - b);
    var evens = 0;
    var odds = 0;
    var curr = arr[0];
    var has1diff = false;
    for (var j = 0; j < n; j++) {
      if (arr[j] - curr === 1) {
        has1diff = true;
      }
      curr = arr[j];
      if (arr[j] % 2) {
        odds++;
      } else {
        evens++;
      }
    }
    if (has1diff || odds % 2 === 0) {
      print("YES");
    } else {
      print("NO");
    }
  }

}

main();

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

	}
	myout(myconv(output,9));
}

const processData = (lines) => {
  const n = +lines[0]
  for (let i=0; i<n; i++) {
    const arr = lines[i*2+2].split(' ').map(x => +x)
    const p = [0, 0]
    for (const t of arr) {
      p[t%2]++
    }
    if (p[0]%2 !==0) {
      arr.sort((a, b) => a-b)
      let prev = arr[0]
      for (let i=1;i<arr.length; i++) {
        if (Math.abs(prev - arr[i]) === 1) {
          p[0]--
          p[1]--
          break
        }
        prev = arr[i]
      }
    }
    console.log(p[0]%2 === 0 ? 'YES' : 'NO')
  }
}

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

'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++];
}
/**
7
4
11 14 16 12
2
1 8
4
1 1 1 1
4
1 2 5 6
2
12 13
6
1 6 3 10 5 8
6
1 12 3 10 5 8

**/

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

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

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

    for(let r=0;r<range;r++) {
        let n = parseInt(readline());
        let a = readline().split(" ").map(Number);

        let even = [];
        let odd = [];

        for(let i=0;i<n;i++) {
            if(a[i] % 2 === 0) {
                even.push(a[i]);
            } else {
                odd.push(a[i]);
            }
        }

        if(even.length % 2 === 0 && odd.length % 2 === 0) {
            console.log('YES');
        } else {
            let find = false;
            for(let i=0;i<odd.length;i++) {
                for(let j=0;j<even.length;j++) {
                    if(Math.abs(odd[i] - even[j]) === 1) {
                        find = true;
                    }
                }
            }

            if(find) {
                console.log('YES');
            } else {
                console.log('NO');
            }
        }
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {

    let cases = parseInt(readline(), 10);
    for (var X = 0; X < cases; X++) {
      readline();
      let force = readline().split(" ").map(e => parseInt(e));
      const {pow, max, min} = Math;

      force.sort((a,b) => a - b);

      const odds = force.filter(f => f % 2 === 0);
      const even = force.filter(f => f % 2 === 1);

      if (odds.length % 2 === 0 && even.length % 2 === 0) {
        console.log('YES');
      } else {
        let follow = false;
        for (let i = 0; i < force.length - 1; i++) {
          const c1 = force[i];
          const c2 = force[i+1];
          if (Math.abs(c1 - c2) === 1) {
            follow = true;
            break;
          }
        }
        if (follow) {
          console.log('YES');
        } else {
          console.log('NO');
        }
      }

      //break;
      //console.log(Math.pow(Math.max(a,b) + Math.max(a,b) , 2))
    }

}

var t = parseInt(readline());
for (var tc = 0; tc < t; tc++) {
  var n = parseInt(readline());
  var arr = readline()
    .split(" ")
    .map((val) => parseInt(val));

  var differs = [];
  var reminders = [];
  reminders.push(arr[0] % 2);
  for (var i = 1; i < arr.length; i++) {
    differs.push(Math.abs(arr[i] - arr[i - 1]));
    reminders.push(arr[i] % 2);
  }
  if (differs.includes(1)) print("Yes");
  else {
    var found = false;
    for (var i = 1; i < reminders.length; i++) {
      if (reminders[i] == reminders[i - 1]) {
        print("Yes");
        found = true;
        break;
      }
    }
    if (!found) print("No");
  }

  differs = differs.sort((a, b) => a - b);
  print(differs[0]);
}

var t = parseInt(readline());
for (var tc = 0; tc < t; tc++) {
  var n = parseInt(readline());
  var arr = readline()
    .split(" ")
    .map((val) => parseInt(val));

  var differs = [];
  var reminders = [];
  reminders.push(arr[0] % 2);
  for (var i = 1; i < arr.length; i++) {
    differs.push(Math.abs(arr[i] - arr[i - 1]));
    reminders.push(arr[i] % 2);
  }
  if (differs.includes(1)) print("Yes");
  else {
    var found = false;
    for (var i = 1; i < reminders.length; i++) {
      if (reminders[i] == reminders[i - 1]) {
        print("Yes");
        found = true;
        break;
      }
    }
    if (!found) print("No");
  }
}

var t = parseInt(readline());
for (var tc = 0; tc < t; tc++) {
  var n = parseInt(readline());
  var arr = readline()
    .split(" ")
    .map((val) => parseInt(val));

  var differs = [];
  var reminders = [];
  reminders.push(arr[0] % 2);
  for (var i = 1; i < arr.length; i++) {
    differs.push(Math.abs(arr[i] - arr[i - 1]));
    reminders.push(arr[i] % 2);
  }
  reminders = reminders.sort((a, b) => a - b);
  if (differs.includes(1)) print("Yes");
  else {
    var found = false;
    for (var i = 1; i < reminders.length; i++) {
      if (reminders[i] == reminders[i - 1]) {
        print("Yes");
        found = true;
        break;
      }
    }
    if (!found) print("No");
  }
}

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

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

'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++];
}
/**
7
4
11 14 16 12
2
1 8
4
1 1 1 1
4
1 2 5 6
2
12 13
6
1 6 3 10 5 8
6
1 12 3 10 5 8

**/

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

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

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

    for(let r=0;r<range;r++) {
        let n = parseInt(readline());
        let a = readline().split(" ").map(Number);

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

        for(let i=0;i<a.length;i++) {
            if(!a[i]) {
                continue;
            }
            for(let j=1;j<a.length;j++) {
                if(i === j) {
                    continue;
                }
                if(!a[j]) {
                    continue;
                }

                if(Math.abs(a[i] - a[j]) === 1) {
                    a[i] = undefined;
                    a[j] = undefined;
                    continue;
                }

                if(a[i] % 2 === a[j] % 2) {
                    a[i] = undefined;
                    a[j] = undefined;
                    continue;
                }
            }
        }

        let nums = a.filter((x) => x !== undefined);
        if(!nums.length) {
            console.log('YES');
        } else {
            console.log('NO');
        }
    }
}


You are given an angle $$$\text{ang}$$$. The Jury asks You to find such regular $$$n$$$-gon (regular polygon with $$$n$$$ vertices) that it has three vertices $$$a$$$, $$$b$$$ and $$$c$$$ (they can be non-consecutive) with $$$\angle{abc} = \text{ang}$$$ or report that there is no such $$$n$$$-gon.  If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed $$$998244353$$$.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 180$$$) — the number of queries.  Each of the next $$$T$$$ lines contains one integer $$$\text{ang}$$$ ($$$1 \le \text{ang} < 180$$$) — the angle measured in degrees.

For each query print single integer $$$n$$$ ($$$3 \le n \le 998244353$$$) — minimal possible number of vertices in the regular $$$n$$$-gon or $$$-1$$$ if there is no such $$$n$$$.

NoteThe answer for the first query is on the picture above.The answer for the second query is reached on a regular $$$18$$$-gon. For example, $$$\angle{v_2 v_1 v_6} = 50^{\circ}$$$.The example angle for the third query is $$$\angle{v_{11} v_{10} v_{12}} = 2^{\circ}$$$.In the fourth query, minimal possible $$$n$$$ is $$$180$$$ (not $$$90$$$).

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

  let tmp=0, T=0, angles=[];

  rl.on('line', (input) => {
      if (tmp==0) {T=Number(input); tmp++;}
      else {
          if (tmp<=T){
          let angle=Number(input);
            angles.push(angle);
            tmp++;}
          }
    if (tmp>T){ rl.close(); therest();}
    return 0;}
);

let therest=function() {
    for (let i=0; i<T; i++) {
        let ang=angles[i];
        let tr=180;
        if (ang%5==0) {
            tr=tr/5;
            ang=ang/5;
        }
        if (ang%4==0) {tr=tr/4; ang=ang/4;}
        else if (ang%2==0) {tr=tr/2; ang=ang/2;}
        if (ang%9==0) {tr=tr/9; ang=ang/9;}
        else if (ang%3==0) {tr=tr/3; ang=ang/3;}

        if (ang+1==tr) tr*=2;
        console.log(tr);

    }
//console.log(T, pairs)
}
//console.log(lngth, str);}

  /*
  rl.question('What do you think of Node.js? ', (answer) => {
    // TODO: Log the answer in a database
    console.log(`Thank you for your valuable feedback: ${answer}`);

    rl.close();
  });*/


Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?

The first line contains integer n (1 ≤ n ≤ 50) — the number of strings. This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.

Print the minimal number of moves Mike needs in order to make all the strings equal or print  - 1 if there is no solution.

NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz".

//@ts-check

/**
 * @param {string} str
 * @param {number} steps
 */
function makeSteps(str, steps) {
  return str.slice(steps) + str.slice(0, steps);
}

/**
 * @param {string[]} arr
 */
function solve(arr) {
  const len = arr[0].length;
  const $ = arr.map(() => new Map());
  for (let j = 0; j < len; j++) {
    const target = makeSteps(arr[0], j);
    if (!$[0].has(target)) {
      $[0].set(makeSteps(arr[0], j), j);
    }
  }
  for (let i = 1; i < $.length; i++) {
    for (let j = 0; j < len; j++) {
      const target = makeSteps(arr[i], j);
      const currentSteps = $[i].has(target)
        ? $[i].get(target)
        : Number.POSITIVE_INFINITY;
      if ($[i - 1].has(target) || $[i - 1].get(target) === -1) {
        const prevLineSteps = $[i - 1].get(target);
        $[i].set(target, Math.min(currentSteps, prevLineSteps + j));
      } else {
        $[i].set(target, -1);
      }
    }
  }
  return Math.min(...$.pop().values());
}

function* main() {
  const n = parseInt(yield);
  const s = [];
  for (let index = 0; index < n; index++) {
    s.push(yield);
  }
  const r = solve(s);
  console.log(r);
  process.exit(0);
}

if (!module.parent) {
  (() => {
    const q = main();
    q.next();
    require("readline")
      .createInterface({
        input: process.stdin,
        output: null,
      })
      .on("line", (line) => q.next(line));
  })();
}

exports.solve = solve;

'use strict';

function createReadLine() {
  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++];
  }

  return readline;
}

const readline = createReadLine();

function readInts(){
  return readline().split(' ').map((value => Number.parseInt(value)));
}

function readFloats(){
  return readline().split(' ').map((value => Number.parseFloat(value)));
}

function readStr() {
  return readline();
}

function readInt(){
  return Number.parseInt(readline());
}

function readFloat(){
  return Number.parseFloat(readline());
}

function main() {
  const n = readInt();
  const strs = []
  for (let i = 0; i < n; i ++){
    strs.push(readStr())
  }
  const result = solve(strs);
  console.log(result);
}

function makeStep(str, steps) {
  return str.slice(steps) + str.slice(0, steps);
}

function solve(strs){
  let set =  strs.map(() => new Map());
  const firstLine = new Array(strs[0].length);
  firstLine[0] = strs[0]
  for (let j = 1; j < firstLine.length; j++){
    firstLine[j] = makeStep(strs[0], j)
  }
  set[0] = new Map([...new Set(firstLine)].map(((value, index) => [value, index])));
  const resultArr =  new Array(strs.length).fill(0).map(() => new Array(strs[0].length).fill(0));
  const values = [...set[0].values()];
  resultArr[0] = [...strs[0]].map((val, index) => {
    if(values[index] !== undefined){
      return index;
    }
    return 0
  })
  for (let i = 1; i < set.length; i ++){
    for (let j = 0; j < strs[0].length; j ++){
      const current = makeStep(strs[i], j)
      let value = set[i  -1].get(current);
      if(value === undefined) {
        value = -1;
      } else {
        const prev = makeStep(strs[i], j -1);
        const currentValue = set[i].get(current);
        if(currentValue) {
          resultArr[i][j] = currentValue;
          continue;
        }
        if(prev !== current){
          value += j;
        }
      }
      set[i].set(current, value);
      resultArr[i][j] = value;
    }
  }
  return Math.min(...resultArr[strs.length - 1])
}

module.exports.solve = solve;

'use strict';

function createReadLine() {
  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++];
  }

  return readline;
}

const readline = createReadLine();

function readInts(){
  return readline().split(' ').map((value => Number.parseInt(value)));
}

function readFloats(){
  return readline().split(' ').map((value => Number.parseFloat(value)));
}

function readStr() {
  return readline();
}

function readInt(){
  return Number.parseInt(readline());
}

function readFloat(){
  return Number.parseFloat(readline());
}

function main() {
  const n = readInt();
  const strs = []
  for (let i = 0; i < n; i ++){
    strs.push(readStr())
  }
  const result = solve(strs);
  console.log(result);
}

function makeStep(str, steps) {
  return str.slice(steps) + str.slice(0, steps);
}

function solve(strs){
  let set =  strs.map(() => new Map());
  const firstLine = new Array(strs[0].length);
  firstLine[0] = strs[0]
  for (let j = 1; j < firstLine.length; j++){
    firstLine[j] = makeStep(strs[0], j)
  }
  set[0] = new Map([...new Set(firstLine)].map(((value, index) => [value, index])));
  for (let i = 1; i < set.length; i ++){
    for (let j = 0; j < strs[0].length; j ++){
      const current = makeStep(strs[i], j)
      let value = set[i  -1].get(current);
      if(value === undefined) {
        value = -1;
      } else {
        const prev = makeStep(strs[i], j -1);
        const currentValue = set[i].get(current);
        if(currentValue) {
          continue;
        }
        if(prev !== current){
          value += j;
        }
      }
      set[i].set(current, value);
    }
  }
  return Math.min(...set[strs.length - 1].values())
}

module.exports.solve = solve;

'use strict';

function createReadLine() {
  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++];
  }

  return readline;
}

const readline = createReadLine();

function readInts(){
  return readline().split(' ').map((value => Number.parseInt(value)));
}

function readFloats(){
  return readline().split(' ').map((value => Number.parseFloat(value)));
}

function readStr() {
  return readline();
}

function readInt(){
  return Number.parseInt(readline());
}

function readFloat(){
  return Number.parseFloat(readline());
}

function main() {
  const n = readInt();
  const strs = []
  for (let i = 0; i < n; i ++){
    strs.push(readStr())
  }
  const result = solve(strs);
  console.log(result);
}

function makeStep(str, steps) {
  return str.slice(steps) + str.slice(0, steps);
}

function solve(strs){
  let set =  strs.map(() => new Map());
  const firstLine = new Array(strs[0].length);
  firstLine[0] = strs[0]
  for (let j = 1; j < firstLine.length; j++){
    firstLine[j] = makeStep(strs[0], j)
  }
  set[0] = new Map([...new Set(firstLine)].map(((value, index) => [value, index])));
  for (let i = 1; i < set.length; i ++){
    for (let j = 0; j < strs[0].length; j ++){
      const current = makeStep(strs[i], j)
      let value = set[i  -1].get(current);
      if(value === undefined) {
        return -1;
      } else {
        const prev = makeStep(strs[i], j -1);
        const currentValue = set[i].get(current);
        if(currentValue) {
          continue;
        }
        if(prev !== current){
          value += j;
        }
      }
      set[i].set(current, value);
    }
  }
  return Math.min(...set[strs.length - 1].values())
}

module.exports.solve = solve;

var N = readline() | 0;
var lines = [];
for(var i = 0; i < N; ++i) {
    lines.push(readline());
}

var results = lines.map(function (line) {
    return lines.map(function (x) {
        return (x+x).indexOf(line);
    });
});

if (results[0].indexOf(-1) >= 0) {
    print(-1);
} else {
    print(results
        .map(function (x) { return x.reduce(function (a, x) { return a + x }, 0); })
        .reduce(function (a, x) { return Math.min(a,x); }, 10000000));
}

var l = [], res = 9999;
for (var i = Number(readline()); i > 0; i--) {
    var s = readline(), d = {};
    for (var j = s.length - 1; j >= 0; j--) d[s.substr(j) + s.substr(0, j)] = j;
    l.push(d)
}
for (s in d) {
    var x = 0;
    for (var t of l) x += t.hasOwnProperty(s) ? t[s] : 9999;
    if (x >= 9999) res = -1;
    else if (res > x) res = x;
}
print(res);

 var n = parseInt(readline());
  var s = [];
  String.prototype.rotate = function(x) {
    var a = x % this.length;
    var b;
    if(a > 0){
      b = this.length - a;
    } else {
      b = -a;
    }
    var c = this.substr(b, this.length);
    var d = this.substr(0, b);
    return c + d;
  };
  for(var i = 0; i < n; i += 1) {
    s[i] = readline();
  }
  var r = [];
  var t = [];
  var flag = true;
  var len = s[0].length;
  for(var i = 0; flag && i < n; i += 1) {
    var ok0 = false;
    var ok1 = false;
    for(var j = 0; j <= len; j += 1) {
      if(s[i].rotate(-j) == s[i] && j !== 0) {
        if(ok1 === false) {
          t[i] = j;
          ok1 = true;
        }
      }
      if(s[i].rotate(-j) == s[0]) {
        if(ok0 === false) {
          r[i] = j;
          ok0 = true;
        }
      }
    }
    if(ok0 == false) {
      flag = false;
    }
  }
  if(flag === false) {
    print(-1);
  } else {
    var res = Infinity;
    for(var i = 0; i < len; i += 1) {
      var tmp = 0;
      for(var j = 0; j < n; j += 1) {
        tmp += (r[j] + i) % t[j];
      }
      res = Math.min(res, tmp);
    }
    print(res);
  }

//@ts-check

/**
 * @param {string} str
 * @param {number} steps
 */
function makeSteps(str, steps) {
  return str.slice(steps) + str.slice(0, steps);
}

/**
 * @param {string[]} arr
 */
function solve(arr) {
  const len = arr[0].length;
  const $ = arr.map(() => new Map());
  for (let j = 0; j < len; j++) {
    $[0].set(makeSteps(arr[0], j), j);
  }
  for (let i = 1; i < $.length; i++) {
    for (let j = 0; j < len; j++) {
      const target = makeSteps(arr[i], j);
      if ($[i - 1].has(target) || $[i - 1].get(target) === -1) {
        const prevLineSteps = $[i - 1].get(target);
        $[i].set(target, prevLineSteps + j);
      } else {
        $[i].set(target, -1);
      }
    }
  }
  return Math.min(...$.pop().values());
}

function* main() {
  const n = parseInt(yield);
  const s = [];
  for (let index = 0; index < n; index++) {
    s.push(yield);
  }
  const r = solve(s);
  console.log(r);
  process.exit(0);
}

if (!module.parent) {
  (() => {
    const q = main();
    q.next();
    require("readline")
      .createInterface({
        input: process.stdin,
        output: null,
      })
      .on("line", (line) => q.next(line));
  })();
}

exports.solve = solve;

'use strict';

function createReadLine() {
  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++];
  }

  return readline;
}

const readline = createReadLine();

function readInts(){
  return readline().split(' ').map((value => Number.parseInt(value)));
}

function readFloats(){
  return readline().split(' ').map((value => Number.parseFloat(value)));
}

function readStr() {
  return readline();
}

function readInt(){
  return Number.parseInt(readline());
}

function readFloat(){
  return Number.parseFloat(readline());
}

function main() {
  const n = readInt();
  const strs = []
  for (let i = 0; i < n; i ++){
    strs.push(readStr())
  }
  const result = solve(strs);
  console.log(result);
}

function makeStep(str, steps) {
  return str.slice(steps) + str.slice(0, steps);
}

function solve(strs){
  let set =  strs.map(() => new Map());
  const firstLine = new Array(strs[0].length);
  firstLine[0] = strs[0]
  for (let j = 1; j < firstLine.length; j++){
    firstLine[j] = makeStep(strs[0], j)
  }
  set[0] = new Map([...new Set(firstLine)].map(((value, index) => [value, index])));
  const resultArr =  new Array(strs.length).fill(0).map(() => new Array(strs[0].length).fill(0));
  const values = [...set[0].values()];
  resultArr[0] = [...strs[0]].map((_, index) => {
    if(values[index] !== undefined){
      return index;
    }
    return Math.max(...values)
  })
  for (let i = 1; i < set.length; i ++){
    for (let j = 0; j < strs[0].length; j ++){
     const current = makeStep(strs[i], j)
     let value = set[i  -1].get(current);
     if(value === undefined) {
       value = -1;
     } else {
       const prev = makeStep(strs[i], j -1);
       if(prev !== current){
         value += j;
       }
     }
     set[i].set(current, value);
     resultArr[i][j] = value;
    }
  }
  return Math.min(...resultArr[strs.length - 1])
}

module.exports.solve = solve;

  var n = parseInt(readline());
  var s = [];
  String.prototype.rotate = function(x) {
    var a = x % this.length;
    var b;
    if(a > 0){
      b = this.length - a;
    } else {
      b = -a;
    }
    var c = this.substr(b, this.length);
    var d = this.substr(0, b);
    return c + d;
  };
  for(var i = 0; i < n; i += 1) {
    s[i] = readline();
  }
  var r = [];
  r[0] = 0;
  var flag = true;
  var len = s[0].length;
  for(var i = 1; flag && i < n; i += 1) {
    var ok = false;
    for(var j = 0; j < len; j += 1) {
      if(s[i].rotate(-j) == s[0]) {
        r[i] = j;
        ok = true;
      }
    }
    if(ok == false) {
      flag = false;
    }
  }
  if(flag === false) {
    print(-1);
  } else {
    var res = Infinity;
    for(var i = 0; i < len; i += 1) {
      var tmp = 0;
      for(var j = 0; j < n; j += 1) {
        tmp += (r[j] + i) % len;
      }
      res = Math.min(res, tmp);
    }
    print(res);
  }

  var n = parseInt(readline());
  var s = [];
  String.prototype.rotate = function(x) {
    var a = x % this.length;
    var b;
    if(a > 0){
      b = this.length - a;
    } else {
      b = -a;
    }
    var c = this.substr(b, this.length);
    var d = this.substr(0, b);
    return c + d;
  };
  for(var i = 0; i < n; i += 1) {
    s[i] = readline();
  }
  var r = [];
  r[0] = 0;
  var flag = true;
  var len = s[0].length;
  for(var i = 1; flag && i < n; i += 1) {
    var ok = false;
    for(var j = 0; j < len; j += 1) {
      if(s[i].rotate(-j) == s[0]) {
        r[i] = j;
        ok = true;
        break;
      }
    }
    if(ok == false) {
      flag = false;
    }
  }
  if(flag === false) {
    print(-1);
  } else {
    var res = Infinity;
    for(var i = 0; i < len; i += 1) {
      var tmp = 0;
      for(var j = 0; j < n; j += 1) {
        tmp += (r[j] + i) % len;
      }
      res = Math.min(res, tmp);
    }
    print(res);
  }


You are given an array a1, a2, ..., an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?Definitions of subsegment and array splitting are given in notes.

The first line contains two integers n and k (1 ≤ k ≤ n ≤  105) — the size of the array a and the number of subsegments you have to split the array to. The second line contains n integers a1,  a2,  ...,  an ( - 109  ≤  ai ≤  109).

Print single integer — the maximum possible integer you can get if you split the array into k non-empty subsegments and take maximum of minimums on the subsegments.

NoteA subsegment [l,  r] (l ≤ r) of array a is the sequence al,  al + 1,  ...,  ar.Splitting of array a of n elements into k subsegments [l1, r1], [l2, r2], ..., [lk, rk] (l1 = 1, rk = n, li = ri - 1 + 1 for all i > 1) is k sequences (al1, ..., ar1), ..., (alk, ..., ark).In the first example you should split the array into subsegments [1, 4] and [5, 5] that results in sequences (1, 2, 3, 4) and (5). The minimums are min(1, 2, 3, 4) = 1 and min(5) = 5. The resulting maximum is max(1, 5) = 5. It is obvious that you can't reach greater result.In the second example the only option you have is to split the array into one subsegment [1, 5], that results in one sequence ( - 4,  - 5,  - 3,  - 2,  - 1). The only minimum is min( - 4,  - 5,  - 3,  - 2,  - 1) =  - 5. The resulting maximum is  - 5.

'use strict'
//
// http://codeforces.com/contest/872/problem/A

const input = readline().split(' ').map(x => parseInt(x));
const arr = readline().split(' ').map(x => parseInt(x));

// const print = console.log;
// const line0 = "5 2";
// const line1 = "1 2 3 4 5";

// const input = line0.split(' ').map(x => parseInt(x));
// const arr = line1.split(' ').map(x => parseInt(x));

const splits = input[1];

function maxMin(arr, splits) {
  if (splits === 1) {
    return Math.min(...arr);
  }
  if (splits > 2) {
    return Math.max(...arr);
  }

  const len = arr.length;

  const minLeft = [arr[0]];
  const minRight = [];
  minRight[len-1] = arr[len-1];

  for (let i = 1; i < len; i++) {
    minLeft[i] = Math.min(minLeft[i-1], arr[i]);
    minRight[len-1-i] = Math.min(minRight[len-i], arr[len-1-i]);
  }

  let result = arr[0];

  for (let i = 0; i < len-1; i++) {
    if (minLeft[i] > result) {
      result = minLeft[i];
    }
    if (minRight[i+1] > result) {
      result = minRight[i+1];
    }
  }
  return result;
}

print(maxMin(arr, splits));


You are given three strings $$$s$$$, $$$t$$$ and $$$p$$$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose any character from $$$p$$$, erase it from $$$p$$$ and insert it into string $$$s$$$ (you may insert this character anywhere you want: in the beginning of $$$s$$$, in the end or between any two consecutive characters). For example, if $$$p$$$ is aba, and $$$s$$$ is de, then the following outcomes are possible (the character we erase from $$$p$$$ and insert into $$$s$$$ is highlighted):  aba $$$\rightarrow$$$ ba, de $$$\rightarrow$$$ ade;  aba $$$\rightarrow$$$ ba, de $$$\rightarrow$$$ dae;  aba $$$\rightarrow$$$ ba, de $$$\rightarrow$$$ dea;  aba $$$\rightarrow$$$ aa, de $$$\rightarrow$$$ bde;  aba $$$\rightarrow$$$ aa, de $$$\rightarrow$$$ dbe;  aba $$$\rightarrow$$$ aa, de $$$\rightarrow$$$ deb;  aba $$$\rightarrow$$$ ab, de $$$\rightarrow$$$ ade;  aba $$$\rightarrow$$$ ab, de $$$\rightarrow$$$ dae;  aba $$$\rightarrow$$$ ab, de $$$\rightarrow$$$ dea; Your goal is to perform several (maybe zero) operations so that $$$s$$$ becomes equal to $$$t$$$. Please determine whether it is possible.Note that you have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Each query is represented by three consecutive lines. The first line of each query contains the string $$$s$$$ ($$$1 \le |s| \le 100$$$) consisting of lowercase Latin letters. The second line of each query contains the string $$$t$$$ ($$$1 \le |t| \le 100$$$) consisting of lowercase Latin letters. The third line of each query contains the string $$$p$$$ ($$$1 \le |p| \le 100$$$) consisting of lowercase Latin letters.

For each query print YES if it is possible to make $$$s$$$ equal to $$$t$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

4
ab
acxb
cax
a
aaaa
aaabbcc
a
aaaa
aabbcc
ab
baaa
aaaaa

NoteIn the first test case there is the following sequence of operation:   $$$s = $$$ ab, $$$t = $$$ acxb, $$$p = $$$ cax;  $$$s = $$$ acb, $$$t = $$$ acxb, $$$p = $$$ ax;  $$$s = $$$ acxb, $$$t = $$$ acxb, $$$p = $$$ a. In the second test case there is the following sequence of operation:   $$$s = $$$ a, $$$t = $$$ aaaa, $$$p = $$$ aaabbcc;  $$$s = $$$ aa, $$$t = $$$ aaaa, $$$p = $$$ aabbcc;  $$$s = $$$ aaa, $$$t = $$$ aaaa, $$$p = $$$ abbcc;  $$$s = $$$ aaaa, $$$t = $$$ aaaa, $$$p = $$$ bbcc.

"use strict";

var foo = function(s1, s2) {
    var f = [];
    for (var i = 0, j = 0; j < s2.length; ++j) {
        if (i < s1.length && s1[i] === s2[j]) {
            ++i;
        } else {
            f.push(s2[j]);
        }
    }

    return [i === s1.length, f];
};

var main = function() {
    var q = +rd();
    loop:while (q-->0) {
        var s = rd().split('');
        var t = rd().split('');
        var p = rd().split('');

        var f1 = foo(s, t);
        if (f1[0]) {
            var f2 = foo(f1[1].sort(), p.sort());
            if (f2[0]) {
                pr('YES');
                continue loop;
            }
        }

        pr('NO');
    }
};

var rd = readline;
var wr = write;
var pr = print;
var rdAr = () => rd().split(' ').map(v => +v);
var prAr = (a) => pr(a.join(' '));
var cmpLt = (a, b) => a - b;
var cmpGt = (a, b) => b - a;

main();

const y = "YES";
const n = "NO";
function solve(){
    var s = readline();
    var t = readline();
    var p = readline();
    if(s.length > t.length){
        print(n);
        return;
    }
    var jt = 0;
    var was = new Array(t.length);
    was.fill(0, 0, t.length);
    var buff = new Array(p.length);
    buff.fill(0, 0, p.length);
    for(var i = 0;i < t.length;i++){
        if(s[jt] == t[i]){
            was[i] = 1;
            jt++;
            if(jt == s.length){
                break;
            }
        }
    }
    if(jt != s.length){
        print(n);
        return;
    }
    for(var i = 0;i < t.length;i++){
        if(!was[i]){
            var can = 0;
            for(var j = 0;j < p.length;j++){
                if(!buff[j] && p[j] == t[i]){
                    buff[j] = 1;
                    can = 1;
                    break;
                }
            }
            if(!can){
                print(n);
                return;
            }
        }
    }
    print(y);
    return;
}

var t = Number(readline());
while(t--){
    solve();
}

const readline = require('readline');

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

var q, s, t, p;

rl.on("line", (line) => {
	if (q == null) q = parseInt(line);
	else if (s == null) s = line;
	else if (t == null) t = line;
	else if (p == null) {
		p = line;
		// begin to solve
		var mp = {};
		var len1 = s.length;
		var len2 = t.length;
		var len3 = p.length;
		for (var i = 0; i < len3; i ++) {
			if (! mp[ p[i] ]) mp[ p[i] ] = 1;
			else mp[ p[i] ] ++;
		}
		var flag = true;
		var j = 0;
		for (var i = 0; i < len2; i ++) {
			if (j < len1 && s[j] == t[i]) j ++;
			else if (mp[ t[i] ]) mp[ t[i] ] --;
			else {
				flag = false;
				break;
			}
		}
		if (j < len1) flag = false;
		console.log( flag ? "YES" : "NO" );
		// end of solve
		s = t = p = null;
		q --;
		if (q == 0)
			rl.close();
	}
});

"use strict";

var foo = function(s1, s2) {
    var f = [];
    for (var i = 0, j = 0; j < s2.length; ++j) {
        if (i < s1.length && s1[i] === s2[j]) {
            ++i;
        } else {
            f.push(s2[j]);
        }
    }

    return [i === s1.length, f];
};

var main = function() {
    var q = +rd();
    loop:while (q-->0) {
        var s = rd().split('');
        var t = rd().split('');
        var p = rd().split('');

        var f1 = foo(s, t);
        if (f1[0]) {
            //pr(f1[1]);
            var f2 = foo(f1[1], p);
            if (f2[0]) {
                pr('YES');
                continue loop;
            }
        }

        pr('NO');
    }
};

var rd = readline;
var wr = write;
var pr = print;
var rdAr = () => rd().split(' ').map(v => +v);
var prAr = (a) => pr(a.join(' '));
var cmpLt = (a, b) => a - b;
var cmpGt = (a, b) => b - a;

main();

const readline = require('readline');

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

var q, s, t, p;

rl.on("line", (line) => {
	if (q == null) q = parseInt(line);
	else if (s == null) s = line;
	else if (t == null) t = line;
	else if (p == null) {
		p = line;
		// begin to solve
		var mp = {};
		var len1 = s.length;
		var len2 = t.length;
		var len3 = p.length;
		for (var i = 0; i < len3; i ++) {
			if (! mp[ p[i] ]) mp[ p[i] ] = 1;
			else mp[ p[i] ] ++;
		}
		var flag = true;
		var j = 0;
		for (var i = 0; i < len2; i ++) {
			if (j < len1 && s[j] == t[i]) j ++;
			else if (mp[ t[i] ]) mp[ t[i] ] --;
			else {
				flag = false;
				break;
			}
		}
		console.log( flag ? "YES" : "NO" );
		// end of solve
		s = t = p = null;
		q --;
		if (q == 0)
			rl.close();
	}
});


Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!The cake is a n × n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.

In the first line of the input, you are given a single integer n (1 ≤ n ≤ 100) — the length of the side of the cake. Then follow n lines, each containing n characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.

Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.

NoteIf we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are:   (1, 2) and (1, 3)  (3, 1) and (3, 3)  Pieces that share the same column are:   (2, 1) and (3, 1)  (1, 3) and (3, 3)

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    const n = +d;
    for (let i = 3; i <= n; i++) {
      t[i] = t[i - 1] + i - 1;
    }
    return;
  }

  matrix.push([...d]);

  c++;
});

rl.on('close', () => {
  let ans = 0;

  for (let i = 0; i < matrix.length; i++) {
    let countX = 0;
    let countY = 0;

    for (let j = 0; j < matrix[i].length; j++) {
      if (matrix[i][j] === 'C') {
        countX++;
      }

      if (matrix[j][i] === 'C') {
        countY++;
      }
    }

    ans += t[countX];
    ans += t[countY];
  }

  console.log(ans);
});

function rda(){ return readline().split(" ").map(Number); };
function rdn(){ return +readline(); };

var cnt = [];
for(var i = 0, s = 0; i <= 100; i++){
    s += i;
    cnt[i] = s;
}

var n = rdn();

var ans = 0;
var cake = [];
for(var i = 0; i < n; i++){
    var line = readline();
    cake.push(line);
    var c = 0;
    for(var j = 0; j < n; j++){
        if(line[j] == "C") c++;
    }

    ans += (cnt[c-1] == undefined) ? 0 : cnt[c-1];
}

for(var j = 0; j < n; j++){
    var c = 0;
    for(var i = 0; i < n; i++){
        if(cake[i][j] == "C") c++;
    }

    ans += (cnt[c-1] == undefined) ? 0 : cnt[c-1];
}

write(ans);

var n = +readline();
var arr = [];
for(var i=0;i<n;i++)
arr.push(readline());
print(main(n, arr));
function main(n, arr) {
	var x = [], y = [];
	arr.forEach(function(row, i){
		row.split('').forEach(function(cell, j){
			x[i] = (x[i]|0)+(cell=='C');
			x[n+j] = (x[n+j]|0)+(cell=='C');
		});
	});
	var ans = 0;
	x.forEach(function(h){ans += (h*(h-1))/2});
	return ans;
}

var n = Number(readline());

var row_count = {};
var col_count = {};

var cake_row = [];

for (var i = 0; i < n; i++) {
	cake_row = readline().split('').map(String);
	for (var j = 0; j < n; j++) {
		if (cake_row[j] == 'C') {
			if (j in col_count) {
				col_count[j] += 1;
			} else {
				col_count[j] = 1;
			}
			if (i in row_count) {
				row_count[i] += 1;
			} else {
				row_count[i] = 1;
			}
		}
	}
}

var C_choose_2 = function(C) {
	return C * (C - 1) / 2;
};

var sum = 0;

for (var key in row_count) {
	sum += C_choose_2(row_count[key]);
}

for (var key in col_count) {
	sum += C_choose_2(col_count[key]);
}

print(sum);

/* TEST CASE
input
3
.CC
C..
C.C
output
4
input
4
CC..
C..C
.CC.
.CC.
output
9
 */
function main() {
	var n = parseInt(readline());
	var answer = 0;
	var cakesInRow = new Array(n);
	var cakesInCol = new Array(n);
	var i, j;
	for (i = 0; i < n; i++) {
		cakesInRow[i] = 0;
		cakesInCol[i] = 0;
	}

	for (i = 0; i < n; i++) {
		var s = readline();
		for (j = 0; j < n; j++) {
			if (s.charAt(j) == 'C') {
				cakesInRow[i]++;
				cakesInCol[j]++;
			}
		}
	}

	for (i = 0; i < n; i++) {
		var nCakes = cakesInRow[i];
		if (nCakes > 1) {
			answer += nCakes * (nCakes - 1) / 2;
		}

		nCakes = cakesInCol[i];
		if (nCakes > 1) {
			answer += nCakes * (nCakes - 1) / 2;
		}
	}
	print(answer);
}

main();

/* TEST CASE
input
3
.CC
C..
C.C
output
4
input
4
CC..
C..C
.CC.
.CC.
output
9
 */
function main() {
	var n = parseInt(readline());
	var answer = 0;
	var cakesInRow = []
	var cakesInCol = []
	var i, j;
	for (i = n; i >= 0; i--) {
		cakesInRow[i] = 0;
		cakesInCol[i] = 0;
	}

	for (i = 0; i < n; i++) {
		var s = readline();
		for (j = 0; j < n; j++) {
			if (s.charAt(j) == 'C') {
				cakesInRow[i]++;
				cakesInCol[j]++;
			}
		}
	}

	for (i = 0; i < n; i++) {
		var nCakes = cakesInRow[i];
		if (nCakes > 1) {
			answer += nCakes * (nCakes - 1) / 2;
		}

		nCakes = cakesInCol[i];
		if (nCakes > 1) {
			answer += nCakes * (nCakes - 1) / 2;
		}
	}
	print(answer);
}

main();

'use strict';

const n = Number(readline());
let cake = [];
let count = 0;

for (let i = 0; i < n; i++) {
  let line = readline().split('');
  count += calc(line.filter((c) => c === 'C').length);
  cake.push(line);
}

for (let i = 0; i < n; i++) {
  let _line = [];
  for (let j = 0; j < n; j++) {
    _line.push(cake[j][i])
  }
  count += calc(_line.filter((c) => c === 'C').length);
}

print(count)

function calc(n) {
  return n * (n - 1) / 2;
}

var n = Number(readline());
var tab = new Array(n);
for (var i = 0; i < n; ++i) {
    tab[i] = readline();
}

var sum = 0;
for (var i = 0; i < n; ++i) {
    var num = 0;
    for (var j = 0; j < n; ++j) {
        if (tab[i][j] === "C") {
            ++num;
        }
    }
    sum += num * (num - 1) / 2;
}
for (var i = 0; i < n; ++i) {
    var num = 0;
    for (var j = 0; j < n; ++j) {
        if (tab[j][i] === "C") {
            ++num;
        }
    }
    sum += num * (num - 1) / 2;
}

print(sum);

var readInt = () => parseInt(readline())
var readIntArray = () => readline().split(' ').forEach(item => parseInt(item))
var fact = n => n > 0 ? n*fact(n-1) : 1;

var N = readInt()
var cake = []
for (var i = 0; i < N; i++) {
    cake.push(readline())
}

var ans = 0
cake.forEach(function(s,i) {
    var n = Array.prototype.filter.call(s, c => c === 'C').length
    if (n > 1)
        ans+=fact(n)/(2*fact(n-2))

    n = cake.map(s => s[i]).filter(c => c ==='C').length
    if (n > 1)
        ans+=fact(n)/(2*fact(n-2))
})
print(ans)

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    const n = +d;
    for (let i = 3; i <= n; i++) {
      t[i] = t[i - 1] + i - 1;
    }
    return;
  }

  matrix.push([...d]);

  c++;
});

rl.on('close', () => {
  let ans = 0;

  for (let i = 0; i < matrix.length; i++) {
    let countX = 0;
    let countY = 0;

    for (let j = 0; j < matrix[i].length; j++) {
      if (matrix[i][j] === 'C') {
        countX++;
      }

      if (matrix[j][i] === 'C') {
        countY++;
      }
    }

    ans += t[countX];
    ans += t[countY];
  }

  console.log(ans);
});

function rda(){ return readline().split(" ").map(Number); };
function rdn(){ return +readline(); };

var cnt = [];
for(var i = 0, s = 0; i <= 100; i++){
    s += i;
    cnt[i] = s;
}

var n = rdn();

var ans = 0;
var cake = [];
for(var i = 0; i < n; i++){
    var line = readline();
    cake.push(line);
    var c = 0;
    for(var j = 0; j < n; j++){
        if(line[j] == "C") c++;
    }

    ans += cnt[c-1];
}

for(var j = 0; j < n; j++){
    var c = 0;
    for(var i = 0; i < n; i++){
        if(cake[i][j] == "C") c++;
    }

    ans += (cnt[c-1] == undefined) ? 0 : cnt[c-1];
}

write(ans);

function rda(){ return readline().split(" ").map(Number); };
function rdn(){ return +readline(); };

var cnt = [];
for(var i = 0, s = 0; i <= 100; i++){
    s += i;
    cnt[i] = s;
}

var n = rdn();

var ans = 0;
var cake = [];
for(var i = 0; i < n; i++){
    var line = readline();
    cake.push(line);
    var c = 0;
    for(var j = 0; j < n; j++){
        if(line[j] == "C") c++;
    }

    ans += cnt[c-1];
}

for(var j = 0; j < n; j++){
    var c = 0;
    for(var i = 0; i < n; i++){
        if(cake[i][j] == "C") c++;
    }

    ans += cnt[c-1];
}

write(ans);


There are $$$n$$$ districts in the town, the $$$i$$$-th district belongs to the $$$a_i$$$-th bandit gang. Initially, no districts are connected to each other.You are the mayor of the city and want to build $$$n-1$$$ two-way roads to connect all districts (two districts can be connected directly or through other connected districts).If two districts belonging to the same gang are connected directly with a road, this gang will revolt.You don't want this so your task is to build $$$n-1$$$ two-way roads in such a way that all districts are reachable from each other (possibly, using intermediate districts) and each pair of directly connected districts belong to different gangs, or determine that it is impossible to build $$$n-1$$$ roads to satisfy all the conditions.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of districts. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the gang the $$$i$$$-th district belongs to. It is guaranteed that the sum of $$$n$$$ does not exceed $$$5000$$$ ($$$\sum n \le 5000$$$).

For each test case, print:   NO on the only line if it is impossible to connect all districts satisfying the conditions from the problem statement.  YES on the first line and $$$n-1$$$ roads on the next $$$n-1$$$ lines. Each road should be presented as a pair of integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n; x_i \ne y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are two districts the $$$i$$$-th road connects.  For each road $$$i$$$, the condition $$$a[x_i] \ne a[y_i]$$$ should be satisfied. Also, all districts should be reachable from each other (possibly, using intermediate districts).

'use strict'; /*jslint node:true, browser:true, es6:true*/
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
const print = console.log
const lines = []
rl.on('line', line => {
    lines.push(line);
});
rl.on('close', main)
let rli = 0;
function readline() {
    return lines[rli++];
}

function query(arr){
    let set = new Set(arr);
    if (set.size==1)
        return print('NO');
    print('YES');
    let left = [], last;
    for (let i=1; i<arr.length; i++)
    {
        if (arr[0]==arr[i])
            left.push(i);
        else
        {
            print('1 '+(i+1));
            last = i;
        }
    }
    for (let i=0; i<left.length; i++)
        print((last+1)+' '+(left[i]+1));

}

function main() {
    var q = +readline();
    while (q--)
    {
        var n = +readline();
        let arr = readline().split(' ').map(a=>+a);
        query(arr);
    }
}

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

let lineNum = 0;
let countOfData = null;
let data = [];
readline.on('line', line => {
  lineNum++;
  if(lineNum === 1) {
    countOfData = +line * 2;
    return;
  }

  data.push(line);

  if(lineNum - 1 === countOfData) {
    goToSolution(data);
  }

});

function goToSolution(data) {
  data.forEach((districts, i) => {
    if(i % 2 !== 0) {

      districts = districts.split(' ');
      const map = districts.reduce((acc, band, i) => {
        (band in acc) ?
          acc[band].push(i + 1) :
          acc[band] = [i + 1];
        return acc;
      }, {});

      const bands = Object.keys(map);
      if(bands.length > 1) {
        console.log('YES');
        for(let i = 0; i < bands.length; i++) {
          if(bands.length - 1 !== i) console.log(`${map[bands[i]][0]} ${map[bands[i + 1]][0]}`);

          if(i > 0) {
            for(let j = 1; j < map[bands[i - 1]].length; j++) {
              console.log(`${map[bands[i]][0]} ${map[bands[i - 1]][j]}`)
            }
          }

          if(bands.length - 1 === i) {
            for(let j = 1; j < map[bands[i]].length; j++) {
              console.log(`${map[bands[i - 1]][map[bands[i - 1]].length - 1]} ${map[bands[i]][j]}`)
            }
          }

        }
      } else {
        console.log('NO');
      }
    }
  })
}

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

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine().split(" ").map(Number);
    const map = new Map();

    for (let i = 0; i < len; i++) {
      const num = arr[i];
      if (map.has(num)) {
        map.set(num, [...map.get(num), i + 1]);
      } else {
        map.set(num, [i + 1]);
      }
    }

    if (map.size === 1) console.log("NO");
    else {
      console.log("YES");
      const values = [...map.values()];
      const [firstRow, secondRow] = [values[0], values[1]];
      for (let row = 1; row < values.length; row++) {
        for (let col = 0; col < values[row].length; col++) {
          console.log(`${firstRow[0]} ${values[row][col]}`);
        }
      }
      for (let col = 1; col < firstRow.length; col++) {
        console.log(`${secondRow[0]} ${firstRow[col]}`);
      }
    }
  }
}

//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 t = nextInt();
	var output = [];
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var tmp = nextIntArray();
		var isOK = false;
		var list = new Array(N);
		var uf = unionFind(N);
		for(var j = 0; j < N; j++){
			list[j] = {
				no : j,
				G : tmp[j],
				child : new Set()
			}
		}
		var connect = new Set();
		for(var j = 0; j < N - 1; j++){
			for(var k = j + 1; k < N; k++){
				if(list[j].child.has(list[k].no) || list[k].child.has(list[j].no)){
					continue;
				}
				if(list[j].G != list[k].G && !uf.isSame(j, k)){
					isOK = true;
					list[j].child.add(list[k].no);
					list[k].child.add(list[j].no);
					connect.add((j + 1) + ":" + (k + 1));
					uf.doUnion(j, k);
				}
			}
		}
		if(isOK){
			output.push("YES");
			var keys = Array.from(connect);
			for(var j = 0; j < keys.length; j++){
				output.push(keys[j].split(":").join(" "));
			}
		}else{
			output.push("NO");
		}
	}
	myout(myconv(output, 9));
}
function unionFind(n){
  var uf = {
    //全てのインデックスは「-X(親、絶対値はグループの大きさ)」「自分が属する親(≒根)」のいずれかを持つ。
    //最初はみんなグループの大きさ1の親
    "list" : new Array(n).fill(-1),

    //同じ親を持つか
    "isSame" : function(mae, ato){
      return this.getRootIndex(mae) == this.getRootIndex(ato);
    },
    //自身の親インデックスをたどって根っこに着く
    //親にたどり終えたら子に帰っていくついでに、子たちに「共通の親を持っている」ことを知らせる
    "getRootIndex" : function(index){
      if(this.list[index] < 0){
        return index;
      }else{
        this.list[index] = this.getRootIndex(this.list[index]);
        return this.list[index];
      }
    },
    //異なる親同士のまとまりを一つにする（同じ親ならスルー）
    //小さいグループの親が大きいグループの親の直下に着く
    //グループの大きさも更新する
    "doUnion" : function(mae, ato){
      var maeRoot = this.getRootIndex(mae);
      var atoRoot = this.getRootIndex(ato);
      if(!this.isSame(maeRoot, atoRoot)){
        if(maeRoot >= atoRoot){
          this.list[maeRoot] += this.list[atoRoot];
          this.list[atoRoot] = maeRoot;
        }else{
          this.list[atoRoot] += this.list[maeRoot];
          this.list[maeRoot] = atoRoot;
        }
      }
    },
    //「-X(親、絶対値はグループの大きさ)」
    //なので、インデックスを指定→親を知る→親の持つグループの大きさがわかる。
    //ただしマイナス値なので、掛け算して返す。
    "getSize" : function(index){
      return -this.list[this.getRootIndex(index)];
    }
  }
  return uf;
}

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

let stdinInput = '';

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

process.stdin.on('end', () => {
  main(stdinInput);
})

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 2;
    let i = 1;
    while (i <= testCases) {
      // let a = data[i].trim();
      // const n = data[i] * 1;
      // const k = a[1];
      const s = data[i + 1].trim().split(' ').map(Number);
      // s.sort((a, b) => b - a);
      let idx = 0;
      let max = 0;
      let obj = {};

      for (let j = 0; j < s.length; j += 1) {
        if (obj[s[j]]) obj[s[j]].push(j);
        else obj[s[j]] = [j];
        // if (s[j] > max) {
        //   max = s[j];
        //   idx = j;
        // }
      }

      let arr = Object.values(obj);
      // console.log(arr);

      if (arr.length < 2) console.log('NO');
      else {
        console.log('YES');
        for (let j = 1; j < arr.length; j += 1) {
          for (let k = 0; k < arr[j].length; k += 1) {
            console.log(arr[0][0] + 1 + ' ' + (arr[j][k] + 1));
          }
        }
        for (let j = 1; j < arr[0].length; j += 1) {
          console.log(arr[1][0] + 1 + ' ' + (arr[0][j] + 1));
        }
      }

      i += 2;
    }
}

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

    districtConnections();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function districtConnections(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));

        let count = 0;
        let map = new Array(1000000005);
        let x = [];
        for(let i = 0; i < n; i++){
            if(map[a[i]] === undefined){
                count++;
                map[a[i]] = i+1;
                x.push(a[i]);
            }

            if(count >= 2)
                break;
        }

        if(count < 2){
            console.log('NO');
            continue;
        }

        console.log('YES');
        let visited = new Array(n+1);

        for(let i = 1; i <= n; i++){
            if(a[i-1] !== x[0]){
                if(!(visited[i] && visited[map[x[0]]])){
                    console.log(i, map[x[0]]);
                    visited[i] = true;
                    visited[map[x[0]]] = true;
                }
            }else{
                if(!(visited[i] && visited[map[x[1]]])){
                    console.log(i, map[x[1]]);
                    visited[i] = true;
                    visited[map[x[1]]] = true;
                }
            }
        }
    }
}

//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 t = nextInt();
	var output = [];
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var tmp = nextIntArray();
		var isOK = false;
		var list = new Array(N);
		for(var j = 0; j < N; j++){
			list[j] = {
				no : j,
				G : tmp[j],
				child : new Set()
			}
		}
		var connect = 0;
		for(var j = 0; j < N - 1; j++){
			if(connect == N - 1){
				break;
			}
			for(var k = j + 1; k < N; k++){
				if(list[j].child.has(list[k].no) || list[k].child.has(list[j].no)){
					continue;
				}
				if(list[j].G != list[k].G){
					isOK = true;
					list[j].child.add(list[k].no);
					connect++;
					if(connect == N - 1){
						break;
					}
					//list[k].child.add(list[j].no);
				}
			}
		}
		if(isOK){
			output.push("YES");
			for(var j = 0; j < N; j++){
				var keys = Array.from(list[j].child);
				for(var k = 0; k < keys.length; k++){
					output.push((j + 1) + " " + (keys[k] + 1));
				}
			}
		}else{
			output.push("NO");
		}
	}
	myout(myconv(output, 9));
}

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

    districtConnections();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function districtConnections(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));

        let count = 0;
        let map = new Array(1000000005);
        let x = [];
        for(let i = 0; i < n; i++){
            if(map[a[i]] === undefined){
                count++;
                map[a[i]] = i+1;
                x.push(a[i]);
            }

            if(count >= 2)
                break;
        }

        if(count < 2){
            console.log('NO');
            continue;
        }

        console.log('YES');
        for(let i = 1; i < n; i++){
            if(a[i-1] !== x[0]){
                console.log(i, map[x[0]]);
            }else{
                console.log(i, map[x[1]]);
            }
        }
    }
}


You have an array $$$a$$$ of size $$$n$$$ consisting only of zeroes and ones and an integer $$$k$$$. In one operation you can do one of the following:  Select $$$2$$$ consecutive elements of $$$a$$$ and replace them with their minimum (that is, let $$$a := [a_{1}, a_{2}, \ldots, a_{i-1}, \min(a_{i}, a_{i+1}), a_{i+2}, \ldots, a_{n}]$$$ for some $$$1 \le i \le n-1$$$). This operation decreases the size of $$$a$$$ by $$$1$$$.  Select $$$k$$$ consecutive elements of $$$a$$$ and replace them with their maximum (that is, let $$$a := [a_{1}, a_{2}, \ldots, a_{i-1}, \max(a_{i}, a_{i+1}, \ldots, a_{i+k-1}), a_{i+k}, \ldots, a_{n}]$$$ for some $$$1 \le i \le n-k+1$$$). This operation decreases the size of $$$a$$$ by $$$k-1$$$. Determine if it's possible to turn $$$a$$$ into $$$[1]$$$ after several (possibly zero) operations.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 50$$$), the size of array $$$a$$$ and the length of segments that you can perform second type operation on. The second line contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$), elements of array $$$a$$$.

For each test case, if it is possible to turn $$$a$$$ into $$$[1]$$$, print "YES", otherwise print "NO".

NoteIn the first test case, you can perform the second type operation on second and third elements so $$$a$$$ becomes $$$[0, 1]$$$, then you can perform the second type operation on first and second elements, so $$$a$$$ turns to $$$[1]$$$.In the fourth test case, it's obvious to see that you can't make any $$$1$$$, no matter what you do.In the fifth test case, you can first perform a type 2 operation on the first three elements so that $$$a$$$ becomes $$$[1, 0, 0, 1]$$$, then perform a type 2 operation on the elements in positions two through four, so that $$$a$$$ becomes $$$[1, 1]$$$, and finally perform the first type operation on the remaining elements, so that $$$a$$$ becomes $$$[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++){
        var a = lines[i].split(' ').map(Number);
        if(i % 2 == 1){
            n = a[0];
        }else{
            var ans = 0;
            var flag = false;
            for(j = 0; j < n; j++){
                if(a[j] == 1){
                    flag = true;
                    break;
                }
            }
            console.log(flag ? 'YES' : 'NO');
        }
    }
});

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var K = nextInt();
		var list = nextIntArray(N);
		if(list.indexOf(1) == -1){
			myout("NO");
		}else{
			myout("YES");
		}
	}
}

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]);
    for(let _=1;_<=t;_++)
    {
        let [n,k]=line[2*_-1].split(' ').map(x=>{return parseInt(x)});
        let a=line[2*_].split(' ').map(x=>{return parseInt(x)});
        flag=false;
        for(let i=0;i<n;i++) {
            if(a[i]) {
                flag=true;
            }
        }
        if(flag) console.log("YES");
        else console.log("NO");
    }
})

'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);
  rns();
  const a = rns();
  if (a.includes(1)) return 'YES';
  return 'NO';
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      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(/\r?\n/);
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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, k] = iInpArr();
    let arr = iInpArr();
    let ans = "NO";
    for (let i = 0; i < n; i++) {
      if (arr[i] === 1) {
        ans = "YES";
        break;
      }
    }
    console.log(ans);
  }
};
solve();

function solve() {
    read();
    write(~(read().indexOf('1')) ? 'YES' : 'NO');
}

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

var MEMORY;
var MEMORY_INDEX = 0;
var ANS = '';

try {
    initInput(start);
} catch (e) {
    console.log(e);
}
function readArray(f) {
    return read().split(' ').map(f);
}

function sortNumbers(a, b) {
    return a - b;
}
function sortNumbersDec(a, b) {
    return b - a;
}
var ANS;
// вывод через ANS быстрее, но ест кучу памяти.
// К тому же, максимальная длина строки - 2097151.
function write(value) {
    // console.log(value);
    ANS += value + '\n';
}
function writeAns() {
    if (ANS) {
        console.log(ANS);
    }
}
function read() {
    return MEMORY[MEMORY_INDEX++];
}
function initInput(callback) {
    var fs = require('fs');
    var isLocalStart = process.argv[2] === 'lorelvate';
    if (!isLocalStart) {
        MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
        callback();
        return;
    }
    var path = require('path');
    fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {
        if (err) {
            write(err);
            return;
        }
        MEMORY = data.split('\r\n');
        callback();
    });
}

var test_number = readline();
var n = 0,
  k = 0;
var temp_line = "",
  array_number;
while (test_number--) {
  temp_line = readline();
  array_number = readline();
  if (array_number.includes("1")) print("YES");
  else print("NO");
}

var n = parseInt(readline());

for (var i = 0; i < n; i++){
    var num = readline();
    var arr = readline().split(" ");
    var counter = false;

    for(var k = 0; k < arr.length; k++){
        if(arr[k] == 1){
            counter = true;
            break;
        }
    }
    if(counter === true) {
        print("YES");
    }else{
    print("NO");
    }
}

var t = readline();
    for(var i = 0 ; i < t ; ++i){
        var inputs = readline().split(' '), n = inputs[0] , k = inputs[1];
        var a = readline().split(' ');
        a.indexOf('1') == -1 ? print("NO") : print("YES");
    }

const cntLines = readline();

for (var i=0; i<cntLines; i++) {
    readline();
    var arr =  readline().split(" ");
    arr.find(item => item == 1) ? print('YES') : print('NO');
}

var test_number = readline();
var n = 0;


As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore. A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive — convex polygon.Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length li.The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle .Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing. Help sculptor!

The first line contains an integer n (3 ≤ n ≤ 105) — a number of rod-blanks. The second line contains n integers li (1 ≤ li ≤ 109) — lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.

Print the only integer z — the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) vertices and nonzero area from all of the rods.

NoteIn the first example triangle with sides {1 + 1 = 2, 2, 1} can be formed from a set of lengths {1, 1, 1, 2}. In the second example you can make a triangle with lengths {20, 11, 4 + 3 + 2 + 1 = 10}.

var n = parseInt(readline());
var input = readline().split(' ').map(function (item) {
    return parseInt(item);
});
var max = 0;
var sum = input.reduce(function(acc, curr){
    if(curr > max){
        max = curr;
    }
    return acc+curr;
}, 0)
print(2*max-sum+1);

function getInput() {
    var line = readline();
    var lines = [line];
    while (line = readline()) {
        lines.push(line);
    }
    return lines;
}

function main() {
    var items = getInput().pop().split(' ').map(i => Number(i));
    var max = 0;
    items.forEach(item => {
        if (max < item) {
            max = item;
        }
    });

    print(max - (items.reduce((res, cur) => res + cur, 0) - max) + 1);
}

main();