One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of lines in the description. Then follow n lines — for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.

Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.

const readline = require('readline');

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

/*
var indicator = 0, cont = new Map(), maxScore = 0, winner = "";

rl.on('line', (input) => {
    if (indicator == 0)
        indicator++;
    else {
        if (cont.has(input))
            cont.set(input, cont.get(input)+1);
        else
            cont.set(input, 1);

        if (maxScore < cont.get(input)) {
            maxScore = cont.get(input);
            winner = input;
        }

    }

  }).on('close',()=> {
      console.log(winner);
  //    console.log(cont);
  });
*/

var indicator = 0, team1Name = "", team2Name = "", score1 = 0, score2 = 0;

rl.on('line', (input)=> {
    if (indicator == 0)
        indicator++;
    else {
        if (input == team1Name)
            score1++;
        else if (input == team2Name)
            score2++;
        else if (team1Name == "") {
            team1Name = input;
            score1++;
        }
        else {
            team2Name = input;
            score2++;
        }
    }
}).on('close', function() {
    console.log((score1 > score2) ? team1Name : team2Name);
});

const readline = require('readline');

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

var indicator = 0, cont = new Map(), maxScore = 0, winner = "";

rl.on('line', (input) => {
    if (indicator == 0)
        indicator++;
    else {
        if (cont.has(input))
            cont.set(input, cont.get(input)+1);
        else
            cont.set(input, 1);

        if (maxScore < cont.get(input)) {
            maxScore = cont.get(input);
            winner = input;
        }

    }

  }).on('close',()=> {
      console.log(winner);
    //  console.log(cont);
  });

const readline = require('readline');
const { SSL_OP_SSLEAY_080_CLIENT_DH_BUG } = require('constants');

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

var n,maxScore=0,myMap={},indicator=SSL_OP_SSLEAY_080_CLIENT_DH_BUG,ans="";

rl.on('line', (input) => {
    if(indicator==0){
       n= parseInt(input);
       indicator++;
    }
    else{
        if(input in myMap)
          myMap[input]++;
          else
          myMap[input]=1;
          if(maxScore<myMap[input]){
              maxScore=myMap[input];
              ans=input;

          }

    }

  }).on('close',()=>{
    console.log(ans);
  });

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  const scores = {};
  while (t--) {
    const score = readLine();
    if (!scores[score]) scores[score] = 1;
    else scores[score]++;
  }
  const keys = Object.keys(scores);
  if (keys.length === 1) console.log(keys[0]);
  else {
    const [k1, k2] = keys;
    if (scores[k1] > scores[k2]) {
      console.log(k1);
    } else {
      console.log(k2);
    }
  }
}

var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);
/*
var n=0;

rl.on('line', function (line) {
var counter=0;
var teams1=[];
var Fcount=0;
var Fteam=0;
    if (arr.length == 0) {
        arr = line.split(' ').map(item => { return parseInt(item) });
        n = arr[0];

    }
    else {

        if (++counter < n) {
             teams1.push(line.split(' ').map(item => { return parseInt(item) }))
             Fteam=teams1[0];

        }
        else {
            teams1.push(line.split(' ').map(item => { return parseInt(item) }));
            }
            for(let i in teams1){
                if(teams1[i]==Fteam)
                    Fcount++;
                     else {
                        Steam=teams1[i] ;
                        Scount++;
            }
               if(Fcount>Scount)
            console.log(Fteam);
                else console.log(Steam);
            rl.close();
        }

    }

}

);
*/
var n = -1;
var dict = {};
rl.on('line', function (line) {
    if (n == -1)
        n = parseInt(line);
    else if (n > 1) {
        if (line in dict)
            dict[line]++;
        else dict[line] = 1;
        n--;

    }
    else {
        if (line in dict)
            dict[line]++;
        else dict[line] = 1;
        var ans,score=0;
        for (var key in dict ){
            var value = dict[key];
            if(score<value){
            score=value;
            ans=key;}
        }
        console.log(ans)

//  console.log(Object.keys(dict));
//console.log(Object.values(dict));
//console.log(JSON.stringify(dict));

        rl.close();
    }

});

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

const store = {};

function main() {
	let n = readLine() >> 0;

	let map = {};
	let maxTeam = { score: 0, team: '' };

	while (n--) {
		let team = readLine();
		map[team] = (map[team] || 0) + 1;

		if (map[team] > maxTeam.score) {
			maxTeam = { score: map[team], team };
		}
	}

	console.log(maxTeam.team);
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}
function main() {
    let stringsArray = [];
    let n = parseInt(readLine());
    for (let i = 0; i < n; i++) {
        stringsArray.push(readLine());
    }
    let first = [];
    let second = [];
    for (let i = 0; i < n; i++) {
        let x = stringsArray[0];
        stringsArray.forEach((team) => {
            if (team === x) {
                first.push(team);
            } else {
                second.push(team);
            }
        });
    }
    if (first.length > second.length) {
        console.log(first[0]);
    } else {
        console.log(second[0]);
    }
}

var n = +readline();
var cnt = {};
while (n--) {
	var name = readline();
	if (!cnt[name]) cnt[name] = 0;
	cnt[name]++;
}

var ans = '';
var max = 0;
for (var name in cnt)
	if (cnt[name] > max)
		max = cnt[name], ans = name;

print(ans);

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

var n = rdn();

var t1, t2, s1 = 0, s2 = 0;

for(var i = 0; i < n; i++){
    var name = readline();
    if(!t1){
        t1 = name;
        s1++;
    }
    if(!t2 && t1 != name){
        t2 = name;
        s2++;
    }

    if(name == t1) s1++;
    if(name == t2) s2++;
}

var ans;
if(s1 > s2){
    ans = t1;
}else{
    ans = t2;
}

write(ans);

var n = +readline();
var teams={};
for (var i = 0; i < n; i++) {
	var element = readline();
	if(teams[element]){
		teams[element] +=1;
	} else {
		teams[element]=1;
	}
}
print(
	teams[Object.keys(teams)[0]] > (teams[Object.keys(teams)[1]]|| 0)
	 ? Object.getOwnPropertyNames(teams)[0]
	 : Object.getOwnPropertyNames(teams)[1]
	 );

var numGoals = readline();
var teams = [[],[]];
var goal;
for(var i = numGoals; i; i--){
	goal = readline();
	if(!teams[0].length){
		teams[0].push(goal);
	} else if(goal == teams[0][0]){
		teams[0].push(goal);
	} else{
		teams[1].push(goal);
	}
}

print(teams[0].length > teams[1].length? teams[0][0] : teams[1][0]);

var n = +readline();
var counter = {};
for (var i = 0; i < n; i++) {
    var name = readline();
    if (!counter[name]) {
        counter[name] = 0
    }
    counter[name] += 1
}
var command_names = Object.keys(counter);
print(command_names[Number(command_names.length == 2 && counter[command_names[1]] > counter[command_names[0]])]);

var n = +readline();
var counter = {};
var command_names = [];
for (var i = 0; i < n; i++) {
    var command_name = readline();
    if (counter[command_name]) {
        counter[command_name] += 1
    } else {
        command_names.push(command_name);
        counter[command_name] = 1
    }
}
if (command_names.length == 1 || counter[command_names[0]] > counter[command_names[1]]) {
    print(command_names[0])
} else {
    print(command_names[1])
}

var numberOfGoal = Number(readline())

var scores = {}
for (var i = 0; i < numberOfGoal; i++) {
  var goal = readline()
  var scored = scores[goal]
  if (scored == null) {
    scores[goal] = 1
  } else {
    scored += 1
    scores[goal] = scored
  }
}
var team = Object.keys(scores)

var scoreTeamOne = scores[team[0]] || 0
var scoreTeamTwo = scores[team[1]] || 0

if (scoreTeamOne > scoreTeamTwo) {
  print(team[0])
} else {
  print(team[1])
}

;(function () {

	var n = +readline();
	var k1n = '', k1s = 0;
	var k2n = '', k2s = 0;

	while (n--) {
		var s = readline();

		if (k1n === '' || k1n === s) {
			k1n = s;
			k1s++;
		} else {
			k2n = s;
			k2s++;
		}
	}

	print(k1s > k2s ? k1n : k2n);

}).call(this)

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 numGoals = parseInt(readline());
	var teamGoals = {},
		teamNames = [];
	for (var lineIndex = 0; lineIndex < numGoals; ++lineIndex) {
		var teamName = trim(readline());
		if (teamGoals[teamName] === undefined) {
			teamNames.push(teamName);
			teamGoals[teamName] = 1;
		}
		else {
			teamGoals[teamName] += 1;
		}
	}
	if (teamNames.length == 1) {
		print(teamNames[0]);
	}
	else {
		print(teamNames[teamGoals[teamNames[0]] > teamGoals[teamNames[1]] ?
				0 : 1]);
	}
}

main();

'use strict'

let N = +readline()
let lll
let s = {}
while (lll = readline()) {
  s[lll] = s[lll] || 0
  s[lll]++
}

