Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handkerchief pattern should look like that:           0        0 1 0      0 1 2 1 0    0 1 2 3 2 1 0  0 1 2 3 4 3 2 1 00 1 2 3 4 5 4 3 2 1 0  0 1 2 3 4 3 2 1 0    0 1 2 3 2 1 0      0 1 2 1 0        0 1 0          0Your task is to determine the way the handkerchief will look like by the given n.

The first line contains the single integer n (2 ≤ n ≤ 9).

Print a picture for the given n. You should strictly observe the number of spaces before the first digit on each line. Every two adjacent digits in the same line should be separated by exactly one space. There should be no spaces after the last digit at the end of each line.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  const len = +readLine();
  const result = [];

  for (let i = 0; i <= len; i++) {
    const line = [];
    for (let j = 0; j <= Math.floor((i * 2) / 2); j++) {
      line.push(j);
    }
    for (let j = Math.floor((i * 2) / 2) - 1; j >= 0; j--) {
      line.push(j);
    }
    result.push(line);
  }

  for (let i = len - 1; i >= 0; i--) {
    result.push(result[i]);
  }

  for (let i = 0; i < result.length; i++) {
    if (i <= len) {
      console.log(`${" ".repeat((len - i) * 2)}${result[i].join(" ")}`);
    } else {
      console.log(`${" ".repeat((i - len) * 2)}${result[i].join(" ")}`);
    }
  }
}

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function main() {
	let n = readLine() >> 0;
	let arr = [];
	let s = n * 2;

	for (let i = 0; i <= s; i++) {
		arr[i] = Array(s + 1).fill(' ');
	}

	for (let i = 0; i <= n; i++) {
		let c = 2 * i;
		let a = n - i;
		let x = 0;
		for (let j = a; j <= n; j++) {
			arr[i][j] = x;
			arr[i][s - j] = x;
			arr[s - i][j] = x;
			arr[s - i][s - j] = x;
			x++;
		}
	}

	for (let i = 0; i <= s; i++) {
		let str = '';
		let found = false;
		for (let j = 0; j <= s; j++) {
			if (arr[i][j] !== ' ') {
				found = true;
			}

			if (!found) {
				str += arr[i][j] + ' ';
			} else {
				if (arr[i][j] !== ' ') {
					str += arr[i][j] + ' ';
				}
			}
		}
		console.log(str.replace(/\s$/, ''));
	}
}

var n=+readline();
function line(n, a){
	var ret = [];
	for(var i=0; i<a-n; i++){
		ret.push(' ');
	}
	for(var i=0; i<=n; i++){
		ret.push(i);
	}
	for(var i=n-1; i>=0; i--){
		ret.push(i);
	}
	return ret.join(' ');
}

for(var i=0; i<=n; i++){
	print(line(i, n));
}
for(var i=n-1; i>=0; i--){
	print(line(i, n));
}

;(function () {

	var n = +readline();
	var s = new Array(2 * n + 1);

	for (var i = 0; i < s.length; i++) {
		s[i] = [];
		for (var j = 0; j < Math.abs(n - i); j++) s[i].push(' ');
		for (var j = 0; j < n - Math.abs(n - i) + 1; j++)s[i].push(j);
		for (var j = n - Math.abs(n - i) - 1; j >= 0 ; j--)s[i].push(j);
		s[i] = s[i].join(' ') + '\n';
	}

	print(s.join(''));

}).call(this);

var n = parseInt(readline());
var str = "", down = false, space = n;
for(var i = 0; i <= 2*n; ++i)
{
    for(var j = 0; j < 2*space; ++j)
    {
        str += " ";
    }
    for(var j = 0; j <= Math.abs(n-space); ++j)
    {
        if(Math.abs(n-space) == 0){str = str + j.toString();}
        else {str = str + j.toString() + " ";}
    }
    for(var j = Math.abs(n-space)-1; j >= 0; --j)
    {
        if(j == 0){str = str + j.toString();}
        else {str = str + j.toString() + " ";}
    }
    if(i < 2*n){str += "\n"};
    if(down){space ++;}
    else {space --;}
    if(space == 0){down = true;}
}
print(str);

var deleteSpace = function(arr)
{
	arr = arr.split('');
	while (arr[arr.length - 1] === ' ')
	{
		if (arr[arr.length - 1] === ' ') arr.splice(arr.length - 1, 1);
	}
	return arr.join('');
}

var main = function(n)
{
	var arr = [],arrAll = [], space, numSpace = 2 * n;
	for (var i = 0; i <= n; i++)
	{
		space = [];
		numSpace -= 2 * i;
		for (var i1 = 1; i1 <= numSpace; i1++)
		{
			space.push(' ');
		}
		arr.push(space.join(''));
		if (i === 0)
			{
				space = space.join('');
				arr[arr.length - 1] += '0';
				print(arr);
				space = space.split('');
			}
		else
			{
				for (var resNum = 0; resNum <= i - 1; resNum++)
				{
				    arr.push(resNum + ' ');
				}
				arr = arr.join('') + i + ' ' + arr.reverse().join('');
				if (arr[arr.length - 1] === ' ') arr = deleteSpace(arr);
				print(arr);
			}
		arrAll.push(arr);
		arr = [];
		numSpace += 2 * i;
	}
	arrAll.reverse();
	for (i = 1; i <= arrAll.length - 1; i++)
	{
	    print( arrAll[i]);
	}
}

main(+readline());

// http://codeforces.com/problemset/problem/118/B
function addSpace(str,time) {
  var space="";
  for(var i = 0; i < time; i++)space+=" ";
  return space+str+"\n";
}
function createPalindromic(n){
  var line="",count=n-1;
  for(var i = 0; i < n; i++){
    line+=(i).toString();
    if(i<=count)line+=" ";
  }
  return line+(n).toString()+line.split("").reverse().join("");
}
function printPresent(n){
  var palindromicArray=[],textToPrint="",counter=n*2;
  for (var i = 0; i < n; i++) {
    var line=addSpace(createPalindromic(i),counter);
    palindromicArray.push(line);
    textToPrint+=line;
    counter-=2;
  }
  textToPrint+=addSpace(createPalindromic(n),0);
  for (var i = n-1; i >= 0; i--)textToPrint+=palindromicArray[i];
  return textToPrint.replace(/\n$/,"");
}
//console.log(printPresent(process.argv[2]));
print(printPresent(readline()));

function getLine(start, n) {
	var res = [];
	var i;
	for (i = 0; i < start; i++ ) {
		res.push(' ');
	}
	for (i = 0; i <= n; i++) {
		res.push(i);
	}
	for (i = n - 1; i >= 0; i--) {
		res.push(i)
	}
	print(res.join(' '));
}

var n = parseInt(readline());
var i;

for(i = 0; i <= n; i++) {
	getLine(n - i, i);
}

for(i = n - 1; i >= 0; i--) {
	getLine(n - i, i);
}

var s = ((+readline()*2))+1;var myarray = ["0"];var last = myarray[myarray.length - 1]

while(last.length!=s){

last = [...new Set(last)];

last.push((+last[last.length-1]) + 1)
last = last.concat(last.slice(0,last.length-1).reverse())

myarray.push(last)
}

for(var i=0;i<myarray.length;i++){tnzm(myarray[i])}
for(var i=myarray.length-2;i>=0;i--){tnzm(myarray[i])}

function tnzm(n){
var space = "";
for(var l=0;l<myarray.length-(i+1);l++){space+="  "}
print(space + n.toString().replace(/,/g," "))
}

function line(start, n) {
	var res = [];
	var i = 0;

	for (i = 0; i < start; i++) {
		res.push(' ');
	};

	for (i = 0; i <= n; i++) {
		res.push(i);
	};

	for (i = n - 1; i >= 0; i--) {
		res.push(i);
	};

	print(res.join(' '));
};

var n = parseInt(readline());
var i = 0;

for (i = 0; i <= n; i++) {
	line(n - i, i);
};

for (i = n - 1; i >= 0; i--) {
	line(n - i, i);
};

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function main() {
	let n = readLine() >> 0;
	let arr = [];
	let s = n * 2;

	for (let i = 0; i <= s; i++) {
		arr[i] = Array(s + 1).fill(' ');
	}

	for (let i = 0; i <= n; i++) {
		let c = 2 * i; // 2 * 1 = 2
		let a = n - i; // 2 - 1 = 1
		let x = 0;
		for (let j = a; j <= n; j++) {
			arr[i][j] = x;
			arr[i][s - j] = x;
			arr[s - i][j] = x;
			arr[s - i][s - j] = x;
			x++;
		}
	}

	for (let i = 0; i <= s; i++) {
		console.log(arr[i].join(' '));
	}
}

;(function () {

	var n = +readline();
	var s = new Array(2 * n + 1);

	for (var i = 0; i < s.length; i++) {
		s[i] = '';
		for (var j = 0; j < Math.abs(n - i); j++)			s[i] += ' ';
		for (var j = 0; j < n - Math.abs(n - i) + 1; j++)	s[i] += j + ' ';
		for (var j = n - Math.abs(n - i) - 1; j > 0 ; j--)	s[i] += j + ' ';
		s[i] += '0\n';
	}

	print(s.join(''));

}).call(this);

