You want to perform the combo on your opponent in one popular fighting game. The combo is the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in $$$s$$$. I.e. if $$$s=$$$"abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend $$$m$$$ wrong tries to perform the combo and during the $$$i$$$-th try you will make a mistake right after $$$p_i$$$-th button ($$$1 \le p_i < n$$$) (i.e. you will press first $$$p_i$$$ buttons right and start performing the combo from the beginning). It is guaranteed that during the $$$m+1$$$-th try you press all buttons right and finally perform the combo.I.e. if $$$s=$$$"abca", $$$m=2$$$ and $$$p = [1, 3]$$$ then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 2 \cdot 10^5$$$) — the length of $$$s$$$ and the number of tries correspondingly. The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. The third line of each test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i < n$$$) — the number of characters pressed right during the $$$i$$$-th try. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ both does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$). It is guaranteed that the answer for each letter does not exceed $$$2 \cdot 10^9$$$.

For each test case, print the answer — $$$26$$$ integers: the number of times you press the button 'a', the number of times you press the button 'b', $$$\dots$$$, the number of times you press the button 'z'.

3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4

NoteThe first test case is described in the problem statement. Wrong tries are "a", "abc" and the final try is "abca". The number of times you press 'a' is $$$4$$$, 'b' is $$$2$$$ and 'c' is $$$2$$$.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is $$$9$$$, 'd' is $$$4$$$, 'e' is $$$5$$$, 'f' is $$$3$$$, 'o' is $$$9$$$, 'r' is $$$3$$$ and 's' is $$$1$$$.

'use strict'

const getLine = () => readline().split(' ')
const getInts = () => getLine().map(n => parseInt(n))
const getInt = () => getInts()[0]

main()

function main () {
  let t = getInt()
  while (t --> 0) {
    const params = getInts()
    const s = getLine()[0]
    const mistakes = getInts()
    solve(...params, s, mistakes)
  }
}

function solve (n, m, s, mistakes) {
  const freq = Array(n + 1).fill(0)
  const ans = Array(26).fill(0)
  let accumulate = 0

  mistakes.push(n)

  mistakes.map(i => {
    freq[0] ++
    freq[i] --
  })

  for (let i = 0; i < n; ++i) {
    const ind = s[i].charCodeAt() - 'a'.charCodeAt()
    accumulate += freq[i]
    ans[ind] += accumulate
  }

  print(ans.join(' '))
}

'use strict'

const getLine = () => readline().split(' ')
const getInts = () => getLine().map(n => parseInt(n))
const getInt = () => getInts()[0]

main()

function main () {
  let t = getInt()
  while (t --> 0) {
    const params = getInts()
    const s = getLine()[0]
    const mistakes = getInts()
    solve(...params, s, mistakes)
  }
}

function solve (n, m, s, mistakes) {
  const freq = Array(n + 1).fill(0)
  const ans = Array(26).fill(0)
  let accumulate = 0

  mistakes.push(n)

  for (const i of mistakes) {
    freq[0] ++
    freq[i] --
  }

  for (let i = 0; i < n; ++i) {
    const ind = s[i].charCodeAt() - 'a'.charCodeAt()
    accumulate += freq[i]
    ans[ind] += accumulate
  }

  print(ans.join(' '))
}

'use strict'

let t = parseInt(readline())
const readInts = () => readline().split(' ').map(n => parseInt(n))
const readInt = () => readInts[0]
const abc = "abcdefghijklmnopqrstuvwxyz"

while (t --> 0) {
  const params = readInts()
  const n = params[0]
  const m = params[1]
  const s = readline()
  const arr = readInts()
  arr.push(n)

  const pre = {}
  for (let j = 0; j < 26; ++j) {
    pre[abc[j]] = Array(n + 1).fill(0)
  }

  for (let i = 0; i < n; ++i) {
    for (let j = 0; j < 26; ++j) {
      const c = abc[j]
      const last = pre[c][i]
      const val = last + (c === s[i])
      pre[c][i + 1] = val
    }
  }

  const out = {}
  for (let j = 0; j < 26; ++j) {
    out[abc[j]] = 0
  }

  for (let i in arr) {
    for (let j = 0; j < 26; ++j) {
      const c = abc[j]
      out[c] += pre[c][arr[i]]
    }
  }

  let ans = ""
  for (let i in out) {
    ans += " " + out[i]
  }
  print(ans)
}

'use strict';

let n = parseInt(readline());

while ( n-- > 0 ) {
  let line = readline().split(' ').map(data => parseInt(data));
  solve(...line);
}

function solve(n, m) {
  const str = readline();
  let freq = Array(n + 1).fill(0);

  const mistakes = readline().split(' ').map(data => parseInt(data));
  mistakes.push(n);

  mistakes.forEach(x => {
    freq[0]++; freq[x]--;
  });

  let answer = Array(26).fill(0);
  let accumulated = 0;

  for ( let i = 0; i < str.length; ++i ) {
    accumulated += freq[i];
    answer[str.charCodeAt(i) - 97] += accumulated;
  }
  print(answer.join(' '));
}

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
    var alphaToNum = {
        "a" : 0,
        "b" : 1,
        "c" : 2,
        "d" : 3,
        "e" : 4,
        "f" : 5,
        "g" : 6,
        "h" : 7,
        "i" : 8,
        "j" : 9,
        "k" : 10,
        "l" : 11,
        "m" : 12,
        "n" : 13,
        "o" : 14,
        "p" : 15,
        "q" : 16,
        "r" : 17,
        "s" : 18,
        "t" : 19,
        "u" : 20,
        "v" : 21,
        "w" : 22,
        "x" : 23,
        "y" : 24,
        "z" : 25
    }
    var t = myconv(next(),1);
    var output = new Array(t);
    for(var i = 0; i < t; i++){
        var one = myconv(next(),4);
        var n = one[0];
        var m = one[1];
        var nlist = myconv(next(),6);
        var mlist = myconv(next(),4);
        var outAlpha = new Array(26).fill(0);
        var countMap = new Array(n);
        var tmpMap = {
        	"a" : 0,
        "b" : 0,
        "c" : 0,
        "d" : 0,
        "e" : 0,
        "f" : 0,
        "g" : 0,
        "h" : 0,
        "i" : 0,
        "j" : 0,
        "k" : 0,
        "l" : 0,
        "m" : 0,
        "n" : 0,
        "o" : 0,
        "p" : 0,
        "q" : 0,
        "r" : 0,
        "s" : 0,
        "t" : 0,
        "u" : 0,
        "v" : 0,
        "w" : 0,
        "x" : 0,
        "y" : 0,
        "z" : 0
        };
        for(var j = 0; j < n; j++){
          tmpMap[nlist[j]]++;
          	outAlpha[alphaToNum[nlist[j]]]++;
            countMap[j] = JSON.parse(JSON.stringify(tmpMap));
        }
        for(var j = 0; j < m; j++){
            var tmpCountMap = countMap[mlist[j] - 1];
            var tmpKeys = Object.keys(tmpCountMap);
            for(var k = 0; k < tmpKeys.length; k++){
                outAlpha[alphaToNum[tmpKeys[k]]] += tmpCountMap[tmpKeys[k]];
            }
        }
        output[i] = myconv(outAlpha,8);
    }
    myout(myconv(output,9));
}

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

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

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

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

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

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let ptr = 0
  let t = readInt(input, ptr++)
  // const alpha = "abcdefghijklmnopqrstuvwxyz"
  while(t--) {
    const [n,m] = readInts(input, ptr++)
    const s = input[ptr++]
    const ps = readInts(input, ptr++)
    let map = new Array(n)
    for(let i = 0; i < n;i++) map[i] = new Array(26).fill(0)
    map[0][s.charCodeAt(0) - 97] = 1
    for(let i = 1; i < n;i ++) {
      const char = s.charCodeAt(i) - 97
      for(let j = 0;j < 26; j++) {
        map[i][j] = map[i - 1][j]
      }
      map[i][char] = map[i - 1][char] + 1
    }
    // console.log(map)

    let ans = new Array(26).fill(0)
    for(let i = 0; i < m;i ++) {
      let x = map[ps[i] - 1]
      for(let j = 0;j < 26; j++) {
        ans[j] = ans[j] + x[j]
      }
    }
    let x = map[n - 1]
    for(let j = 0;j < 26; j++) {
      ans[j] = ans[j] + x[j]
    }

    wr(ans.join(' '))
  }
}

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

    function foo (a, p) {
        p.push(a.length);
        result = Array(26).fill(0);

        const alph = {a:0,b:1,c:2,d:3,e:4,f:5,g:6,h:7,i:8,j:9,k:10,l:11,m:12,n:13,o:14,p:15,q:16,r:17,s:18,t:19,u:20,v:21,w:22,x:23,y:24,z:25};

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

        for (let i = 0; i < p.length; i++) {
            let substr = a.slice(p[i-1] || 0, p[i]);

            for (let k = 0; k < substr.length; k++) {
                let ind = alph[substr[k]];
                result[ind] = result[ind] + p.length - i;
            }
        }
        return result.join(' ');
    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let p = lines[testCount * 3].split(" ").map(Number);
        let a = lines[testCount * 3 - 1];

        let result = foo(a, p);
        answer += result +"\n";
        testCount++;
    }
    console.log(answer);
})