let ts = Object.keys(s)
print(!(s[ts[0]] < s[ts[1]]) ? ts[0] : ts[1])

var lineas = readline();
var equipo1 = [];
var equipo2 = [];
for (var i = 0; i < lineas; i++){
    var palabra = readline();
    if (i === 0) {
         equipo1.push(palabra);
        continue;
    }
    if (equipo1[0] == palabra) {
         equipo1.push(palabra);
    } else {
         equipo2.push(palabra);
    }
}
equipo1.length > equipo2.length ? print(equipo1[0]) : print(equipo2[0]);

var tokenizer;
var index = 0;

function next(){
    while(tokenizer == null || index == tokenizer.length){
        tokenizer = readline().split(" ");
        index = 0;
    }
    var res = tokenizer[index++];
    return res;
}

function nextInt(){
    return parseInt(next());
}

function nextFloat(){
    return parseFloat(next());
}

function solve(){
    var n = nextInt();
    var a = {};
    for(var i = 0; i < n; ++i){
        var s = next();
        if(s in a){
            a[s]++;
        } else {
            a[s] = 1;
        }
    }
    var min = 0;
    var winner;
    for(var team in a){
        if(a[team] > min){
            winner = team;
            min = a[team];
        }
    }
    print(winner);
}
solve();

var n = readline();
a = readline();
var res1 = 1;
var res2 = 0;
for(i = 1; i < n; i++){
    s = readline();
    if(a != s){
        b = s;
         res2++;
    }
    else{
        res1++;
    }
}
print((res1 > res2)? a : b);

var n = readline();
teama = readline();
var one = 1;
var two = 0;
	for (var i=1; i<+n; i++){
		temp = readline();
		if (temp!=teama)	{
			teamb = temp;
			two++;
		}
		else one++;
	}
print((one>two)? teama:teamb)

var number = +readline();
var name;
var teamNames = [];
var winner;
var k;
var max = 0;

while (number--) {
	name = readline();
	teamNames.push(name);
}
if (teamNames.length === 1){
    winner = teamNames[0];
}
teamNames.sort();
for (var i = 0; i<teamNames.length; ++i) {
		k = 1;
		for (var j = i + 1; j<teamNames.length; ++j)  {
			if (teamNames[i] === teamNames[j]) {
				++k;
			}
			if (k > max) {
				max = k,
				winner = teamNames[i];
			}
		}
}
print(winner);

var n = parseInt(readline());
var hash = {};
var max = 0;
var winner = "";
for (var i = 0; i < n; i++) {
	var team = readline();
	if (hash[team]) {
		hash[team]++;
	} else {
		hash[team] = 1;
	}
}

for (var key in hash) {
	if (hash.hasOwnProperty(key)) {
		if (hash[key] > max) {
			max = hash[key];
			winner = key;
		}
	}
}

print(winner);

var nums = parseInt(readline());

var obj = {};

while (nums--){
    var winner = readline();

    if (!(winner in obj)) {
        obj[winner] = 1;
    } else {
        obj[winner]++;
    }
}

var teams = Object.keys(obj);
if (teams.length === 1 || obj[teams[0]] > obj[teams[1]]) {
    print(teams[0])
} else {
    print(teams[1]);
}

var nums = parseInt(readline());

var obj = {};

for (var i = 0; i < nums; i++) {
    var winner = readline();

    if (!(winner in obj)) {
        obj[winner] = 1;
    } else {
        obj[winner]++;
    }
}

var teams = Object.keys(obj);
if (teams.length === 1 || obj[teams[0]] > obj[teams[1]]) {
    print(teams[0])
} else {
    print(teams[1]);
}

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

function main(){
    var n = readline();
    var commands = {};
    var arr = [];
    for(var i = 0; i < n; i++){
        var str = readline();
        if(arr.indexOf(str) == -1)
            arr.push(str);
        if(!(str in commands))
            commands[str] = 1;
        else
            commands[str]++;
    }
    if(arr.length == 1)
        print(arr[0]);
    else if(commands[arr[0]] > commands[arr[1]])
        print(arr[0]);
    else
        print(arr[1]);
}
main();

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

var n = rdn();

var t1, t2, s1 = 0, s2 = 0;

for(var i = 0; i < n; i++){
    var name = readline();
    if(!t1){
        t1 = name;
        s1++;
    }
    if(!t2){
        t2 = name;
        s2++
    }

    if(name == t1) s1++;
    if(name == t2) s2++;
}

var ans;
if(s1 > s2){
    ans = t1;
}else{
    ans = t2;
}

write(ans);

var n = +readline();
var teams={};
for (var i = 0; i < n; i++) {
	var element = readline();
	if(teams[element]){
		teams[element] +=1;
	} else {
		teams[element]=1;
	}
}
print(
	teams[Object.keys(teams)[0]] > teams[Object.keys(teams)[1]]|| 0
	 ? Object.getOwnPropertyNames(teams)[0]
	 : Object.getOwnPropertyNames(teams)[1]
	 );

;(function () {

	var n = +readline();
	var k1n = '', k1s = 0;
	var k2n = '', k2s = 0;

	while (n--) {
		var s = readline();

		if (k1n === '' && k1n === s) {
			k1n = s;
			k1s++;
		} else {
			k2n = s;
			k2s++;
		}
	}

	print(k1s > k2s ? k1n : k2n);

}).call(this)

var n = Number(readline());
teama = readline();
var one = 0;
var two = 0;
	for (var i=0; i<n; i++){
		temp = readline();
		if (temp!=teama)	{
			var teamb = temp;
			two++;
		}
		else one++;
	}
print((one>two)? teama:teamb)

n = Number(readline());
teama = readline();
teamb="";
one = 0;
two = 0;
res = 0;
	for (var i=0; i<n; i++){
		temp = readline();
		if (temp!=teama)	{
			teamb = temp;
			two++;
		}
		else one++;
	}
print(one>two? teama:teamb)

var n = Number(readline());
teama = readline();
var teamb;
var one = 0;
var two = 0;
	for (var i=0; i<n; i++){
		temp = readline();
		if (temp!=teama)	{
			teamb = temp;
			two++;
		}
		else one++;
	}
print((one>two)? teama:teamb)

var n = Number(readline());
teama = readline();
var one = 1;
var two = 0;
	for (var i=0; i<n; i++){
		temp = readline();
		if (temp!=teama)	{
			var teamb = temp;
			two++;
		}
		else one++;
	}
print((one>two)? teama:teamb)

'use strict';
var football43A = function() {
var number = +readline();
var name;
var teamNames = [];
var winner;
var k;
var max = 0;

while (number--) {
	name = readline();
	teamNames.push(name);
}
teamNames.sort();
for (var i = 0; i<teamNames.length; ++i) {
		k = 1;
		for (var j = i + 1; j<teamNames.length; ++j)  {
			if (teamNames[i] === teamNames[j]) {
				++k;
			}
			if (k > max) {
				max = k,
				winner = teamNames[i];
			}
		}
}
return winner;
}
football43A();

'use strict';
var football43A = function() {
var number = +readline();
var name;
var teamNames = [];
var winner;
var k;
var max = 0;

while (number--) {
	name = readline();
	teamNames.push(name);
}
teamNames.sort();
for (var i = 0; i<teamNames.length; ++i) {
		k = 1;
		for (var j = i + 1; j<teamNames.length; ++j)  {
			if (teamNames[i] === teamNames[j]) {
				++k;
			}
			if (k > max) {
				max = k,
				winner = teamNames[i];
			}
		}
}
print(winner);
}
football43A();

'use strict';
var number = +readline();
var name;
var teamNames = [];
var winner;
var k;
var max = 0;

while (number--) {
	name = readline();
	teamNames.push(name);
}
teamNames.sort();
for (var i = 0; i<teamNames.length; ++i) {
		k = 1;
		for (var j = i + 1; j<teamNames.length; ++j)  {
			if (teamNames[i] === teamNames[j]) {
				++k;
			}
			if (k > max) {
				max = k,
				winner = teamNames[i];
			}
		}
}
print(winner);

var nums = parseInt(readline());

var obj = {};

for (var i = 0; i < nums; i++) {
    var winner = readline();

    if (!(winner in obj)) {
        obj[winner] = 1;
    } else {
        obj[winner]++;
    }
}

var teams = Object.keys(obj);
if (obj[teams[0]] > obj[teams[1]]) {
    print(teams[0])
} else {
    print(teams[1]);
}

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

function main(){
    var n = readline();
    var commands = {};
    var arr = [];
    for(var i = 0; i < n; i++){
        var str = readline();
        if(arr.indexOf(str) == -1)
            arr.push(str);
        if(!(str in commands))
            commands[str] = 1;
        else
            commands[str]++;
    }
    if(commands[arr[0]] > commands[arr[1]])
        print(arr[0]);
    else
        print(arr[1]);
}
main();


Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.For example, Zookeeper can use two such operations: AABABBA $$$\to$$$ AABBA $$$\to$$$ AAA.Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 20000)$$$  — the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains a single test case each, consisting of a non-empty string $$$s$$$: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of $$$s$$$ are either 'A' or 'B'. It is guaranteed that the sum of $$$|s|$$$ (length of $$$s$$$) among all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer: the length of the shortest string that Zookeeper can make.