;(function () {

	var n = +readline();
	var s = new Array(2 * n + 1);

	for (var i = 0; i < s.length; i++) {
		s[i] = '';
		for (var j = 0; j < Math.abs(n - i); j++)			s[i] += ' ';
		for (var j = 0; j < n - Math.abs(n - i) + 1; j++)	s[i] += j;
		for (var j = n - Math.abs(n - i) - 1; j >= 0 ; j--)	s[i] += j;
		s[i] += '\n';
	}

	print(s.join(''));

}).call(this);

var n = parseInt(readline());
var str = "", down = false, space = n;
for(var i = 0; i <= 2*n; ++i)
{
    for(var j = 0; j < 2*space; ++j)
    {
        str += " ";
    }
    for(var j = 0; j <= Math.abs(n-space); ++j)
    {
        str = str + j.toString() + " ";
    }
    for(var j = Math.abs(n-space)-1; j >= 0; --j)
    {
        str = str + j.toString() + " ";
    }
    str += "\b";
    if(i < 2*n){str += "\n"};
    if(down){space ++;}
    else {space --;}
    if(space == 0){down = true;}
}
print(str);

var n = parseInt(readline());
var str = "", down = false, space = n;
for(var i = 0; i <= 2*n; ++i)
{
    for(var j = 0; j < 2*space; ++j)
    {
        str += " ";
    }
    for(var j = 0; j <= Math.abs(n-space); ++j)
    {
        if(j == Math.abs(n-space)){str = str + j.toString();}
        else {str = str + j.toString() + " ";}
    }
    for(var j = Math.abs(n-space)-1; j >= 0; --j)
    {
        if(j == 0){str = str + j.toString();}
        else {str = str + j.toString() + " ";}
    }
    if(i < 2*n){str += "\n"};
    if(down){space ++;}
    else {space --;}
    if(space == 0){down = true;}
}
print(str);

var n = parseInt(readline());
var str = "", down = false, space = n;
for(var i = 0; i <= 2*n; ++i)
{
    for(var j = 0; j < 2*space; ++j)
    {
        str += " ";
    }
    for(var j = 0; j <= Math.abs(n-space); ++j)
    {
        str = str + j.toString() + " ";
    }
    for(var j = Math.abs(n-space)-1; j >= 0; --j)
    {
        str = str + j.toString() + " ";
    }
    if(i < 2*n){str += "\n"};
    if(down){space ++;}
    else {space --;}
    if(space == 0){down = true;}
}
print(str);

var n = parseInt(readline());
var str = "", down = false, space = n;
for(var i = 0; i <= 2*n; ++i)
{
    for(var j = 0; j < 2*space; ++j)
    {
        str += " ";
    }
    for(var j = 0; j <= Math.abs(n-space); ++j)
    {
        str = str + j.toString() + " ";
    }
    for(var j = Math.abs(n-space)-1; j >= 0; --j)
    {
        str = str + j.toString() + " ";
    }
    for(var j = 0; j < 2*space; ++j)
    {
        str += " ";
    }
    if(i < 2*n){str += "\n"};
    if(down){space ++;}
    else {space --;}
    if(space == 0){down = true;}
}
print(str);

var n = parseInt(readline());
var str = "", down = false, space = n;
for(var i = 0; i <= 2*n; ++i)
{
    for(var j = 0; j < 2*space; ++j)
    {
        str += " ";
    }
    for(var j = 0; j <= Math.abs(n-space); ++j)
    {
        str = str + j.toString() + " ";
    }
    for(var j = Math.abs(n-space)-1; j >= 0; --j)
    {
        if(j == 0){str = str + j.toString();}
        else {str = str + j.toString() + " ";}
    }
    if(i < 2*n){str += "\n"};
    if(down){space ++;}
    else {space --;}
    if(space == 0){down = true;}
}
print(str);

var n = parseInt(readline());
var str = "", down = false, space = n;
for(var i = 0; i <= 2*n; ++i)
{
    for(var j = 0; j < 2*space; ++j)
    {
        str += " ";
    }
    for(var j = 0; j <= Math.abs(n-space); ++j)
    {
        str = str + j.toString() + " ";
    }
    for(var j = Math.abs(n-space)-1; j >= 0; --j)
    {
        str = str + j.toString() + " ";
    }
    for(var j = 0; j < 2*space; ++j)
    {
        str += " ";
    }
    str += "\n";
    if(down){space ++;}
    else {space --;}
    if(space == 0){down = true;}
}
print(str);

var main = function(n)
{
	var arr = [],arrAll = [], space, numSpace = 2 * n;
	for (var i = 0; i <= n; i++)
	{
		space = [];
		numSpace -= 2 * i;
		for (var i1 = 1; i1 <= numSpace; i1++)
		{
			space.push(' ');
		}
		arr.push(space.join(''));
		if (i === 0)
			{
				space = space.join('');
				arr[arr.length - 1] += '0';
				print(arr);
				space = space.split('');
			}
		else
			{
				for (var resNum = 0; resNum <= i - 1; resNum++)
				{
				    if (resNum !== i - 1)
					    arr.push(resNum + ' ');
					else arr.push(resNum);
				}
				arr = arr.join('') + i + ' ' + arr.reverse().join('');

				print(arr);
			}
		arrAll.push(arr);
		arr = [];
		numSpace += 2 * i;
	}
	arrAll.reverse();
	for (i = 1; i <= arrAll.length - 1; i++)
	{
	    print( arrAll[i]);
	}
}

main(+readline());

var main = function(n)
{
	var arr = [],arrAll = [], space, numSpace = 2 * n;
	for (var i = 0; i <= n; i++)
	{
		space = [];
		numSpace -= 2 * i;
		for (var i1 = 1; i1 <= numSpace; i1++)
		{
			space.push(' ');
		}
		arr.push(space.join(''));
		if (i === 0)
			{
				space = space.join('');
				arr[arr.length - 1] += '0';
				print(arr);
				space = space.split('');
			}
		else
			{
				for (var resNum = 0; resNum <= i - 1; resNum++)
				{
					arr.push(resNum + ' ');
				}
				arr = arr.join('') + i + ' ' + arr.reverse().join('');

				print(arr);
			}
		arrAll.push(arr);
		arr = [];
		numSpace += 2 * i;
	}
	arrAll.reverse();
	for (i = 1; i <= arrAll.length - 1; i++)
	{
	    print( arrAll[i]);
	}
}

main(+readline());

// http://codeforces.com/problemset/problem/118/B
function addSpace(str,time) {
  var space="";
  for(var i = 0; i < time; i++)space+=" ";
  return space+str+space+"\n";
}
function createPalindromic(n){
  var line="";
  var count=n-1;
  for(var i = 0; i < n; i++){
    line+=(i).toString();
    if(i<=count)line+=" ";
  }
  return line+(n).toString()+line.split("").reverse().join("");
}
function printPresent(n){
  var palindromicArray=[];
  var textToPrint="";
  var counter=n*2;
  for (var i = 0; i < n; i++) {
    var line=addSpace(createPalindromic(i),counter);
    palindromicArray.push(line)
    textToPrint+=line;
    counter-=2;
  }
  textToPrint+=addSpace(createPalindromic(n),0);
  for (var i = n-1; i >= 0; i--) {
     textToPrint+=palindromicArray[i];
  }
  return textToPrint.replace(/\n$/,"");
}
printPresent(5);

var s = ((+readline()*2))+1;
var myarray = ["0"];
var last = myarray[myarray.length - 1]

while(last.length!=s){
last = [...new Set(last)];

last.push((+last[last.length-1]) + 1)
last = last.concat(last.slice(0,last.length-1).reverse())
myarray.push(last)
}

for(var i=0;i<myarray.length;i++)
{print(myarray[i].toString().replace(/,/g," "))}

for(var i=myarray.length-2;i>=0;i--){print(myarray[i].toString().replace(/,/g," "))}


You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?

The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.

If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.

4
2
caa
cbb
3
cba
cba
cbb
4
ccab
cbac
bca
acbcc
4
acb
caf
c
cbafc

NoteIn the first test case, you can do the following:   Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.

/* #################################################################
 * This solution has been prepared for TheCodingConversations google
 * meet session to be held on 2020-09-06. If you wish to participate
 * in this session kindly refrain from reading this solution until
 * the session has been concluded.
 *
 * author - atifcppprogrammer
/* ################################################################# */

const handleTestCase = function(strings){
  // Creating map and counting occurences of all
  // characters found in each element of strings.
  const map = {};
  for (var i = 0; i < strings.length; ++i){
    var letters = strings[i].split('');
    for(var j = 0; j < letters.length; ++j){
      var key = letters[j];
      map[key] == undefined ? map[key] = 1 : map[key]++;
    }
  }
  // Checking if the occurence of each letter occurs
  // in integer multiples of strings.length.
  const keys = Object.keys(map); var go = true;
  for (var j = 0; j < keys.length && go; ++j){
    go = map[keys[j]] % strings.length == 0 && go;
  }
  return go;
}
const driverMethod = (function(){
  const testCaseCount = parseInt(readline());
  for (var i = 0; i < testCaseCount; ++i){
    // Collecting problem data for current test case.
    var stringCount = parseInt(readline()), strings = [];
    for (var j = 0; j < stringCount; ++j)
      strings.push(readline());
    // Printing verdict for current test case.
    var verdict = handleTestCase(strings) ? "YES" : "NO";
    print(verdict);
  }
  return "DONE";
})();
/* ################################################################# */