function generateAlphabets() {
  var alphabets = [];
  var start = 'a'.charCodeAt(0);
  var last  = 'z'.charCodeAt(0);
  for (var i = start; i <= last; ++i) {
    alphabets.push(String.fromCharCode(i));
  }

  return alphabets;
}

const seq = generateAlphabets();

const processData = (lines) => {
  const num = +lines[0]
  for (let j=0; j<num; j++){
    const curAlpha = generateAlphabets().reduce((acc, letter) => {acc[letter] = 0; return acc}, {})
    const row = lines[j*3 + 2]
    const missed = lines[j*3 + 3].split(' ').map(x => x - 1).sort((a, b) => b-a)
    for (let j=0; j<row.length; j++) {
      while (missed.length > 0 && missed[missed.length -1] < j) {
        missed.pop()
      }
      curAlpha[row[j]] += missed.length + 1
    }
    let res = ''
    for (const letter of seq) {
      res += curAlpha[letter] + ' '
    }
    console.log(res)
  }
}

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

var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
function main(input) {
    var lines = input.trim().split("\n").map(function (l) { return l.trim(); });
    var t = parseInt(lines.shift(), 10);
    var _loop_1 = function () {
        var _a = lines.shift(), n = _a[0], m = _a[1];
        var lettersMap = "qwertyuiopasdfghjklzxcvbnm".split("").reduce(function (a, k) {
            var _a;
            return (__assign(__assign({}, a), (_a = {}, _a[k] = 0, _a)));
        }, {});
        var combo = lines.shift().split("");
        var tries = lines.shift().split(" ").map(function (v) { return parseInt(v, 10); });
        var willFail = combo.map(function (v) { return 0; });
        tries.forEach(function (ts) { return willFail[ts - 1]++; });
        var inc = 1;
        for (var i = willFail.length - 1; i >= 0; i--) {
            inc += willFail[i];
            lettersMap[combo[i]] += inc;
        }
        console.log(Object.entries(lettersMap).sort(function (_a, _b) {
            var k = _a[0];
            var l = _b[0];
            return k.charCodeAt(0) - l.charCodeAt(0);
        }).map(function (v) { return v[1]; }).join(" "));
    };
    while (t-- > 0) {
        _loop_1();
    }
}
(function () {
    var d = "";
    process.stdin.on("data", function (v) { return d += v; });
    process.stdin.on("end", function () { return main(d); });
})();


Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index bi from 0 to n - 1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index bi, then this person acted like that:  he pointed at the person with index (bi + 1) mod n either with an elbow or with a nod (x mod y is the remainder after dividing x by y);  if j ≥ 4 and the players who had turns number j - 1, j - 2, j - 3, made during their turns the same moves as player bi on the current turn, then he had drunk a glass of juice;  the turn went to person number (bi + 1) mod n. The person who was pointed on the last turn did not make any actions.The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.You can assume that in any scenario, there is enough juice for everybody.

The first line contains a single integer n (4 ≤ n ≤ 2000) — the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns.

Print a single integer — the number of glasses of juice Vasya could have drunk if he had played optimally well.

NoteIn both samples Vasya has got two turns — 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like "abbbb". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different.

print(function(n, s) {

	var ans = 0;

	for (var i = n; i < s.length; i += n)
		if (s[i - 1] === s[i - 2] && s[i - 2] === s[i - 3])
			ans++;

	return ans;

}(+readline(), readline()));

;(function () {

	print(function (n, s, k) {

		for (var i = 1, l = s.length, _i = Math.floor(l / n); i <= _i; i++)
			if (i * n < l && s[i * n - 1] === s[i * n - 2] && s[i * n - 1] === s[i * n - 3]) k++;

		return k;

	}(+readline(), readline(), 0));

}.call(this));

;(function () {

	print(function (n, s, k) {

		for (var i = 1, _i = Math.floor(s.length / n); i <= _i; i++)
			if (s[i * n - 1] === s[i * n - 2] && s[i * n - 1] === s[i * n - 3]) k++;

		return k;

	}(+readline(), readline(), 0));

}.call(this));


There is a binary string $$$a$$$ of length $$$n$$$. In one operation, you can select any prefix of $$$a$$$ with an equal number of $$$0$$$ and $$$1$$$ symbols. Then all symbols in the prefix are inverted: each $$$0$$$ becomes $$$1$$$ and each $$$1$$$ becomes $$$0$$$.For example, suppose $$$a=0111010000$$$.   In the first operation, we can select the prefix of length $$$8$$$ since it has four $$$0$$$'s and four $$$1$$$'s: $$$[01110100]00\to [10001011]00$$$.  In the second operation, we can select the prefix of length $$$2$$$ since it has one $$$0$$$ and one $$$1$$$: $$$[10]00101100\to [01]00101100$$$.  It is illegal to select the prefix of length $$$4$$$ for the third operation, because it has three $$$0$$$'s and one $$$1$$$. Can you transform the string $$$a$$$ into the string $$$b$$$ using some finite number of operations (possibly, none)?

The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 3\cdot 10^5$$$) — the length of the strings $$$a$$$ and $$$b$$$. The following two lines contain strings $$$a$$$ and $$$b$$$ of length $$$n$$$, consisting of symbols $$$0$$$ and $$$1$$$. The sum of $$$n$$$ across all test cases does not exceed $$$3\cdot 10^5$$$.

For each test case, output "YES" if it is possible to transform $$$a$$$ into $$$b$$$, or "NO" if it is impossible. You can print each letter in any case (upper or lower).

NoteThe first test case is shown in the statement.In the second test case, we transform $$$a$$$ into $$$b$$$ by using zero operations.In the third test case, there is no legal operation, so it is impossible to transform $$$a$$$ into $$$b$$$.In the fourth test case, here is one such transformation:   Select the length $$$2$$$ prefix to get $$$100101010101$$$.  Select the length $$$12$$$ prefix to get $$$011010101010$$$.  Select the length $$$8$$$ prefix to get $$$100101011010$$$.  Select the length $$$4$$$ prefix to get $$$011001011010$$$.  Select the length $$$6$$$ prefix to get $$$100110011010$$$. In the fifth test case, the only legal operation is to transform $$$a$$$ into $$$111000$$$. From there, the only legal operation is to return to the string we started with, so we cannot transform $$$a$$$ into $$$b$$$.

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}
function getValue() {
  return parseInt(readline());
}
let mod = BigInt(1e9 + 7);
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let str = stringArr();
    let str1 = stringArr();
    let oarr = [],
      cnt0 = 0,
      cnt1 = 0,
      r = [];
    for (let i = 0; i < n; i++) {
      if (str[i] === "0") {
        cnt0++;
        r.push("1");
      } else {
        cnt1++;
        r.push("0");
      }
      oarr.push({ z: cnt0, o: cnt1 });
    }
    let i = str.length - 1,
      ans = true,
      l = str,
      k = 1;
    while (i >= 0) {
      let j = i;
      while (j >= 0 && l[j] !== str1[j]) j--;
      if (i !== j) {
        if (oarr[i].z !== oarr[i].o) {
          ans = false;
          break;
        }
        if (k) l = r;
        else l = str;
        k = !k;
        i = j;
      } else i--;
    }
    console.log(`${ans ? "YES" : "NO"}`);
  }
};
solve();

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

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

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

		a = a.split('');
		const dp = [];
		dp[-1] = 0;
		for (let i = 0; i < n; i++)
			dp[i] = dp[i-1] + (a[i] == '1') - (a[i] == '0');

		let ok = true;
		for (let i = n - 1, flpd = false; ok && i >= 0; i--) {
			if (flpd)
				a[i] = '10'[a[i]];

			if (a[i] != b[i]) {
				if (dp[i] != 0)
					ok = false;
				else
					flpd = !flpd;
			}
		}

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

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