NoteFor the first test case, you can't make any moves, so the answer is $$$3$$$.For the second test case, one optimal sequence of moves is BABA $$$\to$$$ BA. So, the answer is $$$2$$$.For the third test case, one optimal sequence of moves is AABBBABBBB $$$\to$$$ AABBBABB $$$\to$$$ AABBBB $$$\to$$$ ABBB $$$\to$$$ AB $$$\to$$$ (empty string). So, the answer is $$$0$$$.

var tc = parseInt(readline());
for (; tc--;){
    var str = readline();
    var ar = [];
    for (var i = 0; i < str.length; i++) {
      ar.push(str[i]);
      if (ar.length > 1) {
          var Last = ar[ar.length - 2] + ar[ar.length - 1];

          while (Last === "AB" || Last === "BB") {
          ar.pop(); ar.pop();
          Last = ar[ar.length - 2] + ar[ar.length - 1];
        }
      }
    }
    print(ar.length);
}

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

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

  data.push(line);

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

});

function goToSolution(data) {
  data.forEach(srt => {

    let stack = [];
    for(let i = 0; i < srt.length; i++) {
      stack.push(srt[i]);
      if(stack.length > 1) {
        let stackLast = stack[stack.length - 2] + stack[stack.length - 1];
        while(stackLast === "AB" || stackLast === "BB") {
          stack.pop();
          stack.pop();
          stackLast = stack[stack.length - 2] + stack[stack.length - 1];
        }
      }
    }
    console.log(stack.length)

  })
}

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

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

function main() {
  let t = +readLine();
  while (t--) {
    const str = readLine();
    const stack = [];

    for (let i = 0; i < str.length; i++) {
      const char = str[i];
      if (stack[stack.length - 1] + char === "AB" || stack[stack.length - 1] + char === "BB") {
        stack.pop();
      } else {
        stack.push(char);
      }
    }
    console.log(stack.length);
  }
}

//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 s = nextCharArray();
		var N = s.length;
		var a = 0;
		var b = 0;
		for(var j = 0; j < N; j++){
			if(s[j] == "A"){
				a++;
				continue;
			}
			if(s[j] == "B"){
				b++;
				if(a > 0){
					a--;
					b--;
				}
			}
		}
		output[i] = b % 2 + a;
	}
	myout(myconv(output, 9));
}

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

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

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

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
function inv(b, m) {
  for (var a = m, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + m) % m;
}

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

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

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

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

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
async function main() {
  let inp = input.split(/\s+/), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math,
    bi = BigInt, rand = n => Math.random() * n | 0;

  let t = +$()
  while (t--) {
    let s = $()
    let n = s.length;
    let sa = Arr(n, i => 0)
    let sb = Arr(n, i => 0)
    if (s[0] == 'A') { sa[0] = 1; sb[0] = 1e6 }
    else { sb[0] = 1; sa[0] = 1e6 }
    For(1, n - 1, i => {
      if (s[i] == 'A') {
        sa[i] = sa[i - 1] + 1;
        sb[i] = sb[i - 1] + 1;
      } else {
        // if (s[i-1] == 'B') {
        //   sa[i]
        // }
        sb[i] = sb[i - 1] - 1;
        if (sb[i] < 0) sb[i] = 1;
        sa[i] = sa[i - 1] - 1;
        if (sa[i] < 0) { sa[i] = 1e6; sb[i] = 1; }
      }
    })
    // log(sa)
    // log(sb)
    log(min(sa[n - 1], sb[n - 1]))
  }
}

const input = [];

function splbsi(line) {
  return line.split(" ").map((x) => parseInt(x));
}

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

readLine.on("line", (line) => {
  input.push(line);
});

readLine.on("close", () => {
  for (let i = 1; i < input.length; i += 1) {
    const str = input[i];

    let countA = 0,
      countB = 0;
    let answer = 0;
    for (const char of [...str]) {
      if (char === "A") {
        countA += 1;
      } else if (countA > 0) {
        answer += 1;
        countA -= 1;
      } else {
        countB += 1;
      }
    }

    console.log(countA + (countB % 2))
  }
});

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numCases = readLine();
    for (let i = 0; i < numCases; i++) {
        let input = readLine();
        let toBeRemoved = 0;
        let beginningB = 0;
        let overhangA = 0;
        for (let k = 0; k < input.length; k++) {
            const letter = input[k];
            if (letter === 'A') {
                overhangA++;
            }
            else if (letter === 'B' && overhangA > 0) {
                overhangA--;
                toBeRemoved += 2;
            } else {
                beginningB++;
            }
        }
        console.log(overhangA + (beginningB % 2 === 0 ? 0 : 1));
    }
}

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

    ABBB();
});

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 ABBB(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let s = readline().split('');
        let st = [];
        let i = 0;
        while(i < s.length){
            if(s[i] === 'A'){
                st.push(s[i]);
                i++;
            }else{
                if(st[st.length-1] === 'A'){
                    st.pop();
                    i++;
                }else{
                    st.push(s[i]);
                    i++;
                }
            }
        }

        let countA = 0;
        let countB = 0;
        if(st.length > 0){
            while(st.length > 0){
                if(st.pop() === 'A')
                    countA++;
                else
                    countB++;
            }
        }
        console.log(countA + countB % 2);
    }
}

const input = [];

function splbsi(line) {
  return line.split(" ").map((x) => parseInt(x));
}

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

readLine.on("line", (line) => {
  input.push(line);
});

readLine.on("close", () => {
  for (let i = 1; i < input.length; i += 1) {
    const str = input[i];

    // AABBBABBBB
    const stack = [];
    let answer = 0,
      countB = 0;
    let countA = [...str].reduce((count, char) => {
      if (char === "A") count += 1;
      return count;
    }, 0);
    for (const char of [...str]) {
      if (char === "A") {
        stack.push("A");
        countB = 0;
      } else {

        if (stack.length > 0) {
          stack.pop();
          answer += 2;
          countA -= 1;
        } else {
          countB += 1;

          if (countB % 2 === 0) {
            answer += 2;
            countB -= 2;
          }
        }
      }
    }

    if (countA === 0) {
      const res = str.length - answer;
      console.log(res % 2);
    } else console.log(str.length - answer);
  }
});


Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.Initially there are k cycles, i-th of them consisting of exactly vi vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, x vertices) among all available cycles and replace it by two cycles with p and x - p vertices where 1 ≤ p < x is chosen by the player. The player who cannot make a move loses the game (and his life!).Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the i-th test he adds a cycle with ai vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins? Peter is pretty good at math, but now he asks you to help.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of tests Peter is about to make. The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), i-th of them stands for the number of vertices in the cycle added before the i-th test.

Print the result of all tests in order they are performed. Print 1 if the player who moves first wins or 2 otherwise.