/* #################################################################
 * This solution has been prepared for TheCodingConversations google
 * meet session to be held on 2020-09-06. If you wish to participate
 * in this session kindly refrain from reading this solution until
 * the session has been concluded.
 *
 * author - atifcppprogrammer
/* ################################################################# */

const handleTestCase = function(strings){
  // Creating map and counting occurences of all
  // characters found in each element of strings.
  const map = {};
  for (var i = 0; i < strings.length; ++i){
    var letters = strings[i].split('');
    for(var j = 0; j < letters.length; ++j){
      var key = letters[j];
      map[key] == undefined ? map[key] = 1 : map[key]++;
    }
  }
  // Checking if the occurence of each letter occurs
  // in integer multiples of strings.length.
  const keys = Object.keys(map); var go = true;
  for (var j = 0; j < keys.length && go; ++j){
    go = map[keys[j]] % strings.length == 0 && go;
  }
  return go;
}
const driverMethod = (function(){
  const testCaseCount = parseInt(readline());
  for (var i = 0; i < testCaseCount; ++i){
    // Collecting problem data for current test case.
    var stringCount = parseInt(readline()), strings = [];
    for (var j = 0; j < stringCount; ++j)
      strings.push(readline());
    // Printing verdict for current test case.
    var verdict = handleTestCase(strings) ? "YES" : "NO";
    print(verdict);
  }
  return "DONE";
})();
/* ################################################################### */

/**
 *
 *
 * author - atifcppprogrammer
 */
const handleTestCase = function(strings){
  // Creating map and counting occurences of all
  // characters found in each element of strings.
  const map = {};
  for (var i = 0; i < strings.length; ++i){
    var letters = strings[i].split('');
    for(var j = 0; j < letters.length; ++j){
      var key = letters[j];
      map[key] == undefined ? map[key] = 1 : map[key]++;
    }
  }
  // Checking if the occurence of each letter occurs
  // in integer multiples of strings.length.
  const keys = Object.keys(map); var go = true;
  for (var j = 0; j < keys.length && go; ++j){
    go = map[keys[j]] % strings.length == 0 && go;
  }
  return go;
}
const driverMethod = (function(){
  const testCaseCount = parseInt(readline());
  for (var i = 0; i < testCaseCount; ++i){
    // Collecting problem data for current test case.
    var stringCount = parseInt(readline()), strings = [];
    for (var j = 0; j < stringCount; ++j)
      strings.push(readline());
    // Printing verdict for current test case.
    var verdict = handleTestCase(strings) ? "YES" : "NO";
    print(verdict);
  }
  return "DONE";
})();
/* ###################################################### */

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.split(/\n/)
    main()
});

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

function main() {
    const T = readLine()
    let strArr = new Array(T)
    for (let i = 0; i < T; i++) {
        const N = readLine()
        strArr[i] = []
        for (let _ = 0; _ < N; _++) {
            strArr[i].push(readLine())
        }
    }
    outerLoop: for (let i = 0; i < T; i++) {
        let letters = {}
        const n = strArr[i].length
        const wholeStr = strArr[i].join('')
        for (const letter of wholeStr) {
            if (letter in letters) {
                letters[letter]++
            } else {
                letters[letter] = 1
            }
        }
        for (let letter in letters) {
            if (letters[letter] % n) {
                console.log('NO')
                continue outerLoop
            }
        }
        console.log('YES')
    }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const map = {};
    let count = 0;
    for (let i = 0; i < len; i++) {
      const str = readLine()
        .split("")
        .forEach((char) => {
          count++;
          if (!map[char]) map[char] = 1;
          else map[char]++;
        });
    }
    if (!Number.isInteger(count / len)) console.log("NO");
    else {
      let ok = true;
      const values = Object.values(map);
      for (let value of values) {
        if (value % len !== 0) {
          console.log("NO");
          ok = false;
          break;
        }
      }
      if (ok) console.log("YES");
    }
  }
}

//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 = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    var map = {};
    for(var j = 0; j < N; j++){
      var s = next();
      for(var k = 0; k < s.length; k++){
        if(map[s[k]] == null){
          map[s[k]] = 0;
        }
        map[s[k]]++;
      }
    }
    var isOK = true;
    var key = Object.keys(map);
    for(var j = 0; j < key.length; j++){
      if(map[key[j]] % N != 0){
        isOK = false;
        break;
      }
    }
    output[i] = (isOK) ? "YES" : "NO";
  }
  myout(myconv(output, 9));
}

let inputString = '';
let currentLine = 0;

const runMain = () => {
  inputString = inputString.trim().split('\n').map(string => string.trim());
  main();
  process.exit();
}
const readLine = () => inputString[currentLine++];

process.stdin.on('data', inputStdin => inputString += inputStdin);
process.stdin.on('end', runMain);
process.on('SIGINT', runMain);

function main() {
  let t = Number(readLine());
  while (t--) {
    let n = Number(readLine());
    const ln = n;
    const m = {};
    while (n--) {
      const s = readLine().split('');
      s.forEach(ss => m[ss] = m[ss] ? m[ss] + 1 : 1);
    }
    const res = Object.keys(m).reduce((acc, cur) => acc || m[cur] % ln !== 0, false);
    console.log(!res ? 'YES' : 'NO');
  }
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return mid;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  let sub = [];
  a = a || 0;
  b = b || (this.length - 1);
  for (let i = a; i <= b; i++) {
    sub.push(this[i])
    if (fn(this[i], i, this)) {
      arr.push(sub);
      sub = [];
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
let MOD = 998244353
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);
  return (u + MOD) % MOD;
}

// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[998244353 % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let t = $()
  while (t--) {
    let n = +$()
    let m = {}
    For(n, i => { [...$()].forEach(c => m[c] = (m[c] || 0) + 1) })
    log(m.$k().every(c => m[c] % n == 0) ? 'YES' : '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();

/****** BELOW HERE START WRITING YOUR CODE IN main() FUNCTION   ***************************************/
/**
 * Use "readLine()" function for input, which will return a string consisting the entire line, so accordingly split the string
 * when required.
 *
 * I am using console.log() to output
 */
function main() {
  let t = readLine();
  t = parseInt(t);

  while (t--) {
    let n = readLine();
    n = Number(n);
    let dict = {};
    for (let i = 0; i <= 26; i++) {
      dict[String.fromCharCode(97 + i)] = 0;
    }

    for (let i = 0; i < n; i++) {
      let word = readLine();
      for (const c of word) {
        dict[c]++;
      }
    }

    let pass = true;

    for (const [key, value] of Object.entries(dict)) {
      if (value !== 0 && value % n !== 0) {
        pass = false;
        break;
      }
    }
    console.log(pass === true ? "YES" : "NO");
  }
}

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

let inputString = '';

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

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

    main(inputString);
});

const calculateAmountOfDistinctLetters = letters => {
    const letterMap = {};
    letters.split("").forEach(letter => {
        if(letterMap.hasOwnProperty(letter)){
            letterMap[letter]++;
        }else{
            letterMap[letter] = 1;
        }
    })
    return letterMap;
}

function main(fileContents) {
    // console.log(fileContents);

    fileContents.splice(0,1);

    const questions = [];

    while(fileContents.length > 1){
        questions.push(fileContents.splice(1,parseInt(fileContents[0])))
        fileContents.splice(0,1);
    }

    friendlyFormatQuestions = questions.map(question => ({
        amountOfWords:question.length,
        words:question,
        allLettersTogether:question.join(""),
        amountOfDistinctLetters:calculateAmountOfDistinctLetters(question.join(""))
    }))

 // console.log(friendlyFormatQuestions);

    console.log(friendlyFormatQuestions.map(question => {
        match = true;
        Object.keys(question.amountOfDistinctLetters).forEach(key => {
            if(question.amountOfDistinctLetters[key]%question.amountOfWords!==0){
                match = false;
            }
        })

        return match? "YES" : "NO";
    }).join("\n"));
}

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

    A();
});

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

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

    return a;
}