//Don't have to see. end------------------------------------------

function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var a = next();
		var b = next();
		var area = [];
		var count = 0;
		var last = 0;
		for(var j = 0; j < N; j++){
			if(a[j] == "0"){
				count++;
			}else{
				count--;
			}
			if(count == 0){
				area.push({
					L : last,
					R : j
				});
				last = j + 1;
			}
		}

		var isOK = true;
		for(var j = last; j < N; j++){
			if(a[j] != b[j]){
				isOK = false;
				break;
			}
		}
		for(var j = 0; j < area.length; j++){
			var obj = area[j];
			var L = a.substring(obj.L, obj.R + 1);
			var R = "";
			for(var k = obj.L; k <= obj.R; k++){
				R += ((a[k] == "0") ? "1" : "0");
			}

			if(b.substring(obj.L, obj.R + 1) != L && b.substring(obj.L, obj.R + 1) != R){
				isOK = false;
				break;
			}
		}
		if(isOK){
			myout("YES");
		}else{
			myout("NO");
		}
	}

}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}
function getValue() {
  return parseInt(readline());
}
let mod = BigInt(1e9 + 7);
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let str = stringArr();
    let str1 = stringArr();
    const check = (st, ed) => {
      if (st === ed) return false;
      let cnt1 = 0,
        cnt2 = 0;
      for (let i = st; i <= ed; i++) {
        if (str[i] === "0") cnt1++;
        else cnt2++;
      }
      if (cnt1 === cnt2) return true;
      else return false;
    };
    let ans = true,
      i = 0;
    while (i < n) {
      let j = i;
      while (j < n && str[j] !== str1[j]) {
        j++;
      }
      if (i !== j) {
        if (j - 1 === i) {
          ans = false;
          break;
        }
        if (!check(0, j - 1)) {
          ans = false;
          break;
        }
        i = j;
      } else i++;
    }
    console.log(`${ans === true ? "YES" : "NO"}`);
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}
function getValue() {
  return parseInt(readline());
}
let mod = BigInt(1e9 + 7);
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let str = stringArr();
    let str1 = stringArr();
    const check = (st, ed) => {
      if (st === ed) return false;
      let cnt1 = 0,
        cnt2 = 0;
      for (let i = st; i <= ed; i++) {
        if (str[i] === "0") cnt1++;
        else cnt2++;
      }
      if (cnt1 === cnt2) return true;
      else return false;
    };
    let ans = true,
      i = 0;
    while (i < n) {
      let j = i;
      while (j < n && str[j] !== str1[j]) {
        j++;
      }
      if (i !== j) {
        if (!check(0, j - 1)) {
          ans = false;
          break;
        }
        i = j;
      } else i++;
    }
    console.log(`${ans === true ? "YES" : "NO"}`);
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}
function getValue() {
  return parseInt(readline());
}
let mod = BigInt(1e9 + 7);
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let str = stringArr();
    let str1 = stringArr();
    const check = (st, ed) => {
      if (st === ed) return false;
      let cnt1 = 0,
        cnt2 = 0;
      for (let i = st; i <= ed; i++) {
        if (str[i] === "0") cnt1++;
        else cnt2++;
      }
      if (cnt1 === cnt2) return true;
      else return false;
    };
    let ans = true,
      i = 0;
    while (i < n) {
      let j = i;
      while (j < n && str[j] !== str1[j]) {
        j++;
      }
      if (i !== j) {
        if (!check(i, j - 1)) {
          ans = false;
          break;
        }
        i = j;
      } else i++;
    }
    console.log(`${ans === true ? "YES" : "NO"}`);
  }
};
solve();


Ashish has a string $$$s$$$ of length $$$n$$$ containing only characters 'a', 'b' and 'c'.He wants to find the length of the smallest substring, which satisfies the following conditions:   Length of the substring is at least $$$2$$$  'a' occurs strictly more times in this substring than 'b'  'a' occurs strictly more times in this substring than 'c'  Ashish is busy planning his next Codeforces round. Help him solve the problem.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^{5})$$$  — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2 \le n \le 10^{6})$$$  — the length of the string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting only of characters 'a', 'b' and 'c'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^{6}$$$.

For each test case, output the length of the smallest substring which satisfies the given conditions or print $$$-1$$$ if there is no such substring.

NoteConsider the first test case. In the substring "aa", 'a' occurs twice, while 'b' and 'c' occur zero times. Since 'a' occurs strictly more times than 'b' and 'c', the substring "aa" satisfies the condition and the answer is $$$2$$$. The substring "a" also satisfies this condition, however its length is not at least $$$2$$$.In the second test case, it can be shown that in none of the substrings of "cbabb" does 'a' occur strictly more times than 'b' and 'c' each.In the third test case, "cacabccc", the length of the smallest substring that satisfies the conditions is $$$3$$$.

function getMin(arr) {
    var len = arr.length;
    var min = Infinity;

    while (len--) {
        min = arr[len] < min ? arr[len] : min;
    }
    return min;
}

function dominant_character(n,s){
  var ans = [];
  for (var i=0; i<n; i++){
    if(s[i]=='a'){
      for (var j=i+1; j<n; j++){

        var substring = s.substring(i,j+1);
        if(substring.length>7){
          break;
        }
        var c_a = (substring.match(/a/g) || []).length;
        var c_b = (substring.match(/b/g) || []).length;
        var c_c = (substring.match(/c/g) || []).length;
        if(c_a>c_c && c_a>c_b){
          ans.push(substring.length);
          break;
        }
      }
    }
  }
  if(ans.length>0){
    var result = getMin(ans);
  }
  else{
    var result = -1;
  }
  return result;
}

t = parseInt(readline());
for(var i=0; i<t; i++){
    var n = parseInt(readline());
    var s = readline();
    var ans = dominant_character(n,s);
    print(ans);
}

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

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

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

		let ans = -1;
		if (s.includes('aa')) ans = 2;
		else if (s.includes('aba') || s.includes('aca')) ans = 3;
		else if (s.includes('abca') || s.includes('acba')) ans = 4;
		else if (s.includes('abbacca') || s.includes('accabba')) ans = 7;

		console.log(ans);
	}
}

const readline = require('readline')

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

function solve(n, str) {
    if (contains(str, ['aa'])) return 2
    if (contains(str, ['aba', 'aca'])) return 3
    if (contains(str, ['abca', 'acba'])) return 4
    if (contains(str, ['abbacca', 'accabba'])) return 7
    return -1
}
function contains(str, ps) {
    return ps.some(p => str.indexOf(p) >= 0)
}

function dominant_character(n,s){
  var ans = [];
  for (var i=0; i<n; i++){
    if(s[i]=='a'){
      for (var j=i+1; j<n; j++){

        var substring = s.substring(i,j+1);
        if(substring.length>7){
          break;
        }
        var c_a = (substring.match(/a/g) || []).length;
        var c_b = (substring.match(/b/g) || []).length;
        var c_c = (substring.match(/c/g) || []).length;
        if(c_a>c_c && c_a>c_b){
          ans.push(substring.length);
          break;
        }
      }
    }
  }
  print(ans);
  if(ans.length>0){
    var result = Math.min(...ans);
  }
  else{
    var result = -1;
  }
  return result;
}

t = parseInt(readline());
for(var i=0; i<t; i++){
    var n = parseInt(readline());
    var s = readline();
    var ans = dominant_character(n,s);
    print(ans);
}