NoteIn the first sample test:In Peter's first test, there's only one cycle with 1 vertex. First player cannot make a move and loses.In his second test, there's one cycle with 1 vertex and one with 2. No one can make a move on the cycle with 1 vertex. First player can replace the second cycle with two cycles of 1 vertex and second player can't make any move and loses.In his third test, cycles have 1, 2 and 3 vertices. Like last test, no one can make a move on the first cycle. First player can replace the third cycle with one cycle with size 1 and one with size 2. Now cycles have 1, 1, 2, 2 vertices. Second player's only move is to replace a cycle of size 2 with 2 cycles of size 1. And cycles are 1, 1, 1, 1, 2. First player replaces the last cycle with 2 cycles with size 1 and wins.In the second sample test:Having cycles of size 1 is like not having them (because no one can make a move on them). In Peter's third test: There a cycle of size 5 (others don't matter). First player has two options: replace it with cycles of sizes 1 and 4 or 2 and 3.  If he replaces it with cycles of sizes 1 and 4: Only second cycle matters. Second player will replace it with 2 cycles of sizes 2. First player's only option to replace one of them with two cycles of size 1. Second player does the same thing with the other cycle. First player can't make any move and loses.  If he replaces it with cycles of sizes 2 and 3: Second player will replace the cycle of size 3 with two of sizes 1 and 2. Now only cycles with more than one vertex are two cycles of size 2. As shown in previous case, with 2 cycles of size 2 second player wins. So, either way first player loses.

var n = readline();
var arr = readline().split(' ').map(Number);

var cycle = 0;
 for(var i = 0; i < n; i++){
  cycle += arr[i] - 1;
  if( cycle %2 == 0 ) {

    print(2);
  } else {

    print(1);
  }
 }

/*
    The idea to solve this problem is basically we count the needed movement
    to complete the game in each test. Complete means no players can move anymore.

    Since peter move initially, so in order to win, the movement needed to complete
    the game must be even.
*/

var n = parseInt(readline());
var cycles = readline().split(' ').map(Number);
var move = 0;

for(var i = 0; i < n; i++) {

    move += cycles[i] - 1; // the movement needed to reduce cycle value into 1, note that the rule to breakdown is 1 <= p < x, so the movement needed will always follow this pattern (for any x value)
    if(move % 2)
        print(1);
    else
        print(2);
}

/*
    The idea to solve this problem is basically we count the needed movement
    to complete the game in each test. Complete means no players can move anymore.

    Since peter move initially, so in order to win, the movement needed to complete
    the game must be odd.
*/

var n = parseInt(readline());
var cycles = readline().split(' ').map(Number);
var move = 0;

for(var i = 0; i < n; i++) {

    move += cycles[i] - 1; // the movement needed to reduce cycle value into 1, note that the rule to breakdown is 1 <= p < x, so the movement needed will always follow this pattern (for any x value)
    if(move % 2)
        print(1);
    else
        print(2);
}

'use strict';
/*
let input = `
5
1 1 5 1 1
`.trim().split('\n');
function readline() {
	return input.shift();
}
function print(message) {
	console.log(message);
}*/

//code
var n = Number(readline());
var inputArr = readline().split(' ').map(Number);
var modifiedSum = 0;
for (var i = 0; i < n; i++) {
	modifiedSum += inputArr[i] - 1;
	print((modifiedSum%2 === 0) ? 2 : 1);
}


In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.A permutation $$$p$$$ of size $$$n$$$ is given. A permutation of size $$$n$$$ is an array of size $$$n$$$ in which each integer from $$$1$$$ to $$$n$$$ occurs exactly once. For example, $$$[1, 4, 3, 2]$$$ and $$$[4, 2, 1, 3]$$$ are correct permutations while $$$[1, 2, 4]$$$ and $$$[1, 2, 2]$$$ are not.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $$$[1, 5, 2]$$$ currently in the deque, adding an element $$$4$$$ to the beginning will produce the sequence $$$[\color{red}{4}, 1, 5, 2]$$$, and adding same element to the end will produce $$$[1, 5, 2, \color{red}{4}]$$$.The elements of the permutation are sequentially added to the initially empty deque, starting with $$$p_1$$$ and finishing with $$$p_n$$$. Before adding each element to the deque, you may choose whether to add it to the beginning or the end.For example, if we consider a permutation $$$p = [3, 1, 2, 4]$$$, one of the possible sequences of actions looks like this: $$$\quad$$$ 1.add $$$3$$$ to the end of the deque:deque has a sequence $$$[\color{red}{3}]$$$ in it;$$$\quad$$$ 2.add $$$1$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{1}, 3]$$$ in it;$$$\quad$$$ 3.add $$$2$$$ to the end of the deque:deque has a sequence $$$[1, 3, \color{red}{2}]$$$ in it;$$$\quad$$$ 4.add $$$4$$$ to the end of the deque:deque has a sequence $$$[1, 3, 2, \color{red}{4}]$$$ in it;Find the lexicographically smallest possible sequence of elements in the deque after the entire permutation has been processed. A sequence $$$[x_1, x_2, \ldots, x_n]$$$ is lexicographically smaller than the sequence $$$[y_1, y_2, \ldots, y_n]$$$ if there exists such $$$i \leq n$$$ that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$, $$$\ldots$$$, $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$. In other words, if the sequences $$$x$$$ and $$$y$$$ have some (possibly empty) matching prefix, and the next element of the sequence $$$x$$$ is strictly smaller than the corresponding element of the sequence $$$y$$$. For example, the sequence $$$[1, 3, 2, 4]$$$ is smaller than the sequence $$$[1, 3, 4, 2]$$$ because after the two matching elements $$$[1, 3]$$$ in the start the first sequence has an element $$$2$$$ which is smaller than the corresponding element $$$4$$$ in the second sequence.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases.  The first line of each test case description contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — permutation size. The second line of the description contains $$$n$$$ space-separated integers $$$p_i$$$ ($$$1 \le p_i \le n$$$; all $$$p_i$$$ are all unique) — elements of the permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should contain $$$n$$$ space-separated integer numbers — the elements of the lexicographically smallest permutation that is possible to find in the deque after executing the described algorithm.

NoteOne of the ways to get a lexicographically smallest permutation $$$[1, 3, 2, 4]$$$ from the permutation $$$[3, 1, 2, 4]$$$ (the first sample test case) is described in the problem statement.

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const t = Number(readline());
    for(let i = 0; i < t; i++) {
        let n = Number(readline()), p = readline().split(" ");
        let ans = p[0], head = ans;
        p = p.slice(1);

        for(const num of p) {
            if(parseInt(num) < parseInt(head)) {
                ans = num + " " + ans;
                head = num;
            }else {
                ans += " " + num;
            }
        }
        console.log(ans);
    }
}

"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++];
}
class node {
  constructor(val) {
    this.val = val;
    this.next = null;
  }
}
class dequeue {
  constructor() {
    this.head = null;
    this.tail = null;
  }
  front(val) {
    if (!this.head) return (this.head = this.tail = new node(val));
    let newNode = new node(val);
    newNode.next = this.head;
    return (this.head = newNode);
  }
  back(val) {
    if (!this.tail) return (this.head = this.tail = new node(val));
    let newNode = new node(val);
    this.tail.next = newNode;
    return (this.tail = newNode);
  }
  print() {
    let res = "",
      p = this.head;
    while (p) {
      res += p.val + " ";
      p = p.next;
    }
    console.log(res);
  }
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (arr[0] === 1) console.log(arr.join(" "));
    else {
      let res = new dequeue(),
        min = arr[0];
      for (let i = 0; i < n; i++) {
        if (min > arr[i]) {
          res.front(arr[i]);
          min = arr[i];
        } else res.back(arr[i]);
      }
      res.print();
    }
  }
};
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--) {
		const n = rn();
		const p = rna();

		const ansl = [], ansr = [];

		for (let i = 0, cur = 1e6; i < n; i++) {
			if (p[i] < cur) {
				ansl.push(p[i]);
				cur = p[i];
			} else {
				ansr.push(p[i]);
			}
		}

		console.log(ansl.reverse().join(' '), ansr.join(' '));
	}
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

class LinkedList {
    constructor(value) {
      this.head = {
        value: value,
        next: null
      };
      this.tail = this.head;
      this.length = 1;
    }
    append(value) {
      const newNode = {
        value: value,
        next: null
      }
      if(!this.head.value) {
          this.head.value = value;
          return;
      }
      this.tail.next = newNode;
      this.tail = newNode;
      this.length++;
      return this;
    }
    prepend(value) {
      const newNode = {
        value: value,
        next: null
      }
      if(!this.head.value) {
        this.head.value = value;
        return;
      }
      newNode.next = this.head;
      this.head = newNode;
      this.length++;
      return this;
    }
    printList() {
      const array = [];
      let currentNode = this.head;
      while(currentNode !== null){
          array.push(currentNode.value)
          currentNode = currentNode.next
      }
      return array;
    }
  }