function A(){
    let t = parseInt(readline());
    while(t > 0){
        t--;
        let n = parseInt(readline());
        let str = new Array(n);
        for(let i = 0; i <  n; i++){
            str[i] = readline();
        }

        let map = new Array(26);
        map.fill(0);
        for(let s of str){
            for(let c of s){
                let index = c.charCodeAt(0) - 97;
                map[index] += 1;
            }
        }

        let isPossible = true;
        for(let i = 0; i < 26; i++){
            if(map[i] % n !== 0){
                isPossible = false;
                break;
            }
        }

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

function main(){
    let [n,k] = ti(readline().split(' '));
    let w = new Array(n);
    let v = new Array(n);

    for(let i = 0; i < n; i++){
        let [x,y] = ti(readline().split(' '));
        w[i] = x;
        v[i] = y;
    }

    let dp = new Array(n);
    for(let i = 0; i < n; i++){
        dp[i] = new Array(100001);
        dp[i].fill(99999999999);
    }

    for(let i = 0; i < n; i++){
        for(let j = 0; j < 100001; j++){
            if(i === 0 || j === 0){
                if(i === 0 && j === 0)
                    dp[i][j] = 0;
                else if(i === 0)
                    dp[i][j] = v[0] === j ? w[0] : 99999999999;
            }else{
                dp[i][j] = dp[i-1][j];
                if(j >= v[i])
                    dp[i][j] = Math.min(dp[i][j], w[i] + dp[i-1][j-v[i]]);
            }
        }
    }

    let max = 0;
    for(let i = 100000; i >= 0; i--){
        if(dp[n-1][i] <= k){
            max = i;
            break;
        }
    }

    console.log(max);
}

//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 = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    var map = {};
    for(var j = 0; j < N; j++){
      var s = next();
      for(var k = 0; k < s.length; k++){
        if(map[s[k]] == null){
          map[s[k]] = 0;
        }
        map[s[k]]++;
      }
    }
    var isOK = true;
    var key = Object.keys(map);
    for(var j = 0; j < key.length; j++){
      if(map[key[j]] % 2 != 0){
        isOK = false;
        break;
      }
    }
    output[i] = (isOK) ? "YES" : "NO";
  }
  myout(myconv(output, 9));
}

//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 = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    var map = {};
    for(var j = 0; j < N; j++){
      var s = next();
      for(var k = 0; k < s.length; k++){
        if(map[s[k]] == null){
          map[s[k]] = 0;
        }
        map[s[k]]++;
      }
    }
    var isOK = true;
    var key = Object.keys(map);
    for(var j = 0; j < key.length; j++){
      if(map[key[j]] % 2 != 0 && map[key[j]] >= N){
        isOK = false;
        break;
      }
    }
    output[i] = (isOK) ? "YES" : "NO";
  }
  myout(myconv(output, 9));
}

//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 = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    var map = {};
    for(var j = 0; j < N; j++){
      var s = next();
      for(var k = 0; k < s.length; k++){
        if(map[s[k]] == null){
          map[s[k]] = 0;
        }
        map[s[k]]++;
      }
    }
    var isOK = true;
    var key = Object.keys(map);
    for(var j = 0; j < key.length; j++){
      if(map[key[j]] % 2 != 0 || map[key[j]] >= N){
        isOK = false;
        break;
      }
    }
    output[i] = (isOK) ? "YES" : "NO";
  }
  myout(myconv(output, 9));
}

//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 = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    var map = {};
    for(var j = 0; j < N; j++){
      var s = next();
      for(var k = 0; k < s.length; k++){
        if(map[s[k]] == null){
          map[s[k]] = 0;
        }
        map[s[k]]++;
      }
    }
    var isOK = true;
    var key = Object.keys(map);
    for(var j = 0; j < key.length; j++){
      if(map[key[j]] % 2 != 0 || map[key[j]] < N){
        isOK = false;
        break;
      }
    }
    output[i] = (isOK) ? "YES" : "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();
    });

    main();
});

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

const readFile = () => {
    let input = ""
    let lastline = "";
    while(lastline !== undefined){
        lastline = readline();
        // console.log(lastline)
        input = input + "\n" + lastline;
    }
    return input;
}

const calculateAmountOfDistinctLetters = letters => {
    const letterMap = {};
    letters.split("").forEach(letter => {
        if(letterMap.hasOwnProperty(letter)){
            letterMap[letter]++;
        }else{
            letterMap[letter] = 1;
        }
    })
    return letterMap;
}

// const filename = 'input0.txt';
// const filename = process.argv[2];

function main() {
    const fileContents = readFile().split("\n")
    const totalTests = parseInt(fileContents[0]);

    fileContents.splice(0,1);

    const questions = [];

// console.log(fileContents);

    while(fileContents.length > 1){
        questions.push(fileContents.splice(1,parseInt(fileContents[0])))
        fileContents.splice(0,1);
    }

    friendlyFormatQuestions = questions.map(question => ({
        amountOfWords:question.length,
        words:question,
        allLettersTogether:question.join(""),
        amountOfDistinctLetters:calculateAmountOfDistinctLetters(question.join(""))
    }))

// console.log(friendlyFormatQuestions);

    console.log(friendlyFormatQuestions.map(question => {
        match = true;
        Object.keys(question.amountOfDistinctLetters).forEach(key => {
            if(question.amountOfDistinctLetters[key]%question.amountOfWords!==0){
                match = false;
            }
        })

        return match? "YES" : "NO";
    }).join("\n"));
}

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

let inputString = '';

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

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

    main(inputString);
});

const calculateAmountOfDistinctLetters = letters => {
    const letterMap = {};
    letters.split("").forEach(letter => {
        if(letterMap.hasOwnProperty(letter)){
            letterMap[letter]++;
        }else{
            letterMap[letter] = 1;
        }
    })
    return letterMap;
}

function main(fileContents) {
    console.log(fileContents);

    fileContents.splice(0,1);

    const questions = [];

    while(fileContents.length > 1){
        questions.push(fileContents.splice(1,parseInt(fileContents[0])))
        fileContents.splice(0,1);
    }

    friendlyFormatQuestions = questions.map(question => ({
        amountOfWords:question.length,
        words:question,
        allLettersTogether:question.join(""),
        amountOfDistinctLetters:calculateAmountOfDistinctLetters(question.join(""))
    }))

 console.log(friendlyFormatQuestions);

    console.log(friendlyFormatQuestions.map(question => {
        match = true;
        Object.keys(question.amountOfDistinctLetters).forEach(key => {
            if(question.amountOfDistinctLetters[key]%question.amountOfWords!==0){
                match = false;
            }
        })

        return match? "YES" : "NO";
    }).join("\n"));
}


You're given an integer $$$n$$$. For every integer $$$i$$$ from $$$2$$$ to $$$n$$$, assign a positive integer $$$a_i$$$ such that the following conditions hold:  For any pair of integers $$$(i,j)$$$, if $$$i$$$ and $$$j$$$ are coprime, $$$a_i \neq a_j$$$.  The maximal value of all $$$a_i$$$ should be minimized (that is, as small as possible). A pair of integers is called coprime if their greatest common divisor is $$$1$$$.

The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$).

Print $$$n-1$$$ integers, $$$a_2$$$, $$$a_3$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \leq a_i \leq n$$$).  If there are multiple solutions, print any of them.

NoteIn the first example, notice that $$$3$$$ and $$$4$$$ are coprime, so $$$a_3 \neq a_4$$$. Also, notice that $$$a=[1,2,3]$$$ satisfies the first condition, but it's not a correct answer because its maximal value is $$$3$$$.

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    };

    var n = read.number();
    var res = '';
    var idx = [];
    var arr = [];
    var index = 1;
    for(var i = 2 ; i <= n; i++) {
        var c = true;
        for(var j = 2; j <= Math.floor(i / 2); j++) {
            if(i % j === 0) {
                c = false;
                break;
            }
        }
        if(c) {
            var tmp = i;
            idx[tmp - 2] = index;
            while(tmp + i <= n) {
                tmp += i;
                idx[tmp - 2] = index;
            }
            index++;
        }
    }

    print(idx.join(' '));
}());

var row = readline().split(" ").map(function(x) { return parseInt(x); });
var n = row[0];

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

var color = 1;
var res = [];

for(var i = 0; i <= n ; i++) {
    res.push(0);
}

for(var i = 2; i <= n ; i++) {
    var flag = false;
    for(var j = i; j <= n; j+=i) {
        if(res[j] == 0) {
            res[j] = color;
            flag = true;
        }
    }
    if(flag) color++;
}

write(res.slice(2).join(" "));


There is a matrix A of size x × y filled with integers. For every ,  Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i < x;  (i, j + 1) — only if j < y;  (i - 1, j) — only if i > 1;  (i, j - 1) — only if j > 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?

The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.

If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.

NoteThe matrix and the path on it in the first test looks like this:  Also there exist multiple correct answers for both the first and the third examples.

// First, scan the numbers, memo the first diff that |n - adjN| > 1, if there is another |n - adjN| different than the memo, it's 'NO'
// If there is no such memo, than YES & 10 ** 9
// The memo is y, when the diff is +-1, it's 'NO' when ((n - 1) % y === 0) && ((adjN - 1) % y === (y - 1)) or the other side of the edge happens.
readline();
var numbers = readline().split(' ').map(Number);
var memo;
var done = false;

for (var i = 0; i < (numbers.length - 1); i++) {
  var diff = Math.abs(numbers[i] - numbers[i + 1]);
  if (diff > 1) {
    if (!memo) memo = diff;
    else if (memo != diff) {
      print('NO');
      done = true;
      break;
    }
  }
}
if (!memo) {
  memo = Math.pow(10, 9);
}
if (!done) {
  for (var i = 0; i < (numbers.length - 1); i++) {
    var diff = Math.abs(numbers[i] - numbers[i + 1]);
    if (diff === 1) {
      var condition1 = ((numbers[i] - 1) % memo) === 0;
      var condition2 = numbers[i] > numbers[i + 1];
      var condition3 = ((numbers[i] - 1) % memo) === (memo - 1);
      var condition4 = numbers[i] < numbers[i + 1];
      if ((condition1 && condition2) || (condition3 && condition4)) {
        print('NO');
        done = true;
        break;
      }
    }
    if (diff === 0) {
      print('NO');
      done = true;
      break;
    }
  }
}
if (!done) {
  print('YES');
  var max = Math.max(...numbers);
  print(`${Math.ceil(max / memo)} ${memo}`);
}