function dominant_character(n,s){
  var ans = [];
  for (var i=0; i<n; i++){
    if(s[i]=='a'){
      for (var j=i+1; j<n; j++){

        var substring = s.substring(i,j+1);
        if(substring.length>7){
          break;
        }
        var c_a = (substring.match(/a/g) || []).length;
        var c_b = (substring.match(/b/g) || []).length;
        var c_c = (substring.match(/c/g) || []).length;
        if(c_a>c_c && c_a>c_b){
          ans.push(substring.length);
          break;
        }
      }
    }
  }
  if(ans!=[]){
    var result = Math.min(...ans);
  }
  else{
    var result = -1;
  }
  return result;
}

t = parseInt(readline());
for(var i=0; i<t; i++){
    var n = parseInt(readline());
    var s = readline();
    var ans = dominant_character(n,s);
    print(ans);
}

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

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

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

		let ans = -1;
		if (s.includes('aa')) ans = 2;
		else if (s.includes('aba') || s.includes('aca')) ans = 3;
		else if (s.includes('abca') || s.includes('acba')) ans = 4;

		console.log(ans);
	}
}

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

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

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

		let ans = -1;
		if (s.includes('aa')) ans = 2;
		else if (s.includes('aba') || s.includes('aca')) ans = 3;

		console.log(ans);
	}
}

const readline = require('readline')

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

function solve(n, str) {
    if (contains(str, ['aa'])) return 2
    if (contains(str, ['aba', 'aca'])) return 3
    if (contains(str, ['abca', 'abba', 'acca', 'acba'])) return 4
    return -1
}
function contains(str, ps) {
    return ps.some(p => str.indexOf(p) >= 0)
}


Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).Inserting an element in the same position he was erased from is also considered moving.Can Vasya divide the array after choosing the right element to move and its new position?

The first line contains single integer n (1 ≤ n ≤ 100000) — the size of the array. The second line contains n integers a1, a2... an (1 ≤ ai ≤ 109) — the elements of the array.

Print YES if Vasya can divide the array after moving one element. Otherwise print NO.

NoteIn the first example Vasya can move the second element to the end of the array.In the second example no move can make the division possible.In the third example Vasya can move the fourth element by one position to the left.

function foo(array) {
  var length = array.length;

  var need = 0;
  for (var i=0; i<length; i++) {
    need += array[i];
  }

  if (need%2 === 1) {
    print('NO');
    return;
  }

  need /= 2;

  var res = new Set();
  var sum = 0;

  for (i=0; i<length; i++) {
    var n = array[i];

    sum += n;
    res.add(n);

    if (res.has(sum - need)) {
      print('YES');
      return;
    }
  }

  var res2 = new Set();
  sum = 0;

  array = array.reverse();

  for (i=0; i<length; i++) {
    var n = array[i];

    sum += n;
    res2.add(n);

    if (res2.has(sum - need)) {
      print('YES');
      return;
    }
  }

  print("NO");
}

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

foo(arr);

function solve() {
  var n = +readline();
  var a = readline().split(' ');
  //n = 100000;
  //a = [];
  //for (var i = 0; i < n; i++) {
    //a.push(i + 1);
 // }
  var need = 0;
  for (var i = 0; i < n; i++) {
    a[i] = +a[i];
    need += a[i];
  }
  if (need % 2 !== 0) {
    print("NO");
    return;
  }
  need /= 2;

  var was = new Set;

  var sum = 0;

  for (var i = 0; i < n; i++) {
    sum += a[i];
    was.add(a[i]);
    var val = sum - need;
    if (was.has(val)) {
      print("YES");
      return;
    }
  }

  was = new Set;

  sum = 0;

  a = a.reverse();

  for (var i = 0; i < n; i++) {
    sum += a[i];
    was.add(a[i]);
    var val = sum - need;
    if (was.has(val)) {
      print("YES");
      return;
    }
  }

  print("NO");

}
solve();

function solve() {
  var n = +readline();
  var a = readline().split(' ');
  var need = 0;
  for (var i = 0; i < n; i++) {
    a[i] = +a[i];
    need += a[i];
  }
  if (need % 2 !== 0) {
    print("NO");
    return;
  }
  need /= 2;

  var was = {};

  var sum = 0;

  for (var i = 0; i < n; i++) {
    sum += a[i];
    was[a[i]] = true;
    var val = sum - need;
    if (was[val]) {
      print("YES");
      return;
    }
  }

  print("NO");

}
solve();

function solve() {
  var n = +readline();
  var a = readline().split(' ');
  //n = 100000;
  //a = [];
  //for (var i = 0; i < n; i++) {
    //a.push(i + 1);
 // }
  var need = 0;
  for (var i = 0; i < n; i++) {
    a[i] = +a[i];
    need += a[i];
  }
  if (need % 2 !== 0) {
    print("NO");
    return;
  }
  need /= 2;

  var was = new Set;

  var sum = 0;

  for (var i = 0; i < n; i++) {
    sum += a[i];
    was.add(a[i]);
    var val = sum - need;
    if (was.has(val)) {
      print("YES");
      return;
    }
  }

  print("NO");

}
solve();

function solve() {
  var n = +readline();
  var a = readline().split(' ');
  //n = 100000;
  //a = [];
  //for (var i = 0; i < n; i++) {
    //a.push(i + 1);
 // }
  var need = 0;
  for (var i = 0; i < n; i++) {
    a[i] = +a[i];
    need += a[i];
  }
  if (need % 2 !== 0) {
    print("NO");
    return;
  }
  need /= 2;

  var was = [];

  var sum = 0;

  for (var i = 0; i < n; i++) {
    sum += a[i];
    was[a[i]] = true;
    var val = sum - need;
    if (val > 1000000000 || val <= 0) {
      continue;
    }
    if (was[val]) {
      print("YES");
      return;
    }
  }

  print("NO");

}
solve();


This is an interactive problem!In the last regional contest Hemose, ZeyadKhattab and YahiaSherif — members of the team Carpe Diem — did not qualify to ICPC because of some unknown reasons. Hemose was very sad and had a bad day after the contest, but ZeyadKhattab is very wise and knows Hemose very well, and does not want to see him sad.Zeyad knows that Hemose loves tree problems, so he gave him a tree problem with a very special device.Hemose has a weighted tree with $$$n$$$ nodes and $$$n-1$$$ edges. Unfortunately, Hemose doesn't remember the weights of edges.Let's define $$$Dist(u, v)$$$ for $$$u\neq v$$$ as the greatest common divisor of the weights of all edges on the path from node $$$u$$$ to node $$$v$$$.Hemose has a special device. Hemose can give the device a set of nodes, and the device will return the largest $$$Dist$$$ between any two nodes from the set. More formally, if Hemose gives the device a set $$$S$$$ of nodes, the device will return the largest value of $$$Dist(u, v)$$$ over all pairs $$$(u, v)$$$ with $$$u$$$, $$$v$$$ $$$\in$$$ $$$S$$$ and $$$u \neq v$$$.Hemose can use this Device at most $$$12$$$ times, and wants to find any two distinct nodes $$$a$$$, $$$b$$$, such that $$$Dist(a, b)$$$ is maximum possible. Can you help him?

var readline = require('readline');

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

var g = main();
g.next()
rl.on('line', (input) => {
    // console.log('read', input)
    input.split('\n').forEach(s => s.trim() && g.next(s))
});

function* main() {
    let input

    input = yield 1
    let n = +input
    // console.log(n)
    const edges = []
    for (let i = 0; i < n - 1; i++) {
        input = yield 1
    // console.log('sb', i, input)
        const edge = input.split(' ').map(Number)
        edges.push(edge)
    }
    // console.log(edges)
    yield* solve(n, edges)
    process.exit(0)
}

function* solve(n, edges) {
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })

    const order = dfs(adj, 1, {})

// console.log(order)
    let l = 0
    let r = order.length - 1
    query(order, l, r, 1)
    const dmax = yield 1

    const idx = yield* binarySearch(l, r, function* (x) {
        query(order, l, x, 1)
        const da = yield 1
        return da !== dmax
    })
    query(order, idx + 1, idx + 1)
}
function query(order, l, r, ask) {
    const map = {}
    for (let i = l; i <= r; i++) {
        const [a, b] = order[i]
        map[a] = 1
        map[b] = 1
    }
    // console.log('query', l, r)
    const nodes = Object.keys(map)
    const str = nodes.join(' ')
    if (ask) {
        console.log(`? ${nodes.length} ${str}`)
    } else {
        console.log(`! ${str}`)
    }
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1]]
    // const count = []
    const order = []
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i && p > 0) {
            order.push([p, u])
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // count[u] = 1
            // nb.forEach(v => {
            //     if (v !== p) count[u] += count[v]
            // })
            if (p > 0) {
                order.push([u, p])
            }
            stack.pop()
        }
    }
    // return count
    return order
}
function* binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        const ok = yield* fn(m)
        // console.log('binarySearch', l, r, ok)
        if (ok) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