function main() {
   const t = parseInt(readline());
   for (let i = 0; i < t; i++){
        const n = parseInt(readline());
        const list = new LinkedList();
        readline().split(' ').map((str) => {
            const item = parseInt(str);
            if(!list.head || item <= list.head.value){
                list.prepend(item);
            }else{
                list.append(item);
            }
        });
        console.log(list.printList().join(' '))
   }

}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const t = Number(readline());
    for(let i = 0; i < t; i++) {
        const n = Number(readline()), p = readline().split(" ");
        let str = p.shift(), ans = str;

        for(const num of p) {
            if(num + str[0] < str.slice(0, num.length + 1)) {
                str = num + str
                ans = num + " " + ans;
            }else {
                str += num;
                ans += " " + num;
            }
        }
        console.log(ans);
        }
    }

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const t = Number(readline());
    for(let i = 0; i < t; i++) {
        const n = Number(readline()), p = readline().split(" ");
        let head = p[0];
        for(let i = 1; i < n; i++) {
            if(p[i] < head) {
                head = p[i];
                p.splice(i, 1);
                p.unshift(head);
            }
        }
        console.log(p.join(" "));
        }
    }

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const t = Number(readline());
    for(let i = 0; i < t; i++) {
        const n = Number(readline()), p = readline().split(" ");
        let str = p.shift();
        for(const num of p) {
            if(num < str[0]) str = num + str;
            else str += num;
        }
        console.log(str);
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const t = Number(readline());
    for(let i = 0; i < t; i++) {
        const n = Number(readline());
        let p = readline().split(" "), min = Number(p.join("")), myArrs = [[p.shift()]];
        for(const num of p) {
            const myNewArrs = [];
            for(const arr of myArrs) {
                if(arr.length == n) {
                    let str = arr.join("");
                    min = Math.min(Number(str + num), Number(num + str), min);
                }
                myNewArrs.push(arr.concat([num]));
                myNewArrs.push([num].concat(arr));
            }
            myArrs = myNewArrs;
        }
        console.log(String(min).split("").join(" "));
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const t = Number(readline());
    for(let i = 0; i < t; i++) {
        const n = Number(readline());
        let p = readline().split(" "), min = Number(p.join("")), myArrs = [p.shift()];
        for(const num of p) {
            const myNewArrs = [];
            for(const arr of myArrs) {
                if(arr.length == n) {
                    let str = arr.join("");
                    min = Math.min(Number(str + num), Number(num + str), min);
                }
                myNewArrs.push(arr.concat([num]));
                myNewArrs.push([num].concat(arr));
            }
            myArrs = myNewArrs;
        }
        console.log(String(min).split("").join(" "));
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const t = Number(readline());
    for(let i = 0; i < t; i++) {
        const n = Number(readline()), p = readline().split(" "), arr = [p[0]];
        let min = Number(p.join(""));
        function permutations(p, index, arr, n) {
            for(let option = 0; option < 2; option++) {
                if(index == n) {
                    min = Math.min(min, Number(arr.join("")));
                    return;
                }
                if(option == 0) {
                    permutations(p, index + 1, [p[index]].concat(arr), n);
                }
                if(option == 1) {
                    permutations(p, index + 1, arr.concat([p[index]]), n);
                }
            }
            return
        }
        permutations(p, 1, arr, n);
        console.log(min);

    }
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let min = Infinity,
      ind = 0;
    for (let i = 1; i < n; i++) {
      if (arr[i] < min) {
        ind = i;
        min = arr[i];
      }
    }
    if (arr[0] > min) {
      let res = [];
      res.push(arr[ind]);
      for (let i = 0; i < n; i++) {
        if (ind !== i) res.push(arr[i]);
      }
      console.log(res.join(" "));
    } else console.log(arr.join(" "));
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let min = Infinity,
      ind = 0;
    for (let i = 1; i < n; i++) {
      if (arr[i] < min) {
        ind = i;
        min = arr[i];
      }
    }
    if (arr[0] > min) {
      [arr[0], arr[ind]] = [arr[ind], arr[0]];
    }
    console.log(arr.join(" "));
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    for (let i = 0; i < n - 1; i++) {
      if (arr[0] > arr[i + 1]) {
        let k = i + 1,
          j = i + 1;
        while (j < n) {
          if (arr[k] > arr[j]) k = j;
          j++;
        }
        [arr[i], arr[k]] = [arr[k], arr[i]];
        break;
      }
    }
    console.log(arr.join(" "));
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    for (let i = 0; i < n - 1; i++) {
      if (arr[i] > arr[i + 1]) {
        let k = i + 1,
          j = i + 1;
        while (j < n) {
          if (arr[k] > arr[j]) k = j;
          j++;
        }
        [arr[i], arr[k]] = [arr[k], arr[i]];
        break;
      }
    }
    console.log(arr.join(" "));
  }
};
solve();


New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.

The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.

If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".

NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.

function main() {
    let n = parseInt(read()),
        t = parseInt(read());

    let arr = [];
    for (let i = 0; i < n - 1; i++) {
        let x = parseInt(read());
        arr.push(x);
    }

    let p = 0;
    while (p < t - 1) {
        p += arr[p];
    }
    if (p === t - 1) {
        writeline("YES");
    } else {
        writeline("NO");
    }

    return 0;
}

var input = "";
var read;
var writeline = (x) => process.stdout.write(x + "\n");
var write = (x) => process.stdout.write(x);

process.stdin.resume();
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => input += chunk);
process.stdin.on("end", () => {
    input = input.split(/\s+/);
    read = () => input.shift();
    process.exit(main() || 0);
});

// 500A - New Year Transportation
// http://codeforces.com/problemset/problem/500/A

process.stdin.resume();
process.stdin.setEncoding("utf8");

// var getline;
var input = "";
var read;
var writeline = (x) => process.stdout.write(x + "\n");
var write = (x) => process.stdout.write(x);

process.stdin.on("data", (chunk) => input += chunk);
process.stdin.on("end", () => {
    // input = input.split(/\r?\n/);
    // getline = () => input.shift();
    input = input.split(/\s+/);
    read = () => input.shift();
    process.exit(main() || 0);
});

function main() {
    let n = parseInt(read()),
        t = parseInt(read());

    let arr = [];
    for (let i = 0; i < n - 1; i++) {
        let x = parseInt(read());
        arr.push(x);
    }

    let p = 0;
    while (p < t - 1) {
        p += arr[p];
    }
    if (p === t - 1) {
        writeline("YES");
    } else {
        writeline("NO");
    }

    return 0;
}

//NYTransport.js
"use strict"
const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin
});
var count=0,
    arr=[],
    arr2=[],
    x,y,i;
rl.question('', (nb) => {
  rl.on('line', (TC) => {
    arr = nb.split(' ');
    arr2 = TC.split(' ');
    y = Number(arr[1]); //dest
    i=0;
    while(i<y){
      i = i+Number(arr2[i]);
      if(i === y-1){
        console.log("YES");
        rl.close();
        break;
      }else if(i > y-1){
        console.log("NO");
        rl.close();
        break;
      }
    }
  });
});

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

const input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  const [n, t] = input[0].split(' ').map(x => parseInt(x));
  const nums = input[1].split(' ').map(x => parseInt(x));

  let now = 1; if (t === now) { console.log('YES'); return; }
  for (let i = 0; i < nums.length;) {
    now = nums[i] + (i+1);
    if (t === now) {
      console.log('YES'); return;
    }
    i += nums[i];
  }

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

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

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