// First, scan the numbers, memo the first diff that |n - adjN| > 1, if there is another |n - adjN| different than the memo, it's 'NO'
// If there is no such memo, than YES & 10 ** 9
// The memo is y, when the diff is +-1, it's 'NO' when ((n - 1) % y === 0) && ((adjN - 1) % y === (y - 1)) or the other side of the edge happens.
readline();
var numbers = readline().split(' ').map(Number);
var memo;
var done = false;

for (var i = 0; i < (numbers.length - 1); i++) {
  var diff = Math.abs(numbers[i] - numbers[i + 1]);
  if (diff > 1) {
    if (!memo) memo = diff;
    else if (memo != diff) {
      print('NO');
      done = true;
      break;
    }
  }
}
if (!memo) {
  done = true;
  print('YES');
  print(`1 ${Math.pow(10, 9)}`);
}
if (!done) {
  for (var i = 0; i < (numbers.length - 1); i++) {
    var diff = Math.abs(numbers[i] - numbers[i + 1]);
    if (diff === 1) {
      var condition1 = ((numbers[i] - 1) % memo) === 0;
      var condition2 = numbers[i] > numbers[i + 1];
      var condition3 = ((numbers[i] - 1) % memo) === (memo - 1);
      var condition4 = numbers[i] < numbers[i + 1];
      if ((condition1 && condition2) || (condition3 && condition4)) {
        print('NO');
        done = true;
        break;
      }
    }
    if (diff === 0) {
      print('NO');
      done = true;
      break;
    }
  }
}
if (!done) {
  print('YES');
  var max = Math.max(...numbers);
  print(`${Math.ceil(max / memo)} ${memo}`);
}

// First, scan the numbers, memo the first diff that |n - adjN| > 1, if there is another |n - adjN| different than the memo, it's 'NO'
// If there is no such memo, than YES & 10 ** 9
// The memo is y, when the diff is +-1, it's 'NO' when ((n - 1) % y === 0) && ((adjN - 1) % y === (y - 1)) or the other side of the edge happens.
readline();
var numbers = readline().split(' ').map(Number);
var memo;
var done = false;
for (var i = 0; i < (numbers.length - 1); i++) {
  var diff = Math.abs(numbers[i] - numbers[i + 1]);
  if (diff > 1) {
    if (!memo) memo = diff;
    else if (memo != diff) {
      print('NO');
      done = true;
      break;
    }
  }
}
if (!done) {
  for (var i = 0; i < (numbers.length - 1); i++) {
    var diff = Math.abs(numbers[i] - numbers[i + 1]);
    if (diff === 1) {
      var condition1 = (numbers[i] - 1) % memo === 0;
      var condition2 = numbers[i] > numbers[i + 1];
      var condition3 = (numbers[i] - 1) % memo === memo - 1;
      var condition4 = numbers[i] < numbers[i + 1];
      if ((condition1 && condition2) || (condition3 && condition4)) {
        print('NO');
        done = true;
        break;
      }
    }
  }
}
if (!done) {
  print('YES');
  var max = Math.max(...numbers);
  print(`${Math.ceil(max / memo)} ${memo}`);
}


The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.

The first input line contains an integer n (2 ≤ n ≤ 100). The second line contains n - 1 integers di (1 ≤ di ≤ 100). The third input line contains two integers a and b (1 ≤ a < b ≤ n). The numbers on the lines are space-separated.

Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.

var n=+readline();
var d=readline().split(' ').map(function(v){return +v;});
var l=readline().split(' ');
var a=+l[0];
var b=+l[1];

var ans=0;
for(var i=a-1; i<b-1; i++){
	ans+=d[i];
}
print(ans);

;(function () {

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

	print( p.slice(a, b).reduce(function (p, e) { return p + e; }, 0) );

}).call(this)

'use strict'

let N = +readline()
let zs = readline().split(' ').map(v => parseInt(v))
let v = readline().split(' ').map(v => parseInt(v))

let ys = 0
for (let i = v[0] - 1; i < v[1] - 1; i++) {
  ys += zs[i]
}

print(ys)

var n = readline();
var d = readline();
var ab = readline();
d = d.split(" ");
ab = ab.split(" ");
var sum = 0;
for(var i = parseInt(ab[0])-1; i < parseInt(ab[1])-1; ++i)
{
    sum += parseInt(d[i]);
}
print(sum);

var n= readline();
var ranks=readline();
var needed=readline();
ranks=ranks.split(" ");
needed=needed.split(" ");
var sum=0;
for( var i = parseInt(needed[0])-1; i< parseInt(needed[1])-1;i++)
{
	sum+=parseInt(ranks[i]);
}
print(sum);

var n = parseInt(readline());
var d = readline().split(' ').map(function (a) {return parseInt(a)});
var input = readline().split(' ').map(function (a) {return parseInt(a)});
var a = input[0];
var b = input[1];
var sum = 0;

for (var i = a; i < b; i++) {
	sum += d[i-1];
}

print(sum);

var n = +readline();
var d = readline().split(' ').map(Number);
var z = readline().split(' ').map(Number);
var a = z[0];
var b = z[1];

var years = 0;

while(a < b) {
  years += d[a++ - 1];
}

print(years);

const readline = require('readline');

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

var n,cont=[],indicator=0;
rl.on('line', (input) => {
   if(indicator==0){
       n=parseInt(input);
       indicator++;
   }
   else if(indicator==1){
       cont=input.split(" ").map(item=>parseInt(item));
       indicator++;
   }
   else{
       let  temp=input.split(" ").map(item=>parseInt(item));
       let nowR=temp[0];
       let needR=temp[1];
       let ans=0;
       for(let i=nowR-1;i<needR-1;i++)
             ans+=cont[i];
        console.log(ans);
        rl.close();
   }

  });

readline = require('readline')
let stdinInput = '';

// //file
//     var fs = require('fs');
//    const inputfile = '_in.txt';
//    const outputfile = '_out.txt';
//    fs.writeFileSync(outputfile, '');
//    var myInterface = readline.createInterface({
//      input: fs.createReadStream(inputfile),
//    });
//    myInterface.on('line', function (line) {
//       stdinInput += line+'\n';
//     }).on('close', () => {
//            main();
//         process.exit(0);
//     })
   /*
   *  Api Scanner
   */
  class Scanner {
    constructor() {
      this.index = -1;
      this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
    }

    nextLine() {
      this.index += 1;
      return this.lines[this.index].trim();
    }
    nextArray(fn) {
      const array = this.nextLine().split(' ');
      return fn === String ? array : array.map(fn);
    }

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

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

var n;
function main() {
    const is = new Scanner();

    const n = is.nextArray(Number);
    const a = is.nextArray(Number);
    const [dau, cuoi] = is.nextArray(Number);
    // console.log(a);

    let kq=0;
    	for(i=dau-1; i<Math.min(cuoi-1, n); i++)
    	{
    		kq+=a[i];
    	}
    	console.log("%d", kq);

}

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

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

  if (c === 1) {
    years = d.split(' ').map(Number);
    c++;
    return;
  }

  const [start, end] = d.split(' ').map(Number);
  let ans = 0;

  for (let i = start; i < end; i++) {
    ans += years[i - 1];
  }

  console.log(ans);

  c++;
});

const n = readline().split('');
const d = readline().split('');
print(d);

const n = readline();
const d = readline();
const t = readline();

print(t);

var n = +readline();
var d = readline().split(' ').map(Number);
var z = readline().split(' ').map(Number);
var a = z[0];
var b = z[1];

print(a);

const n = readline();
const d = readline();

print(d);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] < t[1]) {
  years=5;
  t[0]+=1;
}

print(t[0],t[1]);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] < t[1]) {
  years += d[t[0]-1];
  t[0]++;
}

print(years);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] >= t[2]) {
  years+= d[t[0]-1];
  t[0]+=1;
}

print(years);

var n = readline();
var d = readline();
var t = readline().split(' ').map(v => +v);

var years = 0;

while(t[0] < t[1]) {
  years=5;
  t[0]+=1;
}

print(t);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] < t[1]) {
  years+=d[t[0]-1];
  t[0]++;
}

print(d[t[0]-1]);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] < t[1]) {
  years=5;
  t[0]+=1;
}

print(t);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] >= t[2]) {
  years+= d[t[0]-1];
  t[0]+=1;
}

print(typeof t[2]);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] < t[1]) {
  years+=d[t[0]-1];
  print(years);
  t[0]+=1;
}

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] <= t[1]) {
  years += d[t[0]-1];
  t[0]++;
}

print(years);

const n = readline();
const d = readline();
print(n);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] < t[1]) {
  years=5;
  t[0]+=1;
}