var readline = require('readline');

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

var g = main();
g.next()
rl.on('line', (input) => {
    // console.log('read', input)
    input.split('\n').forEach(s => s.trim() && g.next(s))
});

function* main() {
    let input

    input = yield 1
    let n = +input
    // console.log(n)
    const edges = []
    for (let i = 0; i < n - 1; i++) {
        input = yield 1
    // console.log('sb', i, input)
        const edge = input.split(' ').map(Number)
        edges.push(edge)
    }
    // console.log(edges)
    yield* solve(n, edges)
    process.exit(0)
}

function* solve(n, edges) {
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })

    const order = dfs(adj, 1, {})

// console.log(order)
    let l = 0
    let r = order.length - 1
    query(order, l, r, 1)
    const dmax = yield 1

    const idx = yield* binarySearch(l, r, function* (x) {
        query(order, l, x, 1)
        const da = yield 1
        return da === dmax
    })
    query(order, idx, idx)
}
function query(order, l, r, ask) {
    const map = {}
    for (let i = l; i <= r; i++) {
        const [a, b] = order[i]
        map[a] = 1
        map[b] = 1
    }
    // console.log('query', l, r)
    const nodes = Object.keys(map)
    const str = nodes.join(' ')
    if (ask) {
        console.log(`? ${nodes.length} ${str}`)
    } else {
        console.log(`! ${str}`)
    }
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1]]
    // const count = []
    const order = []
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i && p > 0) {
            order.push([p, u])
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // count[u] = 1
            // nb.forEach(v => {
            //     if (v !== p) count[u] += count[v]
            // })
            if (p > 0) {
                order.push([u, p])
            }
            stack.pop()
        }
    }
    // return count
    return order
}
function* binarySearch(l, r, fn) {
    while (l < r) {
        const m = Math.floor((l + r) / 2)
        const ok = yield* fn(m)
        // console.log('binarySearch', l, r, ok)
        if (ok) {
            r = m
        } else {
            l = m
        }
    }
    return r
}

var readline = require('readline');

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

var g = main();
g.next()
rl.on('line', (input) => {
    // console.log('read', input)
    input.split('\n').forEach(s => s.trim() && g.next(s))
});

function* main() {
    let input

    input = yield 1
    let n = +input
    // console.log(n)
    const edges = []
    for (let i = 0; i < n - 1; i++) {
        input = yield 1
    // console.log('sb', i, input)
        const edge = input.split(' ').map(Number)
        edges.push(edge)
    }
    // console.log(edges)
    yield* solve(n, edges)
    process.exit(0)
}

function* solve(n, edges) {
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })

    const order = dfs(adj, 1, {})

// console.log(order)
    let l = 0
    let r = n - 1
    console.log('? ' + query(order, l, r, 1))
    const dmax = yield 1

    // let max
    while (l + 1 < r) {
        const m = Math.floor((l + r) / 2)
        let da = -1
        if (l + 1 <= m) {
            console.log('? ' + query(order, l, m, 1))
            da = yield 1
        }
        if (da === dmax) {
            r = m
            if (l + 1 === r) {
                console.log('! ' + query(order, l, r))
                return
            }
        } else {
            l = m
            if (l + 1 === r) {
                console.log('! ' + query(order, l, r))
                return
            }
        }
    }
}
function query(order, l, r, ask) {
    return (ask ? (r - l + 1) + ' ' : '') + order.slice(l, r + 1).join(' ')
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1]]
    // const count = []
    const order = []
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            order.push(u)
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // count[u] = 1
            // nb.forEach(v => {
            //     if (v !== p) count[u] += count[v]
            // })
            stack.pop()
        }
    }
    // return count
    return order
}

var readline = require('readline');

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

var g = main();
g.next()
rl.on('line', (input) => {
    // console.log('read', input)
    input.split('\n').forEach(s => s.trim() && g.next(s))
});

function* main() {
    let input

    input = yield 1
    let n = +input
    // console.log(n)
    const edges = []
    for (let i = 0; i < n - 1; i++) {
        input = yield 1
    // console.log('sb', i, input)
        const edge = input.split(' ').map(Number)
        edges.push(edge)
    }
    // console.log(edges)
    yield* solve(n, edges)
    process.exit(0)
}

function* solve(n, edges) {
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })

    const order = dfs(adj, 1, {})

// console.log(order)
    let l = 0
    let r = n - 1
    console.log('? ' + query(order, l, r, 1))
    const dmax = yield 1

    // let max
    while (l + 1 < r) {
        const m = Math.floor((l + r) / 2)
        let da = -1
        if (l + 1 <= m) {
            console.log('? ' + query(order, l, m, 1))
            da = yield 1
        }
        let db = -1
        if (m + 1 + 1 <= r) {
            console.log('? ' + query(order, m + 1, r, 1))
            db = yield 1
        }
        // console.log('log', da, db, dmax)
        if (da === dmax) {
            r = m
            if (l + 1 === r) {
                console.log('! ' + query(order, l, r))
                return
            }
        } else if (db === dmax) {
            l = m + 1
            if (l + 1 === r) {
                console.log('! ' + query(order, l, r))
                return
            }
        } else {
            console.log('! ' + query(order, m, m + 1))
            return
        }
    }
}
function query(order, l, r, ask) {
    return (ask ? (r - l + 1) + ' ' : '') + order.slice(l, r + 1).join(' ')
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1]]
    // const count = []
    const order = []
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            order.push(u)
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // count[u] = 1
            // nb.forEach(v => {
            //     if (v !== p) count[u] += count[v]
            // })
            stack.pop()
        }
    }
    // return count
    return order
}

var readline = require('readline');

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

var g = main();
g.next()
rl.on('line', (input) => {
    // console.log('read', input)
    input.split('\n').forEach(s => s.trim() && g.next(s))
});

function* main() {
    let input

    input = yield 1
    let n = +input
    // console.log(n)
    const edges = []
    for (let i = 0; i < n - 1; i++) {
        input = yield 1
    // console.log('sb', i, input)
        const edge = input.split(' ').map(Number)
        edges.push(edge)
    }
    // console.log(edges)
    yield* solve(n, edges)
    process.exit(0)
}

function* solve(n, edges) {
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })

    const order = dfs(adj, 1, {})

// console.log(order)
    let l = 0
    let r = n - 1
    console.log('? ' + query(order, l, r))
    const dmax = yield 1

    // let max
    while (l + 1 < r) {
        const m = Math.floor((l + r) / 2)
        let da = -1
        if (l + 1 <= m) {
            console.log('? ' + query(order, l, m))
            da = yield 1
        }
        let db = -1
        if (m + 1 + 1 <= r) {
            console.log('? ' + query(order, m + 1, r))
            db = yield 1
        }
        // console.log('log', da, db, dmax)
        if (da === dmax) {
            r = m
            if (l + 1 === r) {
                console.log('! ' + query(order, l, r))
                return
            }
        } else if (db === dmax) {
            l = m + 1
            if (l + 1 === r) {
                console.log('! ' + query(order, l, r))
                return
            }
        } else {
            console.log('! ' + query(order, m, m + 1))
            return
        }
    }
}
function query(order, l, r) {
    return order.slice(l, r + 1).join(' ')
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1]]
    // const count = []
    const order = []
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            order.push(u)
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // count[u] = 1
            // nb.forEach(v => {
            //     if (v !== p) count[u] += count[v]
            // })
            stack.pop()
        }
    }
    // return count
    return order
}

var readline = require('readline');

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

var g = main();
g.next()
rl.on('line', (input) => {
    // console.log('read', input)
    input.split('\n').forEach(s => s.trim() && g.next(s))
});