function main() {
	let [n, t] = readLine()
		.split(' ')
		.map(x => parseInt(x));

	const a = readLine()
		.split(' ')
		.map(x => parseInt(x));

	const graphHash = {};

	for (let i = 1; i <= n - 1; ++i) {
		graphHash[i] = i + a[i - 1];
	}

	const stack = [1];
	let found = false;

	while (stack.length > 0) {
		let u = stack.pop();

		if (graphHash[u] !== undefined) {
			if (graphHash[u] == t) {
				found = true;
				break;
			} else {
				stack.push(graphHash[u]);
			}
		}
	}

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

let fs=require("fs");
let txt=fs.readFileSync(0,"utf-8").split(/[\r\n]/).filter(data=>data.length);
for (let i = 0; i < txt.length; i+=2) {
    let info=txt[i].split(" ")[1]*1;
    doit(info,txt[i+1].split(" ").filter(data=>data.length>0).map(data=>data*1));

}

function doit(target,arr){
    let current=1;
    while (true) {
        if(current-1>=arr.length){
            console.log("NO");
            return;
        }
        current=current+arr[current-1];
        if(current==target){
            console.log("YES");
            return;
        }else if(current>target){
            console.log("NO");
            return;
        }
    }

}

var input1 = readline().split(" "), input2 = readline().split(" ");
var n = +input1[0], t = +input1[1] - 1, cells = [];
for(i = 0; i < n-1; i++){
	cells.push(i + +input2[i]);
}
cells.push(0);

if(cells.indexOf(t) + 1){
	for(i = 0; ; ){
		i = cells[i];
		if(i == t){
			write("YES");
			break;
		}
		else if( i > t){
			write("NO");
			break;
		}
	}
}
else{
	write("NO");
}

nt = readline().split(' ').map(Number); n=nt[0]; t=nt[1]; x=1;
a = readline().split(' ').map(Number);
while(x<t) { x += a[x-1] }
write(x === t ? 'YES' : 'NO');

function readNumbersArray () {
	return readline().split(' ').map(Number);
}

var array = readNumbersArray(),
	size = array[0],
	target = array[1],
	a = readNumbersArray(),
	position = 1;

while (position < target && position < size) {
	position += a[position - 1];
}

print(position === target ? 'YES' : 'NO');

var s = readline().split(" ");
var n = Number(s[0]), t = Number(s[1])-1;
s = readline().split(" ");
var i = 0;
var weCan = false;
while(i<n) {
    if (i == t) {
        weCan = true;
        break;
    }
    i+=Number(s[i]);
}
if (weCan) {
    print('YES');
}
else {
    print('NO');
}

var line = readline().split(' '), n = +line[0], t = +line[1];
var arr = readline().split(' ');
var str, b = false, res, next = 1, now = 0;

while(next < n) {
    next = next + (+arr[next - 1]);
    if (next == t) {
        b = true;
        break;
    }
}

if (b)
    print("YES");
else
    print("NO");

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

(function() {
  let array_1 = readline().getNumArray(),
    n = array_1[0],
    t = array_1[1],
    array_2 = readline().getNumArray();

  for (let i = 1; i <= t; i+=array_2[i - 1]) {
    if (i === t) {
      write('YES');
      return;
    }
  }
write('NO');
})();

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

n = numbers[0];
t = numbers[1] - 1;

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

ans = "NO"
cur = 0
while(cur < t){
    cur += numbers[cur]
    if(cur == t){
        ans = "YES"
    }
}

print(ans)

var s = readline().split(" ");
var str =  readline().split(" ");
var f = 1;
		for (var i=0; i<+s[0]; i++){
			if (f==+s[1]){
				f = 1;
				break;}
				f+=+str[f-1]
		}
f==1? print("YES"):print("NO");

var p = readline().split(" ").map(function(x) { return parseInt(x); })[1] - 1;
var ar = readline().split(" ").map(function(x) { return parseInt(x); });
var pos = 0, found;
while(true){
  if (pos == p) {
    found = 'YES';
    break;
  } else if (pos > p){
    found = 'NO';
    break;
  }
  pos = pos + ar[pos];
}
print (found);

// var n = 4;
// var t = 4;

// var world = [2, 2, 1];

var nt = readline().split(' ');
var n = Number(nt[0]);
var t = Number(nt[1]);

var world = readline().split(' ').map(Number);
var res = 'NO';
var i = 0;

while (i <= n - 1) {
	var portal = i + 1;

	if (i + 1 == t) {
		res = 'YES';
	}

	i = portal + world[i] - 1;
}

//console.log(res);
print(res);

var params = readline().split(" ").map(value => +value);
var n = params[0], t = params[1];
var portals = readline().split(" ").map(value => +value);

var i = 0, flag = false;
while(i < n - 1) {
	if (portals[i] + i + 1 === t) {
		flag = true;
		break;
	}

	i += portals[i];
}

print(flag ? "YES" : "NO");

function sa(n,t,data){

        var current = 1;
        while(current <= t){
            if(current == t){
                return "YES";
            }
            current = current + data[current -1];
        }

        return "NO"
    }

    var f = readline().split(" ").map(Number);
    var n = f[0];
    var t = f[1];
    var data = readline().split(" ").map(Number);

    print(sa(n,t,data));

var input = readline().split(' ').map(value => +value);
var n = input[0];
var t = input[1];
var a = readline().split(' ').map(value => +value);

var p = 1;

while (p < t) {
    p += a[p - 1];
}

write(p === t ? 'YES' : 'NO');

(function() {
    var input = readline().split(' ');
    var n = parseInt(input[0]);
    var t = parseInt(input[1]);
    var e = readline().split(' ');
    var cur = 1;
    while (cur < n) {
        if (cur == t) {
            break;
        }
        cur = cur + parseInt(e[cur - 1]);
    }
    if (cur == t) {
        write('YES');
    } else {
        write('NO');
    }
})()

var input = readline().split(' ').map(Number), n = input[0], t = input[1];
var a = readline().split(' ').map(Number);
var queue = [];
var flag = false;
queue.push(0);
while (queue.length) {
    var pos = queue.pop();
    if (a[pos] + pos + 1 == t) { write('YES'); flag = true; break; }
    else if (a[pos] > 0) queue.push(a[pos] + pos);
    a[pos] = -1;
}
if (!flag) write('NO');

function main()    {
    var cellCount, movedToIndex = readline().split(/\s/gi).map(Number);
    cellCount = movedToIndex[0], movedToIndex = movedToIndex[1];

    var lineList = [0].concat(readline().split(/\s/gi)),
        cellList = [], index = 1,
        result = 'YES';

    while(true)    {
        if(index == movedToIndex)    break;
        if(index > movedToIndex)    {
            result = 'NO';
            break;
        }
        var fromCell = index,
            toCell = fromCell + parseInt(lineList[fromCell]);

        index = toCell;
    };

    print(result);
};
main();

function main() {
	var n, t;
	var line = readline().split(" ").map(Number);
	n = line[0]; t = line[1] - 1;
	var value = readline().split(" ").map(Number);
	value.push(0);

	var cur = 0;
	while (cur != t && value[cur] !== 0) {
		cur += value[cur];
	}

	if (cur == t)
		print("YES");
	else
		print("NO");
}

main();

var r = readline().split(' ');
var n = +r[0];
var t = +r[1];
var a = readline().split(' ');
var result = 'NO';
for (var i = 1; i <= t; ) {
    if (i == t) {
        result = 'YES';
        break;
    } else {
        i += +a[i - 1];
    }
}
print(result);

var input = readline().split(" ").map((x) => parseInt(x));
var location = readline().split(" ").map((x) => parseInt(x));
var position = input[1];
var counter = 1;
var found = false;

if(position > location.length) {
    print("YES");
} else {
    while(counter < location.length) {
        counter = counter + location[counter - 1];

        if(counter === position) {
            print("YES");
            found = true;
            break;
        }
    }

    if(!found) {
        print("NO");
    }
}

(function() {
    var values = readline().split(" ").map(Number);
    var n = values[0] - 1;
    var k = values[1];
    var arr = readline().split(" ").map(Number);
    var save = 1;

    for (var i = 1; i <= arr.length && save <= n; i++) {
        save = arr[save - 1] + save;
        if (save === k) {
            print("YES");
            return;
        }
    }

    print("NO");
})();

const data = readline().split(" ").map(x => parseInt(x));
const a = readline().split(" ").map(x => parseInt(x));
const n = data[0];
const t = data[1];
var canWe = false;
var i = 0;
while (i<t) {
    i = a[i] + i;
    if (i + 1 === t) {
        canWe = true;
        break;
    }
}
print(canWe ? "YES" : "NO");

// 500A - New Year Transportation
// http://codeforces.com/problemset/problem/500/A

process.stdin.resume();
process.stdin.setEncoding("utf8");

// var getline;
var input = "";
var read;
var writeline = (x) => process.stdout.write(x + "\n");
var write = (x) => process.stdout.write(x);

process.stdin.on("data", (chunk) => input += chunk);
process.stdin.on("end", () => {
    // input = input.split(/\r?\n/);
    // getline = () => input.shift();
    input = input.split(/\s+/);
    read = () => input.shift();
    process.exit(main() || 0);
});

function main() {
    let n = parseInt(read()),
        t = parseInt(read());

    let arr = [];
    for (let i = 0; i < n - 1; i++) {
        let x = parseInt(read());
        arr.push(x);
    }

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

    // dfs(0, vis);
    if (vis[t - 1] === 1) {
        writeline("YES");
    } else {
        writeline("NO");
    }

    return 0;
}

// 500A - New Year Transportation
// http://codeforces.com/problemset/problem/500/A

process.stdin.resume();
process.stdin.setEncoding("utf8");

// var getline;
var input = "";
var read;
var writeline = (x) => process.stdout.write(x + "\n");
var write = (x) => process.stdout.write(x);

process.stdin.on("data", (chunk) => input += chunk);
process.stdin.on("end", () => {
    // input = input.split(/\r?\n/);
    // getline = () => input.shift();
    input = input.split(/\s+/);
    read = () => input.shift();
    process.exit(main() || 0);
});

function main() {
    let n = parseInt(read()),
        t = parseInt(read());

    let arr = [];
    for (let i = 0; i < n - 1; i++) {
        let x = parseInt(read());
        arr.push(x);
    }

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

    // dfs(0, vis);
    if (vis[t - 1]) {
        writeline("YES");
    } else {
        writeline("NO");
    }

    return 0;
}

// 500A - New Year Transportation
// http://codeforces.com/problemset/problem/500/A

process.stdin.resume();
process.stdin.setEncoding("utf8");

// var getline;
var input = "";
var read;
var writeline = (x) => process.stdout.write(x + "\n");
var write = (x) => process.stdout.write(x);

process.stdin.on("data", (chunk) => input += chunk);
process.stdin.on("end", () => {
    // input = input.split(/\r?\n/);
    // getline = () => input.shift();
    input = input.split(/\s+/);
    read = () => input.shift();
    process.exit(main() || 0);
});

function main() {
    let n = parseInt(read()),
        t = parseInt(read());

    let g = [...Array(n)].map(x => Array().fill([]));
    let arr = [];
    for (let i = 0; i < n - 1; i++) {
        let x = parseInt(read());
        arr.push(x);
        g[i].push(i + x);
    }

    function dfs(s, vis) {
        vis[s] = 1;
        for (const v of g[s]) {
            if (!vis[v]) {
                dfs(v, vis);
            }
        }
    }

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

    // dfs(0, vis);
    if (vis[t - 1]) {
        writeline("YES");
    } else {
        writeline("NO");
    }

    return 0;
}

//NYTransport.js
"use strict"
const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin
});
var count=0,
    arr=[],
    arr2=[],
    x,y,i;
rl.question('', (nb) => {
  rl.on('line', (TC) => {
    arr = nb.split(' ');
    arr2 = TC.split(' ');
    y = Number(arr[1]); //dest
    for(i = 0; i < y; i++){
      i = i+Number(arr2[i]);
      if(i+1 === y){
        console.log("YES");
        rl.close();
        break;
      }else if(i+1 > y){
        console.log("NO");
        rl.close();
        break;
      }
    }
  });
});