print(t[1]);

var n = readline();
var d = readline();
var t = readline().split('');

var years = 0;

while(t[0] < t[1]) {
  years=5;
  t[0]+=1;
}

print(t[0]);
print(t[1]);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] < t[1]) {
  years += d[t[0]-1];
  t[0]++;
}

print(t[0]);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] < t[1]) {
  years=5;
  t[0]+=1;
}

print(years);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] < t[1]) {
  years=5;
  t[0]+=1;
}

print(t[0]);
print(t[1]);

var n = readline();
var d = readline();
var t = readline().split('');

var years = 0;

while(t[0] < t[1]) {
  years=5;
  t[0]+=1;
}

print(t);
print(t[1]);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] < t[1]) {
  years=5;
  t[0]+=1;
}

print(t[0] < t[1]);

var n = readline();
var d = readline();
var t = readline();

var years = 0;

while(t[0] < t[1]) {
  years+=d[t[0]-1];
  t[0]+=1;
}

print(years);

const input = readline().split('');
print(input);

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

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

  if (c === 1) {
    years = d.split(' ').map(Number);
    c++;
    return;
  }

  const [start, end] = d.split(' ').map(Number);
  let ans = 0;
  let idx = 0;

  for (let i = start; i < end; i++) {
    ans += years[idx];
    idx++;
  }

  console.log(ans);

  c++;
});


Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?

The first input line contains integer n (1 ≤ n ≤ 105) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.

Output the amount of ways to cut the stripe into two non-empty pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.

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

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

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

function main() {
	var n = parseInt(readline());
	var arr = tokenizeIntegers(readline());

	var totals = [arr[0]];
	for (var i = 1; i < n; i += 1) {
		totals[i] = totals[i-1] + arr[i];
	}

	var grandTotal = totals[n-1];
	var count = 0;
	for (var i = 0; i < n-1; i += 1) {
		if (grandTotal-totals[i] == totals[i]) {
			count += 1;
		}
	}

	print(count);
}

main();

function somaAcolumada(array) {
    var novoArray = new Array(array.length);
    novoArray[0] = array[0];
    for (var i = 1 ; i < array.length ; i++) {
        novoArray[i] = array[i] + novoArray[i-1];
    }
    return novoArray;
}

var N = parseInt(readline());
var quadrados = readline().split(" ").map(function(n) { return parseInt(n)});

var numeroPossibilidades = 0;
var soma = somaAcolumada(quadrados);
var somaTotal = soma[quadrados.length - 1];

for(var i = 0 ; i < N - 1 ; i++) {
    var valorAtual = soma[i];
    var somaOutrosValores = somaTotal - soma[i];
    if (valorAtual === somaOutrosValores) {
        numeroPossibilidades ++;
    }
}

print(numeroPossibilidades);


Bajtek, known for his unusual gifts, recently got an integer array $$$x_0, x_1, \ldots, x_{k-1}$$$.Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array $$$a$$$ of length $$$n + 1$$$. As a formal description of $$$a$$$ says, $$$a_0 = 0$$$ and for all other $$$i$$$ ($$$1 \le i \le n$$$) $$$a_i = x_{(i-1)\bmod k} + a_{i-1}$$$, where $$$p \bmod q$$$ denotes the remainder of division $$$p$$$ by $$$q$$$.For example, if the $$$x = [1, 2, 3]$$$ and $$$n = 5$$$, then:  $$$a_0 = 0$$$,  $$$a_1 = x_{0\bmod 3}+a_0=x_0+0=1$$$,  $$$a_2 = x_{1\bmod 3}+a_1=x_1+1=3$$$,  $$$a_3 = x_{2\bmod 3}+a_2=x_2+3=6$$$,  $$$a_4 = x_{3\bmod 3}+a_3=x_0+6=7$$$,  $$$a_5 = x_{4\bmod 3}+a_4=x_1+7=9$$$. So, if the $$$x = [1, 2, 3]$$$ and $$$n = 5$$$, then $$$a = [0, 1, 3, 6, 7, 9]$$$.Now the boy hopes that he will be able to restore $$$x$$$ from $$$a$$$! Knowing that $$$1 \le k \le n$$$, help him and find all possible values of $$$k$$$ — possible lengths of the lost array.

The first line contains exactly one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the length of the array $$$a$$$, excluding the element $$$a_0$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^6$$$). Note that $$$a_0$$$ is always $$$0$$$ and is not given in the input.

The first line of the output should contain one integer $$$l$$$ denoting the number of correct lengths of the lost array. The second line of the output should contain $$$l$$$ integers — possible lengths of the lost array in increasing order.

NoteIn the first example, any $$$k$$$ is suitable, since $$$a$$$ is an arithmetic progression.Possible arrays $$$x$$$:  $$$[1]$$$ $$$[1, 1]$$$ $$$[1, 1, 1]$$$ $$$[1, 1, 1, 1]$$$  $$$[1, 1, 1, 1, 1]$$$In the second example, Bajtek's array can have three or five elements.Possible arrays $$$x$$$:  $$$[1, 2, 2]$$$ $$$[1, 2, 2, 1, 2]$$$For example, $$$k = 4$$$ is bad, since it leads to $$$6 + x_0 = 8$$$ and $$$0 + x_0 = 1$$$, which is an obvious contradiction.In the third example, only $$$k = n$$$ is good.Array $$$[1, 4, -2]$$$ satisfies the requirements.Note that $$$x_i$$$ may be negative.

'use strict';

const n = Number(readline());
const a = readline().split(' ').map(Number);
const possible_lengths = []

const try_length = function(length) {
    const x = []
    for (let i = 0; i < n; i++) {
        const value = a[i] - ((i > 0) ? a[i - 1] : 0);
        if (i < length) {
            x.push(value);
        } else if (x[i % length] != value) {
            return false;
        }
    }
    return true;
}

for (let possible_length = 1; possible_length <= n; possible_length++) {
    if (try_length(possible_length)) {
        possible_lengths.push(possible_length);
    }
}

print(possible_lengths.length);

print(possible_lengths.join(' '));

var aLength = +readline()
var a = readline().split(' ').map(v=>+v)
a.unshift(0)

var xLengths = []

for(var xLength = 1; xLength <= aLength; xLength++) {
   var xSum = a[xLength]
   var res = true
   for(var y = xLength; y > 0; y--) {
      var aValue = a[y]
      for(var j = y + xLength; j <= aLength; j+=xLength) {
         if(a[j] - aValue !== xSum) {
            res = false;
            break
         }
         aValue = a[j]
      }
      if(!res) break
   }

   if(res) {
      xLengths.push(xLength)
   }
}

print(xLengths.length)
print(xLengths.join(' '))


Polycarp is practicing his problem solving skill. He has a list of $$$n$$$ problems with difficulties $$$a_1, a_2, \dots, a_n$$$, respectively. His plan is to practice for exactly $$$k$$$ days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all $$$n$$$ problems in exactly $$$k$$$ days.Thus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in $$$k$$$ days he will solve all the $$$n$$$ problems.The profit of the $$$j$$$-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the $$$j$$$-th day (i.e. if he solves problems with indices from $$$l$$$ to $$$r$$$ during a day, then the profit of the day is $$$\max\limits_{l \le i \le r}a_i$$$). The total profit of his practice is the sum of the profits over all $$$k$$$ days of his practice.You want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all $$$n$$$ problems between $$$k$$$ days satisfying the conditions above in such a way, that the total profit is maximum.For example, if $$$n = 8, k = 3$$$ and $$$a = [5, 4, 2, 6, 5, 1, 9, 2]$$$, one of the possible distributions with maximum total profit is: $$$[5, 4, 2], [6, 5], [1, 9, 2]$$$. Here the total profit equals $$$5 + 6 + 9 = 20$$$.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the number of problems and the number of days, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$) — difficulties of problems in Polycarp's list, in the order they are placed in the list (i.e. in the order Polycarp will solve them).

In the first line of the output print the maximum possible total profit. In the second line print exactly $$$k$$$ positive integers $$$t_1, t_2, \dots, t_k$$$ ($$$t_1 + t_2 + \dots + t_k$$$ must equal $$$n$$$), where $$$t_j$$$ means the number of problems Polycarp will solve during the $$$j$$$-th day in order to achieve the maximum possible total profit of his practice. If there are many possible answers, you may print any of them.

NoteThe first example is described in the problem statement.In the second example there is only one possible distribution.In the third example the best answer is to distribute problems in the following way: $$$[1, 2000], [2000, 2]$$$. The total profit of this distribution is $$$2000 + 2000 = 4000$$$.

function main() {
  const is = new Scanner();
  const [n, k] = is.nextArray().map(Number);
  const problems = is.nextArray().map(Number);

  const copy = problems.slice();
  copy.sort((a, b) => a - b).reverse();

  let totalProfit = 0, index;
  const intervals = [];
  for (let i = 0; i < k; i += 1) {
    totalProfit += copy[i];
    index = problems.indexOf(copy[i]);
    intervals.push(index);
    problems[index] = -1;
  }

  intervals.push(n);
  intervals.unshift(-1);
  intervals.sort((a, b) => a - b);

  console.log(totalProfit);
  for (let i = 1; i < intervals.length - 1; i += 1) {
    intervals[i] = intervals[i + 1] - 1;
    process.stdout.write(`${String(intervals[i] - intervals[i - 1])} `);
  }
  console.log();
}