function* main() {
    let input

    input = yield 1
    let n = +input
    // console.log(n)
    const edges = []
    for (let i = 0; i < n - 1; i++) {
        input = yield 1
    // console.log('sb', i, input)
        const edge = input.split(' ').map(Number)
        edges.push(edge)
    }
    // console.log(edges)
    yield* solve(n, edges)
    process.exit(0)
}

function* solve(n, edges) {
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })

    const order = dfs(adj, 1, {})

// console.log(order)
    let l = 0
    let r = n - 1
    console.log(query(order, l, r))
    const dmax = yield 1

    // let max
    while (l + 1 < r) {
        const m = Math.floor((l + r) / 2)
        let da = -1
        if (l + 1 <= m) {
            console.log(query(order, l, m))
            da = yield 1
        }
        let db = -1
        if (m + 1 + 1 <= r) {
            console.log(query(order, m + 1, r))
            db = yield 1
        }
        // console.log('log', da, db, dmax)
        if (da === dmax) {
            r = m
            if (l + 1 === r) {
                console.log(query(order, l, r))
                return
            }
        } else if (db === dmax) {
            l = m + 1
            if (l + 1 === r) {
                console.log(query(order, l, r))
                return
            }
        } else {
            console.log(query(order, m, m + 1))
            return
        }
    }
}
function query(order, l, r) {
    return order.slice(l, r + 1).join(' ')
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1]]
    // const count = []
    const order = []
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            order.push(u)
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // count[u] = 1
            // nb.forEach(v => {
            //     if (v !== p) count[u] += count[v]
            // })
            stack.pop()
        }
    }
    // return count
    return order
}


You are playing a variation of game 2048. Initially you have a multiset $$$s$$$ of $$$n$$$ integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset.During each operation you choose two equal integers from $$$s$$$, remove them from $$$s$$$ and insert the number equal to their sum into $$$s$$$.For example, if $$$s = \{1, 2, 1, 1, 4, 2, 2\}$$$ and you choose integers $$$2$$$ and $$$2$$$, then the multiset becomes $$$\{1, 1, 1, 4, 4, 2\}$$$.You win if the number $$$2048$$$ belongs to your multiset. For example, if $$$s = \{1024, 512, 512, 4\}$$$ you can win as follows: choose $$$512$$$ and $$$512$$$, your multiset turns into $$$\{1024, 1024, 4\}$$$. Then choose $$$1024$$$ and $$$1024$$$, your multiset turns into $$$\{2048, 4\}$$$ and you win.You have to determine if you can win this game.You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) – the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in multiset. The second line of each query contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 2^{29}$$$) — the description of the multiset. It is guaranteed that all elements of the multiset are powers of two.

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

NoteIn the first query you can win as follows: choose $$$512$$$ and $$$512$$$, and $$$s$$$ turns into $$$\{1024, 64, 1024\}$$$. Then choose $$$1024$$$ and $$$1024$$$, and $$$s$$$ turns into $$$\{2048, 64\}$$$ and you win.In the second query $$$s$$$ contains $$$2048$$$ initially.

// s of n
// power two
let lines = ''

process.stdin.resume()
process.stdin.setEncoding('utf-8')
process.stdin.on('data', input => lines += input)
process.stdin.on('end', () => {
  const { EOL } = require('os')
  lines = lines.split(EOL)

  main()
})

function main() {
  const q = lines[0]

  for(let i = 1; i <= q * 2; i+=2) {
    const n = lines[i]
    const s = lines[i + 1].split(/\s/)
    const m = {}
    let result = false

    s.some(v => {
      if(!m[v]) m[v] = []

      m[v].push(Number(v))

      if(m[v].length === 2) {
        const sum = makeSum(m, v)

        if(sum === 2048) {
          result = true
          return result
        }
      } else {
        if(v === '2048') {
          result = true
          return result
        }
      }
    })

    console.log(result ? 'YES' : 'NO')
  }
}

function makeSum(m, v) {
  const sum = Number(v) + Number(v)

  if(!m[sum]) m[sum] = []

  m[sum].push(sum)
  m[v] = []

  if(m[sum].length === 2) {
    return makeSum(m, sum)
  } else {
    return sum
  }
}

q=+readline()
while (q--){
    a=new Array(2049)
    for (i=0;i<=2048;i++)
        a[i]=0
    n=+readline()
    s=readline().split(' ').map(function(x){a[+x]++;return undefined})
    for (i=2;i<=2048;i*=2){
        a[i]+=a[i/2]>>1
    }
    if (a[2048])
    print("YES")
    else
    print("NO")
}

"use strict";

String.prototype.getNumArray = function () {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  });
};

var gamesAmount = parseInt(readline());
var answers = [];
var nums = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048];

var _loop = function _loop(game) {
  var n = parseInt(readline());
  var s = readline().getNumArray();
  var obj = {
    1: 0,
    2: 0,
    4: 0,
    8: 0,
    16: 0,
    32: 0,
    64: 0,
    128: 0,
    256: 0,
    512: 0,
    1024: 0,
    2048: 0
  };
  var answer = 'YES';

  for (var i = 0; i < n; i++) {
    if (s[i] === 2048) {
      obj[2048] = 1;
      break;
    }

    if (s[i] < 2048) {
      obj[s[i]] += 1;
    }
  }

  if (obj[2048]) {
    answers.push(answer);
    return "continue";
  } else {
    nums.forEach(function (_n) {
      var nextN = _n * 2;
      var nextNAmount = Math.floor((obj[_n] || 0) / 2);
      obj[nextN] += nextNAmount;
    });

    if (!obj[2048]) {
      answer = 'NO';
    }

    answers.push(answer);
  }
};

for (var game = 0; game < gamesAmount; game++) {
  var _ret = _loop(game);

  if (_ret === "continue") continue;
}

write(answers.join('\n'));

// s of n
// power two
let lines = ''

process.stdin.resume()
process.stdin.setEncoding('utf-8')
process.stdin.on('data', input => lines += input)
process.stdin.on('end', () => {
  const { EOL } = require('os')
  lines = lines.split(EOL)

  main()
})

function main() {
  const q = lines[0]

  for(let i = 1; i <= q * 2; i+=2) {
    const n = lines[i]
    const s = lines[i + 1].split(/\s/).map(Number).sort((a, b) => a - b)
    let result = false
    let p = s[0]
    let sum = p

    s.slice(1).some(v => {
      if(sum === 2048) {
        return true
      } else if(v === 2048) {
        sum = v
        return true
      }

      if(p === v) {
        sum = p + v
        p = sum
      } else {
        p = v
      }
    })

    if(sum === 2048) {
      result = true
    }

    console.log(result ? 'YES' : 'NO')
  }
}

"use strict";

String.prototype.getNumArray = function () {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  });
};

var gamesAmount = parseInt(readline());
var answers = [];
var nums = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048];

var _loop = function _loop(game) {
  var n = parseInt(readline());
  var s = readline().getNumArray();
  var obj = {
    1: 0,
    2: 0,
    4: 0,
    8: 0,
    16: 0,
    32: 0,
    64: 0,
    128: 0,
    256: 0,
    512: 0,
    1024: 0,
    2048: 0
  };
  var answer = 'YES';

  for (var i = 0; i < n; i++) {
    if (s[i] === 2048) {
      obj[2048] = 1;
      break;
    }

    if (s[i] < 2048) {
      obj[s[i]] += 1;
    }

    nums.forEach(function (_n) {
      var nextN = _n * 2;
      var nextNAmount = Math.floor((obj[_n] || 0) / 2);
      obj[nextN] += nextNAmount;
    });
  }

  if (!obj[2048]) {
    answer = 'NO';
  }

  answers.push(answer);
};

for (var game = 0; game < gamesAmount; game++) {
  _loop(game);
}

write(answers.join('\n'));


Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition Ai ≥ Bj holds. Help Leha rearrange the numbers in the array A so that the sum  is maximally possible, where A' is already rearranged array.

First line of input data contains single integer m (1 ≤ m ≤ 2·105) — length of arrays A and B. Next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 109) — array A. Next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109) — array B.

Output m integers a'1, a'2, ..., a'm — array A' which is permutation of the array A.

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

var bp = new Array(m);
for(var i = 0; i < m; i++) {
    bp[i] = [b[i], i];
}
function sortBP(p,q) {
    return p[0] - q[0];
}
bp.sort(sortBP);