//NYTransport.js
"use strict"
const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin
});
var count=0,
    arr=[],
    arr2=[],
    x,y,i;
rl.question('', (nb) => {
  rl.on('line', (TC) => {
    arr = nb.split(' ');
    arr2 = TC.split(' ');
    y = Number(arr[1]); //dest
    for(i = 0; i < y; i++){
      i = i+Number(arr2[i]);
      if(i === y-1){
        console.log("YES");
        rl.close();
        break;
      }else if(i > y-1){
        console.log("NO");
        rl.close();
        break;
      }
    }
  });
});

//NYTransport.js
"use strict"
const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin
});
var count=0,
    arr=[],
    arr2=[],
    x,y,i;
rl.question('', (nb) => {
  rl.on('line', (TC) => {
    arr = nb.split(' ');
    arr2 = TC.split(' ');
    y = Number(arr[1]); //dest
    for(i = 0; i < y; i++){
      i = i+Number(arr2[i]);
      console.log(i)
      if(i+1 === y){
        console.log("YES");
        rl.close();
        break;
      }else if(i+1 > y){
        console.log("NO");
        rl.close();
        break;
      }
    }
  });
});

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

const input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  const [n, t] = input[0].split(' ').map(x => parseInt(x));
  const nums = input[1].split(' ').map(x => parseInt(x));

  let now = 1; if (t === now) { console.log('YES'); return; }
  for (let i = 0; i < nums.length; i += 1) {
    now += nums[i] + (i+1);
    if (t === now) {
      console.log('YES'); return;
    }
  }

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

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

const input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  const [n, t] = input[0].split(' ').map(x => parseInt(x));
  const nums = input[1].split(' ').map(x => parseInt(x));

  let now = 1; if (t === now) { console.log('YES'); return; }
  for (let i = 0; i < nums.length; i += 1) {
    now = nums[i] + (i+1);
    if (t === now) {
      console.log('YES'); return;
    }
  }

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

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

(function() {
  let array_1 = readline().getNumArray(),
    n = array_1[0],
    t = array_1[1] - 1,
    array_2 = readline().getNumArray();

  for (let i = 0; i <= t; i++) {
    const a = array_2[i] ;
    if (a + i === t) {
      write('Yes');
      return;
    }
  }
write('No');
})();

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

(function() {
  let array_1 = readline().getNumArray(),
    n = array_1[0],
    t = array_1[1],
    array_2 = readline().getNumArray();

  for (let i = 0; i < t - 1; i++) {
    const a = array_2[i] ;
    if (a + 1 === array_2[t - 1]) {
      write('Yes');
      return;
    }
  }
write('No');
})();

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

(function() {
  let array_1 = readline().getNumArray(),
    n = array_1[0],
    t = array_1[1] - 1,
    array_2 = readline().getNumArray(),
    nextHome = 0;

  for (let i = 0; i <= t; i++) {
    const a = array_2[i] ;
    nextHome = a + i;
    if (nextHome === t) {
      write('Yes');
      return;
    }
  }
write('No');
})();

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

(function() {
  let array_1 = readline().getNumArray(),
    n = array_1[0],
    t = array_1[1],
    array_2 = readline().getNumArray();

  for (let i = 1; i <= t; i+=array_2[i - 1] + i) {
    if (i === t) {
      write('Yes');
      return;
    }
  }
write('No');
})();

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

(function() {
  let array_1 = readline().getNumArray(),
    n = array_1[0],
    t = array_1[1],
    array_2 = readline().getNumArray();

  for (let i = 0; i < t - 1; i++) {
    const a = array_2[i] ;
    if (a + i === t - 1) {
      write('Yes');
      return;
    }
  }
write('No');
})();

var s = readline().split(" ");//readline();
var str = readline().split(" ");
var res = 0;
var f = 0;
		for (var i=0; i<+s[0]-1; i++){
			if (+str[i]+i+1==+s[1]){
				f = 1;
				break;}
		}
f==1? print("YES"):print("NO");

var s = readline().split(" ");//readline().split(" ");//readline();
var str =  readline().split(" ");
var f = 1;
		for (var i=0; i<+s[0]-1; i++){

			if (f==+s[1]){
				f = 1;
				break;}
					f+=+str[f-1]
		}
f==1? print("YES"):print("NO");

// var n = 8;
// var t = 8;

// var world = [1, 2, 1, 2, 1, 1, 1];

var nt = readline().split(' ');
var n = Number(nt[0]);
var t = Number(nt[1]);

var world = readline().split(' ').map(Number);
var res = 'NO';
var i = 0;

while (i < n - 1) {
	var portal = i + 1;

	if (i + 1 == t) {
		res = 'YES';
	}

	i = portal + world[i] - 1;
}

// console.log(res);
print(res);

var t = readline().split(" ").map(value => +value)[1];
print(
	(readline().split(" ").map((value, index) => +value + index + 1).indexOf(t) === -1) ?
	"NO" : "YES");

var t = readline().split(" ").map(value => +value)[1];
print((readline().split(" ").some((value, index) => +value + index + 1 === t)) ? "YES" : "NO");

var input = readline().split(" ").map((x) => parseInt(x));
var location = readline().split(" ").map((x) => parseInt(x));
var position = input[1];
var counter = 1;
var found = false;

while(counter < location.length) {
    if(counter === position) {
        print("YES");
        found = true;
        break;
    } else {
        counter = counter + location[counter - 1];
    }
}

if(!found) {
    print("NO");
}

var input = readline().split(" ").map((x) => parseInt(x));
var location = readline().split(" ").map((x) => parseInt(x));
var position = input[1];
var counter = 1;
var found = false;

while(counter < location.length) {
    counter = counter + location[counter - 1];

    if(counter === position) {
        print("YES");
        found = true;
        break;
    }
}

if(!found) {
    print("NO");
}

(function() {
    var values = readline().split(" ").map(Number);
    var n = values[0] - 1;
    var k = values[1];
    var arr = readline().split(" ").map(Number);
    var save = 1;

    for (var i = 1; i < arr.length && save <= n; i++) {
        save = arr[save - 1] + save;
        if (save === k) {
            print("YES");
            return;
        }
    }

    print("NO");
})();

(function() {
    var values = readline().split(" ").map(Number);
    var n = values[0] - 1;
    var k = values[1];
    var arr = readline().split(" ").map(Number);
    var save = 1;

    for (var i = 1; i < arr.length && save < n; i++) {
        save = arr[save - 1] + save;
        if (save === k) {
            print("YES");
            return;
        }
    }

    print("NO");
})();

const data = readline().split(" ").map(x => parseInt(x));
const a = readline().split(" ").map(x => parseInt(x));
const n = data[0];
const t = data[1];
var canWe = true;
for (var i=1; i<t; i++) {
    i = a[i] + i;
    if (a[i] + i > t) {
        canWe = false;
        break;
    }
}
print(canWe ? "YES" : "NO");

const data = readline().split(" ").map(x => parseInt(x));
const a = readline().split(" ").map(x => parseInt(x));
const n = data[0];
const t = data[1];
var canWe = false;
var i = 0;
while (i<t) {
    i = a[i] + i + 1;
    if (i === t) {
        canWe = true;
        break;
    }
}
print(canWe ? "YES" : "NO");

const data = readline().split(" ").map(x => parseInt(x));
const a = readline().split(" ").map(x => parseInt(x));
const n = data[0];
const t = data[1];
var canWe = true;
for (var i=0; i<t; i++) {
        if (a[i] + i + 1 > t) {
        canWe = false;
        break;
    }
    i = a[i] + i;
    if (i === t) {
        canWe = true;
        break;
    }
}
print(canWe ? "YES" : "NO");

const data = readline().split(" ").map(x => parseInt(x));
const a = readline().split(" ").map(x => parseInt(x));
const n = data[0];
const t = data[1];
var canWe = true;
for (var i=0; i<t; i++) {
        if (a[i] + i + 1 > t) {
        canWe = false;
        break;
    }
    i = a[i] + i;
}
print(canWe ? "YES" : "NO");

const data = readline().split(" ").map(x => parseInt(x));
const a = readline().split(" ").map(x => parseInt(x));
const n = data[0];
const t = data[1];
var canWe = true;
for (var i=0; i<=t; i++) {
    i = a[i] + i;
    if (a[i] + i > t) {
        canWe = false;
        break;
    }
}
print(canWe ? "NO" : "YES");

const data = readline().split(" ").map(x => parseInt(x));
const a = readline().split(" ").map(x => parseInt(x));
const n = data[0];
const t = data[1];
var canWe = true;
for (var i=0; i<=t; i++) {
    i = a[i] + i;
    if (a[i] + i > t) {
        canWe = false;
        break;
    }
}
print(canWe ? "YES" : "NO");

const data = readline().split(" ").map(x => parseInt(x));
const a = readline().split(" ").map(x => parseInt(x));
const n = data[0];
const t = data[1];
var canWe = true;
for (var i=1; i<t; i++) {
        if (a[i] + i > t) {
        canWe = false;
        break;
    }
    i = a[i] + i;
}
print(canWe ? "YES" : "NO");