/*
 *  Api Scanner
 */

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

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

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

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

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

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

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

var line = readline ();
line = line.trim ().split ( ' ' );
var n, k;
n = (+ line [ 0 ]);
k = (+ line [ 1 ]);
var a = readline ();
a = a.trim ().split ( ' ' );
var i, srt = [ ];
for ( i = 0; i < n; i ++ ) {
    a [ i ] = Number ( a [ i ] );
    srt [ i ] = a [ i ];
}
srt.sort ( function ( a, b ) { return b - a; } );
var o = { };
var sum = 0;
for ( i = 0; i < k; i ++ ) {
    if ( ! ( srt [ i ] in o ) ) o [ srt [ i ] ] = 0;
    o [ srt [ i ] ] ++;
    sum += srt [ i ];
}
var prev = 0;
var ans = [ ];
var other = 0;
for ( i = 0; i < n; i ++ ) {
    if ( a [ i ] in o ) {
        ans.push ( i - prev + 1 );
        other += (i - prev + 1);
        o [ a [ i ] ] --;
        if ( o [ a [ i ] ] == 0 ) delete o [ a [ i ] ];
        prev = i + 1;
    }
}
ans [ ans.length - 1 ] += n - other;
print ( sum );
print ( ans.join ( ' ' ) );

var line = readline().split(' ').map(Number);
var n = line[0]; // Number of problems
var k = line[1]; // Number of days
var difProblems = readline().split(' ').map(Number);

var maxInd = [];
var ans = 0;

for (var i = 0; i < k; i++) {
    var max = difProblems[0];
    var index = 0;
    for (var j = 0; j < n; j++) {
        if (max < difProblems[j]) {
            max = difProblems[j];
            index = j;
        }
    }
    ans += max;
    difProblems[index] = 0;
    maxInd[i] = index;
}

maxInd.sort((a, b) => a < b ? -1 : 1);

print(ans);
if (maxInd.length === 1) {
    print(n);
} else {
    var problemsDay = [maxInd[0]+1];
    for (var i = 1; i < maxInd.length - 1; i++) {
        problemsDay.push(maxInd[i] - maxInd[i-1]);
    }

    problemsDay.push(n - maxInd[k-2] - 1);
    print(problemsDay.join(' '));
}

var l = readline()

var n = parseInt(l.split(' ')[0], 10)
var k = parseInt(l.split(' ')[1], 10)
var a = readline().split(' ').map(v => parseInt(v, 10));
var b = a.map((v, i) => {
    return {
        value: v,
        index: i,
    };
});

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

b = b.slice(0, k);

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

print(b.map(v => v.value).reduce((a, b) => a + b, 0))
b = b.map(v => v.index);

var ans = '';

function add(v) {
    ans += v + ' ';
}

var last = -1;

for (var i = 0; i < k - 1; i++) {
    add(b[i] - last);
    last = b[i];
}
add(n - 1 - last)
print(ans)

function main() {
  const is = new Scanner();
  const [n, k] = is.nextArray().map(Number);
  const problems = is.nextArray().map(Number);

  const copy = problems.slice();
  copy.sort((a, b) => a - b).reverse();

  let totalProfit = 0, index;
  const intervals = [];
  for (let i = 0; i < k; i += 1) {
    totalProfit += copy[i];
    index = problems.indexOf(copy[i]);
    intervals.push(index);
    problems[index] = -1;
  }

  intervals.push(n);
  intervals.unshift(-1);
  intervals.sort();

  console.log(totalProfit);
  for (let i = 1; i < intervals.length - 1; i += 1) {
    intervals[i] = intervals[i + 1] - 1;
    process.stdout.write(`${String(Math.abs(intervals[i] - intervals[i - 1]))} `);
  }
  console.log();
}

/*
 *  Api Scanner
 */

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

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

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

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

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

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

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

function main() {
  const is = new Scanner();
  const [n, k] = is.nextArray().map(Number);
  const problems = is.nextArray().map(Number);

  const copy = problems.slice();
  copy.sort((a, b) => a - b).reverse();

  let totalProfit = 0, index;
  const intervals = [];
  for (let i = 0; i < k; i += 1) {
    totalProfit += copy[i];
    index = problems.indexOf(copy[i]);
    intervals.push(index);
    problems[index] = 0;
  }

  intervals.push(n);
  intervals.sort();
  intervals.unshift(-1);

  for (let i = 1; i < intervals.length - 1; i += 1) {
    intervals[i] = intervals[i + 1] - 1;
  }

  console.log(totalProfit);
  for (let i = 1; i < intervals.length - 1; i += 1) {
    process.stdout.write(`${String((intervals[i] - intervals[i - 1]))} `);
  }
  console.log();
}

/*
 *  Api Scanner
 */

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

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

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

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

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

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

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

function main() {
  const is = new Scanner();
  const [n, k] = is.nextArray().map(Number);
  const problems = is.nextArray().map(Number);

  const copy = problems.slice();
  copy.sort((a, b) => a - b).reverse();

  let totalProfit = 0, index;
  const intervals = [];
  for (let i = 0; i < k; i += 1) {
    totalProfit += copy[i];
    index = problems.indexOf(copy[i]);
    intervals.push(index);
    problems[index] = -1;
  }

  intervals.push(n);
  intervals.unshift(-1);
  intervals.sort();

  for (let i = 1; i < intervals.length - 1; i += 1) {
    intervals[i] = intervals[i + 1] - 1;
  }

  console.log(totalProfit);
  for (let i = 1; i < intervals.length - 1; i += 1) {
    process.stdout.write(`${String(intervals[i] - intervals[i - 1])} `);
  }
  console.log();
}

/*
 *  Api Scanner
 */

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

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

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

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

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

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

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

function main() {
  const is = new Scanner();
  const [n, k] = is.nextArray().map(Number);
  const problems = is.nextArray().map(Number);

  const copy = problems.slice();
  copy.sort((a, b) => a - b).reverse();

  let totalProfit = 0, index;
  const intervals = [];
  for (let i = 0; i < k; i += 1) {
    totalProfit += copy[i];
    index = problems.indexOf(copy[i]);
    intervals.push(index);
    problems[index] = 0;
  }

  intervals.push(n);
  intervals.sort();
  intervals[0] = 0;

  console.log(totalProfit);
  for (let i = 1; i < intervals.length; i += 1) {
    process.stdout.write(`${String(intervals[i] - intervals[i - 1])} `);
  }
  console.log();
}

/*
 *  Api Scanner
 */

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

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

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

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

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

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

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

var line = readline().split(' ').map(Number);
var n = line[0]; // Number of problems
var k = line[1]; // Number of days
var difProblems = readline().split(' ').map(Number);

var indexes = [];
var profit = 0;

for (var i = 0; i < k; i++) {
    var max = difProblems[0];
    var index = 0;
    for (var j = 0; j < n; j++) {
        if (max < difProblems[j]) {
            max = difProblems[j];
            index = j;
        }
    }
    profit += max;
    difProblems[index] = 0;
    indexes[i] = index;
}

indexes.sort((a, b) => a < b ? -1 : 1);

print(profit);
if (indexes.length === 1) {
    print(n);
} else {
    var problemsDay = [indexes[0]+1];
    for (var i = 1; i < indexes.length - 1; i++) {
        problemsDay.push(indexes[i] - indexes[i-1]);
    }

    problemsDay.push(n - indexes[k-1]);
    print(problemsDay.join(' '));
}

var line = readline().split(' ').map(Number);
var n = line[0]; // Number of problems
var k = line[1]; // Number of days
var difProblems = readline().split(' ').map(Number);

var indexes = [];
var profit = 0;

for (var i = 0; i < k; i++) {
    var max = difProblems[0];
    var index = 0;
    for (var j = 0; j < n; j++) {
        if (max < difProblems[j]) {
            max = difProblems[j];
            index = j;
        }
    }
    profit += max;
    difProblems[index] = 0;
    indexes[i] = index;
}

indexes.sort((a, b) => a < b ? -1 : 1);

print(profit);
if (indexes.length === 1) {
    print(n);
} else {
    var problemsDay = [indexes[0]+1];
    for (var i = 1; i < indexes.length - 1; i++) {
        problemsDay.push(indexes[i] - indexes[i-1]);
    }

    problemsDay.push(n - indexes[k-1]);
    print(problemsDay);
}

var l = readline()

var n = parseInt(l.split(' ')[0], 10)
var k = parseInt(l.split(' ')[1], 10)
var a = readline().split(' ').map(v => parseInt(v, 10));
var b = a.map((v, i) => {
    return {
        value: v,
        index: i,
    };
});

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

b = b.slice(0, k);

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

print(b.map(v => v.value).reduce((a, b) => a + b, 0))
b = b.map(v => v.index);

var ans = '';

function add(v) {
    ans += v + ' ';
}

var last = -1;