function sortNumber(p,q) {
    return p - q;
}
a.sort(sortNumber);
var ans = new Array(m);
for(var i = 0; i < m; i++) {
    ans[bp[i][1]] = a[m-i-1];
}
print(ans.join(" "));

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

var bp = new Array(m);
for(var i = 0; i < m; i++) {
    bp[i] = [b[i], i];
}
bp.sort();
a.sort();
var ans = new Array(m);
for(var i = 0; i < m; i++) {
    ans[bp[i][1]] = a[m-i-1];
}
print(ans.join(" "));


A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Let $$$p$$$ be any permutation of length $$$n$$$. We define the fingerprint $$$F(p)$$$ of $$$p$$$ as the sorted array of sums of adjacent elements in $$$p$$$. More formally,$$$$$$F(p)=\mathrm{sort}([p_1+p_2,p_2+p_3,\ldots,p_{n-1}+p_n]).$$$$$$For example, if $$$n=4$$$ and $$$p=[1,4,2,3],$$$ then the fingerprint is given by $$$F(p)=\mathrm{sort}([1+4,4+2,2+3])=\mathrm{sort}([5,6,5])=[5,5,6]$$$.You are given a permutation $$$p$$$ of length $$$n$$$. Your task is to find a different permutation $$$p'$$$ with the same fingerprint. Two permutations $$$p$$$ and $$$p'$$$ are considered different if there is some index $$$i$$$ such that $$$p_i \ne p'_i$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 668$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2\le n\le 100$$$)  — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1,\ldots,p_n$$$ ($$$1\le p_i\le n$$$). It is guaranteed that $$$p$$$ is a permutation.

For each test case, output $$$n$$$ integers $$$p'_1,\ldots, p'_n$$$ — a permutation such that $$$p'\ne p$$$ and $$$F(p')=F(p)$$$. We can prove that for every permutation satisfying the input constraints, a solution exists. If there are multiple solutions, you may output any.

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

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    arr.reverse();
    console.log(arr.join(" "));
  }
}

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

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var N = nextInt();
    var list = nextIntArray();
    var tmp = [];
    for(var j = 0; j < N; j++){
      tmp.push(list.pop());
    }
    output[i] = myconv(tmp, 8);
  }
  myout(myconv(output, 9));
}

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i <= b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = a; i >= b; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function Arr(a, b, cb, prev) {
  let p = prev || 0;
  if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb ? (p = cb(a + i, p)) : a + i);
  return Array(a - b + 1).fill(0).map((v, i) => cb ? (p = cb(a - i, p)) : a - i);
}

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(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex(v => v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex(v => v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  t = inp[r++];
  while (t--) {
    let n = inp[r++];
    let a = inp.slice(r, r = r + n);
    console.log(a.reverse().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();
    });

    A();
});

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

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

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

    return a;
}

function A(){
    let t = pi(readline());

    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        for(let i = 0; i < Math.floor(n/2); i++){
            let temp = a[i];
            a[i] = a[n-i-1];
            a[n-i-1] = temp;
        }

        for(let num of a)
            console.log(num);
    }
}

function F(){
    let [n,x] = ti(readline().split(' '));
    let s = readline();
    let t = readline();

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

    for(let i = 1; i < n; i++){
        for(let j = 0; j <= x; j++){
            for(let k = 0; k <= n; k++){
                dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j][k-1] + (s.charAt(i) === t.charAt(1) ? k-1 : 0));
                if(j !== 0){
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j-1][k-1] + (t.charAt(0) === t.charAt(1) ? k-1 : 0));
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j-1][k-1] + k-1);
                }
            }
        }
    }

    let max = 0;
    for(let i = 0; i < x; i++)
        for(let j = 0; j < n; j++)
            max = Math.max(max, dp[n-1][i][j]);

    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 list = nextIntArray();
    list.sort(function(){
      return 1;
    });
    output[i] = myconv(list, 8);
  }
  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();
    });

    A();
});

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

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

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

    return a;
}

function A(){
    let t = pi(readline());

    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        if(n % 2 === 0){
            for(let i = 1; i < n; i += 2){
                let temp = a[i-1];
                a[i-1] = a[i];
                a[i] = temp;
            }
        }else{
            for(let i = 0; i < Math.floor(n/2); i++){
                let temp = a[i];
                a[i] = a[n-i-1];
                a[n-i-1] = temp;
            }
        }

        for(let num of a)
            console.log(num);
    }
}

function F(){
    let [n,x] = ti(readline().split(' '));
    let s = readline();
    let t = readline();

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

    for(let i = 1; i < n; i++){
        for(let j = 0; j <= x; j++){
            for(let k = 0; k <= n; k++){
                dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j][k-1] + (s.charAt(i) === t.charAt(1) ? k-1 : 0));
                if(j !== 0){
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j-1][k-1] + (t.charAt(0) === t.charAt(1) ? k-1 : 0));
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j-1][k-1] + k-1);
                }
            }
        }
    }

    let max = 0;
    for(let i = 0; i < x; i++)
        for(let j = 0; j < n; j++)
            max = Math.max(max, dp[n-1][i][j]);

    console.log(max);
}


Vasya bought the collected works of a well-known Berland poet Petya in n volumes. The volumes are numbered from 1 to n. He thinks that it does not do to arrange the book simply according to their order. Vasya wants to minimize the number of the disposition’s divisors — the positive integers i such that for at least one j (1 ≤ j ≤ n) is true both: j mod i = 0 and at the same time p(j) mod i = 0, where p(j) is the number of the tome that stands on the j-th place and mod is the operation of taking the division remainder. Naturally, one volume can occupy exactly one place and in one place can stand exactly one volume.Help Vasya — find the volume disposition with the minimum number of divisors.

The first line contains number n (1 ≤ n ≤ 100000) which represents the number of volumes and free places.

Print n numbers — the sought disposition with the minimum divisor number. The j-th number (1 ≤ j ≤ n) should be equal to p(j) — the number of tome that stands on the j-th place. If there are several solutions, print any of them.

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(), 10);
	var arrangement = [];
	for (var position = 2; position <= n; ++position) {
		arrangement.push(position);
	}
	arrangement.push(1);
	print(arrangement.join(" "));
}

main();


Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.

NoteIn the first test case, you can add roads   from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$,  from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$,  from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$,  from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$,  from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$.  The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = +lines[0]
    var l = 1;
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        var arr = lines[l++].split(' ').map(Number)
        console.log(solve(n, arr));
    }
});

function solve(n, arr) {
    if (n === 1) return 0

    arr.sort((a, b) => a - b)
    // let ans = 0
    // let s = 0
    // for (let i = 0; i < n; ++i) {
    //     ans -= arr[i] * i;
    //     ans += s;
    //     s += arr[i];
    // }
    // ans += arr[n - 1];
    // return ans

    const segs = []
    arr.forEach((a, i) => {
        let val
        if (i) {
            val = arr[i] - arr[i - 1]
        } else {
            val = arr[i]
        }
        // filter the first
        if (i) {
            segs.push(BigInt(val))
        }
    })
    // console.log(segs)

    const dp = []
    let count = 0n
    let sum = 0n // sum of those end with i
    segs.forEach((a, i) => {
        sum += count * a + a
        count++
        if (i) {
            dp[i] = dp[i - 1] + sum
        } else {
            dp[i] = a
        }
    })
    // console.log(dp)
    const result = calSum(segs) - dp[segs.length - 1]
    return result.toString()
}

function calSum(arr) {
    return arr.reduce((s, x) => s + x, 0n)
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => {
        let next;
        do {
            next = (await getLineGen.next());
        } while (!next.done && next.value === '');
        return next.value;
    };
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const ar = (await getLine()).split(' ').map(num => parseInt(num));
        ar.sort((a,b) => (a-b));
        let sum = BigInt(ar[n-1]);
        for(let i = 1; i < n; i++) {
            sum -= BigInt(ar[i] - ar[i-1]) * BigInt(i) * BigInt(n - i);
        }
        console.log(sum.toString());
    }
}