const data = readline().split(" ").map(x => parseInt(x));
const a = readline().split(" ").map(x => parseInt(x));
const n = data[0];
const t = data[1];
var canWe = true;
var i = 0;
while (i<t) {
        if (a[i] + i + 1 > t) {
        canWe = false;
        break;
    }
    i = a[i] + i + 1;
    if (i === t) {
        canWe = true;
        break;
    }
}
print(canWe ? "YES" : "NO");

const data = readline().split(" ").map(x => parseInt(x));
const a = readline().split(" ").map(x => parseInt(x));
const n = data[0];
const t = data[1];
var canWe = true;
var i = 0;
while (i<t) {
        if (a[i] + i + 1 > t) {
        canWe = false;
        break;
    }
    i = a[i] + i;
    if (i === t) {
        canWe = true;
        break;
    }
}
print(canWe ? "YES" : "NO");

const data = readline().split(" ").map(x => parseInt(x));
const a = readline().split(" ").map(x => parseInt(x));
const n = data[0];
const t = data[1];
var canWe = true;
for (var i=0; i<t; i++) {
        if (a[i] + i + 1 > t) {
        canWe = false;
        break;
    }
    i = a[i] + i + 1;
}
print(canWe ? "YES" : "NO");


Given an integer $$$n$$$, find any array $$$a$$$ of $$$n$$$ distinct nonnegative integers less than $$$2^{31}$$$ such that the bitwise XOR of the elements on odd indices equals the bitwise XOR of the elements on even indices.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 629$$$) — the number of test cases. Then $$$t$$$ lines follow, each containing a single integer $$$n$$$ $$$(3 \leq n \leq 2\cdot10^5)$$$ — the length of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, output one line containing $$$n$$$ distinct integers that satisfy the conditions. If there are multiple answers, you can output any of them.

NoteIn the first test case the XOR on odd indices is $$$4 \oplus 1 \oplus 0 \oplus 7 = 2$$$ and the XOR on even indices is $$$2 \oplus 5 \oplus 6 \oplus 3= 2$$$.

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++]
        output[i] = solve(n)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n) {
    const ans = []
    const half = Math.floor(n / 2)
    let k = 1
    while (k <= half) k *= 2
    let odd = 0
    let even = 0
    for (let i = 1; i <= half; i++) {
        even ^= i
        odd ^= k + i
        ans.push(i, k + i)
    }
    if (half & 1) {
        if (n & 1) {
            ans.push(k)
        } else {
            ans.pop()
            ans.pop()
            ans.pop()
            ans.pop()
            ans.pop()
            ans.pop()
            ;[4,1,2,12,3,8].forEach(x => {
                ans.push(2 ** 30 + x)
            })
        }
    } else {
        if (n & 1) ans.push(0)
    }
// console.log(n)
    // check(ans)
    return ans.join(' ')
}
function check(arr) {
    let odd = 0
    let even = 0
    for (let i = 0; i < arr.length; i++) {
        if (i & 1) {
            odd ^= arr[i]
        } else {
            even ^= arr[i]
        }
    }
    if (odd !== even) {
        console.log(arr, even, odd)
        throw 'sb'
    }
}


Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.

The first line contains an integer n (1 ≤ n ≤ 5·105) — the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≤ xi ≤ 1023.

Output an integer k (0 ≤ k ≤ 5) — the length of your program. Next k lines must contain commands in the same format as in the input.

NoteYou can read about bitwise operations in https://en.wikipedia.org/wiki/Bitwise_operation.Second sample:Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.

'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('latin1');

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readLine() {
    return inputString[currentLine++];
}
function main() {
    var t = parseInt(readLine(), 10);
    var n = 0, a = 1023, o = 0, x = 0;
    for (; t--; ) {
        const l = readLine().split(' ');
        if (l[0] == '|') {
            n |= l[1];
            o |= l[1];
        } else if (l[0] == '^') {
            n ^= l[1];
        } else {
            n &= l[1];
            a &= l[1];
        }
    }
    x = a < 1023 ? o & a ^ n : o ^ n;
    t = 0
    let s = []
    if (o) s.push("| " + o) && t++
    if (a < 1023) s.push("& " + a) && t++
    if (x) s.push("^ " + x) && t++
    console.log(t)
    console.log(s.join`\n`)
}

'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('latin1');

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readLine() {
    return inputString[currentLine++];
}
function main() {
    var t = parseInt(readLine(), 10);
    var n = 0, a = 1023, o = 0, x = 0;
    for (; t--; ) {
        const l = readLine().split(' ');
        if (l[0] == '|') {
            n |= l[1];
            o |= l[1];
        } else if (l[0] == '^') {
            n ^= l[1];
        } else {
            n &= l[1];
            a = l[1];
        }
    }
    x = a < 1023 ? o & a ^ n : o ^ n;
    t = 0
    let s = []
    if (o) s.push("| " + o) && t++
    if (a < 1023) s.push("& " + a) && t++
    if (x) s.push("^ " + x) && t++
    console.log(t)
    console.log(s.join`\n`)
}

'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('latin1');

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readLine() {
    return inputString[currentLine++];
}
function main() {
    var t = parseInt(readLine(), 10);
    var n = 0, a = 1023, o = 0, x = 0;
    for (; t--; ) {
        const l = readLine().split(' ');
        if (l[0] == '|') {
            n |= l[1];
            o |= l[1];
        } else if (l[0] == '^') {
            n ^= l[1];
        } else {
            n &= l[1];
            a &= l[1];
        }
    }
    x = a ? o & a ^ n : o ^ n;
    t = 0
    let s = []
    if (o) s.push("| " + o) && t++
    if (a) s.push("& " + a) && t++
    if (x) s.push("^ " + x) && t++
    console.log(t)
    console.log(s.join`\n`)
}

'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('latin1');

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readLine() {
    return inputString[currentLine++];
}
function main() {
    var t = parseInt(readLine(), 10);
    var n = 0, a = 1023, o = 0, x = 0;
    for (; t--; ) {
        const l = readLine().split(' ');
        if (l[0] == '|') {
            n |= l[1];
            o |= l[1];
        } else if (l[0] == '^') {
            n ^= l[1];
        } else {
            n &= l[1];
            a &= l[1];
        }
    }
    x = a < 1023 ? o & a ^ n : o ^ n;
    console.log(n, o, x, a, (o & a) ^ x)
    t = 0
    let s = []
    if (o) s.push("| " + o) && t++
    if (a < 1023) s.push("& " + a) && t++
    if (x) s.push("^ " + x) && t++
    console.log(t)
    console.log(s.join`\n`)
}

'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('latin1');

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readLine() {
    return inputString[currentLine++];
}
function main() {
    var t = parseInt(readLine(), 10);
    console.log(t < 5 ? t : 5);
    var n = 0;
    for (; t--; ) {
        const a = readLine().split(' ');
        if (a[0] == '|') {
            n |= a[1];
        } else if (a[0] == '^') {
            n ^= a[1];
        } else {
            n &= a[1];
        }
        if (t == 4) {
            console.log("| " + n);
        } else if (t < 4) {
            console.log(a.join(' '));
        }
//console.log(a, n)
    }
}

'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('latin1');

let inputString = '';
let currentLine = 0;

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

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

    main();
});
function readLine() {
    return inputString[currentLine++];
}
function main() {
    var t = parseInt(readLine(), 10);
    var n = 0;
    for (; t--; ) {
        const a = readLine().split(' ');
        if (a[0] == '|') {
            n |= a[1];
        } else if (a[0] == '^') {
            n ^= a[1];
        } else {
            n &= a[1];
        }
    }
    if (n == 0)
        console.log(0)
    else {
        console.log(2)
        console.log("| "+n)
        console.log("& "+n)
    }
}

'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('latin1');

let inputString = '';
let currentLine = 0;

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

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

    main();
});
function readLine() {
    return inputString[currentLine++];
}
function main() {
    var t = parseInt(readLine(), 10);
    var n = 0;
    for (; t--; ) {
        const a = readLine().split(' ');
        if (a[0] == '|') {
            n |= a[1];
        } else if (a[0] == '^') {
            n ^= a[1];
        } else {
            n &= a[1];
        }
    }
    if (n == 0)
        console.log(0)
    else {
        console.log(1)
        console.log("| "+n)
    }
}

'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('latin1');

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
//    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    var t = parseInt(readLine(), 10);
    console.log(t < 5 ? t : 5);
    var n = 0;
    for (; t--; ) {
        const a = readLine().split(' ');
//console.log(a)
        if (t > 4) {
            if (a[0] == '|') {
                n |= a[1];
            } else if (a[0] == '^') {
                n ^= a[1];
            } else {
                n &= a[1];
            }
        } else if (t == 4) {
            console.log("| " + n);
        } else {
            console.log(a.join(' '));
        }
    }
//    ws.end();
}