for (var i = 0; i < k - 1; i++) {
    add(b[i] - last);
    last = b[i];
}
add(b[k-1] - last)
print(ans)

var l = readline()

var n = parseInt(l.split(' ')[0], 10)
var k = parseInt(l.split(' ')[1], 10)
var a = readline().split(' ').map(v => parseInt(v, 10));
var b = a.map((v, i) => {
    return {
        value: v,
        index: i,
    };
});

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

b = b.slice(0, k);

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

b = b.map(v => v.index);
var ans = '';

function add(v) {
    ans += v + ' ';
}

var last = -1;

for (var i = 0; i < k - 1; i++) {
    add(b[i] - last);
    last = b[i];
}
add(n - 1 - last)
print(ans)


This is the easy version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$3n$$$ operations. It can be proved that it is always possible.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 1000$$$)  — the length of the binary strings. The next two lines contain two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$1000$$$.

For each test case, output an integer $$$k$$$ ($$$0\le k\le 3n$$$), followed by $$$k$$$ integers $$$p_1,\ldots,p_k$$$ ($$$1\le p_i\le n$$$). Here $$$k$$$ is the number of operations you use and $$$p_i$$$ is the length of the prefix you flip in the $$$i$$$-th operation.

NoteIn the first test case, we have $$$01\to 11\to 00\to 10$$$.In the second test case, we have $$$01011\to 00101\to 11101\to 01000\to 10100\to 00100\to 11100$$$.In the third test case, the strings are already the same. Another solution is to flip the prefix of length $$$2$$$, which will leave $$$a$$$ unchanged.

function not(c) {
   if (c === '1') {
      return '0';
   }
   return '1';
}

function solve() {
   var n = Number(read());
   var a = Array.from(read());
   var b = Array.from(read());
   var ans = [];

   function f(index) {
      var res = a.slice();
      for (var i = 0; i <= index; i++) {
         res[i] = not(a[index - i]);
      }
      a = res;
   }

   for (var i = n - 1; i >= 0; i--) {
      if (a[i] === b[i]) {
         continue;
      }
      if (a[0] !== b[i]) {
         ans.push(i + 1);
         f(i);
         continue;
      }
      var j = i - 1;
      while(a[j] !== b[i]) {
         j--;
      }
      ans.push(j + 1);
      f(j);
      ans.push(i + 1);
      f(i);
   }
   write(ans.length + ' ' + ans.join(' '));
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', init);
   }
} else {
   init();
}

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

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const t = Number(readLine())
    for (let _i = 0; _i < t; _i++) {
        const n = Number(readLine())
        let a = Array.from(readLine()).map(Number)
        const b = Array.from(readLine()).map(Number)
        const results = []
        for (let i = n - 1; i >= 0; i--) {
          if (a[i] === b[i]) {
            continue
          }
          if (i === 0) {
            if (a[0] !== b[0]) {
              results.push(1)
            }
            continue
          }
          if (a[0] === b[i]) {
            results.push(1)
            a[0] = (a[0] + 1) % 2
          }
          results.push(i + 1)
          a = a.slice(0, i + 1).map(v => (v + 1) % 2).reverse()
        }
      console.log(`${results.length}${results.length ? ' ' + results.join(' ') : ''}`)
    }
}

'use strict';

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

let inputString = ''
let currentLine = 0

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

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

    main()
})

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

String.prototype.count = function(c) {
  let result = 0
  for(let i = 0; i < this.length; i++)
    if(this[i] == c)
      result++
  return result
}

function nextChar(c) {
  return String.fromCharCode(c.charCodeAt(0) + 1)
}

function main() {
  let t = readLine()
  t = parseInt(t)

  while(t--) {
    let n = parseInt(readLine())
    let [a, b] = [readLine(), readLine()]

    let res = []
    if (a[0] != b[0])
      res.push(1)

    for (let i = 1; i < a.length; ++i) {
      if (a[i] != b[i]) {
        res.push(i+1)
        res.push(1)
        res.push(i+1)
      }
    }
    console.log(res.length, ...res)
  }
}

'use strict';

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

let inputString = ''
let currentLine = 0

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

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

    main()
})

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

String.prototype.count = function(c) {
  let result = 0
  for(let i = 0; i < this.length; i++)
    if(this[i] == c)
      result++
  return result
}

function nextChar(c) {
  return String.fromCharCode(c.charCodeAt(0) + 1)
}

function main() {
  let t = readLine()
  t = parseInt(t)

  while(t--) {
    let n = parseInt(readLine().trim())
    let [a, b] = [readLine().trim(), readLine().trim()]

    a += '0'
    b += '0'

    let [ops1, ops2] = [[], []]

    for (let i = 1; i <= n; ++i) {
      if (a[i] !== a[i-1])
        ops1.push(i)

      if (b[i] !== b[i-1])
        ops2.push(i)
    }

    ops2.reverse()
    console.log(ops1.length + ops2.length, ...ops1.concat(ops2))
  }
}

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

    C();
});

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

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

    return a;
}

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

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,m] = ti(readline().split(' '));
        let a = ti(readline().split(' '));
        let b = ti(readline().split(' '));

        let map = new Array(1000+10);

        for(let i = 0; i < a.length; i++)
            map[a[i]] = 1;

        let isFound = false;
        for(let i = 0; i < b.length; i++){
            if(map[b[i]] === 1){
                console.log('YES');
                console.log(1, b[i]);
                isFound = true;
                break;
            }
        }

        if(!isFound)
            console.log('NO');
    }
}

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

        let turn = 0;
        for(let i = 0; i < a.length; i++){
            if(i === n-1){
                console.log(turn === 0 ? 'First' : 'Second');
            }
            else if(a[i] === 1){
                turn = turn === 0 ? 1 : 0;
            }else{
                console.log(turn === 0 ? 'First' : 'Second');
                break;
            }
        }
    }
}

function C(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = readline();
        let b = readline();

        let p1 = 0;
        let p2 = n-1;

        let ans = [];
        let count = 0;
        for(let i = 0; i < n; i++){
            let x = '-1';
            if(i % 2 === 0){
                x = count % 2 === 0 ? a.charAt(p1) : (a.charAt(p1) === '0' ? '1' : '0');
                p1++;
            }else{
                x = count % 2 === 0 ? a.charAt(p2) : (a.charAt(p2) === '0' ? '1' : '0');
                p2--;
            }

            if(x !== b.charAt(n-i-1)){
                count += 1;
                ans.push(n-i);
            }else{
                if(n-i !== 1){
                    ans.push(1);
                    ans.push(n-i);
                    count++;
                }
            }
        }

        console.log(ans.length);
        for(let i = 0; i < ans.length; i++)
            console.log(ans[i]);
    }
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const t = Number(readLine())
    for (let _i = 0; _i < t; _i++) {
        const n = Number(readLine())
        let a = Array.from(readLine()).map(Number)
        const b = Array.from(readLine()).map(Number)
        const results = []
        for (let i = n - 1; i >= 0; i--) {
          if (a[i] === b[i]) {
            continue
          }
          if (i === 0) {
            if (a[0] !== b[0]) {
              results.push(1)
            }
            continue
          }
          if (a[0] === b[i]) {
            results.push(1)
            a[0] = (a[0] + 1) % 2
          }
          results.push(i + 1)
          a = a.slice(0, i).map(v => (v + 1) % 2).reverse()
        }
      console.log(`${results.length}${results.length ? ' ' + results.join(' ') : ''}`)
    }
}

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

let inputString = '';
let currentLine = 0;

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

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

    C();
});

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

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

    return a;
}

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

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,m] = ti(readline().split(' '));
        let a = ti(readline().split(' '));
        let b = ti(readline().split(' '));

        let map = new Array(1000+10);

        for(let i = 0; i < a.length; i++)
            map[a[i]] = 1;

        let isFound = false;
        for(let i = 0; i < b.length; i++){
            if(map[b[i]] === 1){
                console.log('YES');
                console.log(1, b[i]);
                isFound = true;
                break;
            }
        }

        if(!isFound)
            console.log('NO');
    }
}

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

        let turn = 0;
        for(let i = 0; i < a.length; i++){
            if(i === n-1){
                console.log(turn === 0 ? 'First' : 'Second');
            }
            else if(a[i] === 1){
                turn = turn === 0 ? 1 : 0;
            }else{
                console.log(turn === 0 ? 'First' : 'Second');
                break;
            }
        }
    }
}

function C(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = readline();
        let b = readline();

        let p1 = 0;
        let p2 = n-1;

        let ans = [];
        let count = 0;
        for(let i = 0; i < n; i++){
            let x = '-1';
            if(i % 2 === 0){
                x = count % 2 === 0 ? a.charAt(p1) : (a.charAt(p1) === '0' ? '1' : '0');
                p1++;
            }else{
                x = count % 2 === 0 ? a.charAt(p2) : (a.charAt(p2) === '0' ? '1' : '0');
                p2--;
            }

            if(x !== b.charAt(n-i-1)){
                count += 1;
                ans.push(n-i);
            }else{
                ans.push(1);
                ans.push(n-i);
            }
        }

        console.log(ans.length);
        for(let i = 0; i < ans.length; i++)
            console.log(ans[i]);
    }
}