solve();

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = __importStar(require("fs"));
// import * as readline from 'readline'
// const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
// const ask = (query: string) => new Promise<string>((resolve) => rl.question(query, resolve))
// // Don't forget `rl.close()`.
const INT = Math.floor;
Array.prototype.last = function () {
    return this.length === 0 ? undefined : this[this.length - 1];
};
Array.prototype.isEmpty = function () {
    return this.length === 0;
};
const less = (a, b) => (a == b ? 0 : a < b ? -1 : 1);
const greater = (a, b) => (a == b ? 0 : a < b ? 1 : -1);
const bigIntMax = (...args) => args.reduce((m, e) => (e > m ? e : m));
const bigIntMin = (...args) => args.reduce((m, e) => (e < m ? e : m));
const bigIntAbs = (arg) => (arg < 0 ? -arg : arg);
function read_stdin() {
    return fs.readFileSync(process.env.NODE_ENV === 'debug' ? stdin : process.stdin.fd, 'utf8');
}
class Input {
    constructor(str) {
        this.index = 0;
        this.inputs = (str ? str : read_stdin()).split(/\s+/);
    }
    number() {
        return Number(this.inputs[this.index++]);
    }
    numbers(n) {
        return this.inputs.slice(this.index, (this.index += n)).map(Number);
    }
    bigint() {
        return BigInt(this.inputs[this.index++]);
    }
    bigints(n) {
        return this.inputs.slice(this.index, (this.index += n)).map(BigInt);
    }
    word() {
        return this.inputs[this.index++];
    }
    words(n) {
        return this.inputs.slice(this.index, (this.index += n));
    }
}
function array(len, init) {
    return Array(len).fill(init);
}
function array2(h, w, init) {
    return array(h, 0).map(() => array(w, init));
}
function main() {
    const input = new Input();
    const T = input.number();
    const ans = Array(T);
    for (let k = 0; k < T; k++) {
        const N = input.number();
        const A = input.numbers(N);
        A.sort((a, b) => a - b);
        let sum = 0n;
        let acc = 0;
        for (let [i, j] = [N - 1, 0]; i >= 1; i--, j++) {
            acc += i - j;
            sum -= BigInt(acc - 1) * BigInt(A[j + 1] - A[j]);
        }
        ans[k] = sum;
    }
    console.log(ans.join('\n'));
}
main();
//# sourceMappingURL=aoj.js.map

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = +lines[0]
    var l = 1;
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        var arr = lines[l++].split(' ').map(Number)
        console.log(solve(n, arr));
    }
});

function solve(n, arr) {
    if (n === 1) return 0

    arr.sort((a, b) => a - b)
    // let ans = 0
    // let s = 0
    // for (let i = 0; i < n; ++i) {
    //     ans -= arr[i] * i;
    //     ans += s;
    //     s += arr[i];
    // }
    // ans += arr[n - 1];
    // return ans

    const segs = []
    arr.forEach((a, i) => {
        let val
        if (i) {
            val = arr[i] - arr[i - 1]
        } else {
            val = arr[i]
        }
        // filter the first
        if (i) {
            segs.push(val)
        }
    })
    // console.log(segs)

    const dp = []
    let count = 0
    let sum = 0 // sum of those end with i
    segs.forEach((a, i) => {
        sum += count * a + a
        count++
        if (i) {
            dp[i] = dp[i - 1] + sum
        } else {
            dp[i] = a
        }
    })
    // console.log(dp)
    return calSum(segs) - dp[segs.length - 1]
}

function calSum(arr) {
    return arr.reduce((s, x) => s + x, 0)
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = +lines[0]
    var l = 1;
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        var arr = lines[l++].split(' ').map(Number)
        console.log(solve(n, arr));
    }
});

function solve(n, arr) {
    if (n === 1) return 0

    arr.sort((a, b) => a - b)

    const segs = []
    arr.forEach((a, i) => {
        let val
        if (i) {
            val = arr[i] - arr[i - 1]
        } else {
            val = arr[i]
        }
        // filter 0
        if (val) {
            segs.push(val)
        }
    })
    // console.log(segs)

    const dp = []
    segs.forEach((a, i) => {
        if (i) {
            dp[i] = dp[i - 1] + a + a + dp[i - 1]
        } else {
            dp[i] = a
        }
    })
    return calSum(segs) - dp[segs.length - 1]
}

function calSum(arr) {
    return arr.reduce((s, x) => s + x, 0)
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => {
        let next;
        do {
            next = (await getLineGen.next());
        } while (!next.done && next.value === '');
        return next.value;
    };
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const ar = (await getLine()).split(' ').map(num => parseInt(num));
        ar.sort((a,b) => (a-b));
        let sum = ar[n-1];
        for(let i = 1; i < n; i++) {
            sum -= (ar[i] - ar[i-1]) * (i) * (n - i);
        }
        console.log(sum);
    }
}

solve();


You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:   Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$;  Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$;  Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$).

Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it.

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

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

  let n = BigInt(d);
  let isProcessing = true;
  let ans = 0;
  while(isProcessing) {
    if (n % 2n === 0n) {
      n /= 2n;
      ans++;
    }
    else if (n % 3n === 0n) {
      n = 2n * n / 3n;
      ans++;
    }
    else if (n % 5n === 0n) {
      n = 4n * n / 5n;
      ans++;
    }
    else if (n === 1n) {
      isProcessing = false;
    }
    else {
      isProcessing = false;
      ans = -1;
    }
  }

  console.log(ans);

  c++;
});


You are given an integer array $$$a$$$ of length $$$n$$$. Does there exist an array $$$b$$$ consisting of $$$n+1$$$ positive integers such that $$$a_i=\gcd (b_i,b_{i+1})$$$ for all $$$i$$$ ($$$1 \leq i \leq n$$$)? Note that $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^5$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ space-separated integers $$$a_1,a_2,\ldots,a_n$$$ representing the array $$$a$$$ ($$$1 \leq a_i \leq 10^4$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output "YES" if such $$$b$$$ exists, otherwise output "NO". You can print each letter in any case (upper or lower).

NoteIn the first test case, we can take $$$b=[343,343]$$$.In the second test case, one possibility for $$$b$$$ is $$$b=[12,8,6]$$$.In the third test case, it can be proved that there does not exist any array $$$b$$$ that fulfills all the conditions.

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

let inputString = ""
let currentLine = 0

process.stdin.on("data", inputStdin => inputString += inputStdin)

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

const readline = () => inputString[currentLine++]
// Common Template Ends //

// Driver Function Starts //
const main = () => {
    console.clear()
    let t = parseInt(readline())
    while (t--) {
        let n = parseInt(readline())
        let a = readline().split(' ').map(Number)
        console.log(solve(n, a))
    }
}
// Driver Function Ends //

// MAIN LOGIC
const solve = (n, a) => {

    for (let i = 1; i < n - 1; i++) {
        let g = gcd( a[i - 1] , a[i + 1] )
        if( a[i] % g != 0 ) return "NO"
    }

    return "YES"
}

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

const isOdd = (num) => num & 1
const isEven = (num) => !(num & 1)
const minOfArray = (arr) => Math.min.apply(null, arr)
const maxOfArray = (arr) => Math.max.apply(null, arr)
const uniqueArray = (arr) => [...new Set(arr)]
const sortArray = (arr) => arr.sort((a, b) => a - b)
const sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)

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

let inputString = ""
let currentLine = 0

process.stdin.on("data", inputStdin => inputString += inputStdin)

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

const readline = () => inputString[currentLine++]
// Common Template Ends //

// Driver Function Starts //
const main = () => {
    console.clear()
    let t = parseInt(readline())
    while (t--) {
        let n = parseInt(readline())
        let a = readline().split(' ').map(Number)
        console.log(solve(n, a))
    }
}
// Driver Function Ends //

// MAIN LOGIC
const solve = (n, a) => {

    for (let i = 0; i < n - 2; i++) {
        if (gcd(a[i], a[i + 2]) > gcd(a[i], a[i + 1])) {
            return "NO"
        }
    }

    return "YES"
}

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

const isOdd = (num) => num & 1
const isEven = (num) => !(num & 1)
const minOfArray = (arr) => Math.min.apply(null, arr)
const maxOfArray = (arr) => Math.max.apply(null, arr)
const uniqueArray = (arr) => [...new Set(arr)]
const sortArray = (arr) => arr.sort((a, b) => a - b)
const sumOfArray = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0)