There are $$$n + 1$$$ cities, numbered from $$$0$$$ to $$$n$$$. $$$n$$$ roads connect these cities, the $$$i$$$-th road connects cities $$$i - 1$$$ and $$$i$$$ ($$$i \in [1, n]$$$).Each road has a direction. The directions are given by a string of $$$n$$$ characters such that each character is either L or R. If the $$$i$$$-th character is L, it means that the $$$i$$$-th road initially goes from the city $$$i$$$ to the city $$$i - 1$$$; otherwise it goes from the city $$$i - 1$$$ to the city $$$i$$$.A traveler would like to visit as many cities of this country as possible. Initially, they will choose some city to start their journey from. Each day, the traveler must go from the city where they currently are to a neighboring city using one of the roads, and they can go along a road only if it is directed in the same direction they are going; i. e., if a road is directed from city $$$i$$$ to the city $$$i + 1$$$, it is possible to travel from $$$i$$$ to $$$i + 1$$$, but not from $$$i + 1$$$ to $$$i$$$. After the traveler moves to a neighboring city, all roads change their directions to the opposite ones. If the traveler cannot go from their current city to a neighboring city, their journey ends; it is also possible to end the journey whenever the traveler wants to.The goal of the traveler is to visit as many different cities as possible (they can visit a city multiple times, but only the first visit is counted). For each city $$$i$$$, calculate the maximum number of different cities the traveler can visit during exactly one journey if they start in the city $$$i$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$). The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters, each character is either L or R. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, print $$$n + 1$$$ integers. The $$$i$$$-th integer should be equal to the maximum number of different cities the traveler can visit during one journey if this journey starts in the $$$i$$$-th city.

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

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

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

		const dpl = Array(n+1).fill(0);
		for (let i = 1; i <= n; i++) {
			if (d[i-1] == 'L') {
				dpl[i]++;
				if (i-2 >= 0 && d[i-2] == 'R') {
					dpl[i]++;
					dpl[i] += dpl[i-2];
				}
			}
		}

		const dpr = Array(n+1).fill(0);
		for (let i = n-1; i >= 0; i--) {
			if (d[i] == 'R') {
				dpr[i]++;
				if (i+1 < n && d[i+1] == 'L') {
					dpr[i]++;
					dpr[i] += dpr[i+2];
				}
			}
		}

		const ans = [];
		for (let i = 0 ; i <= n; i++) {
			ans[i] = 1 + dpl[i] + dpr[i];
		}

		console.log(ans.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++];
}

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();

    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, iii) => {
        var n = parseInt(readline())
        var x = new Array(n)
        var a = readline().split('').map((x, iii) => {
            return x
        })
        var dpl  = new Array(n+1).fill(0)
        var dpr  = new Array(n+1).fill(0)

        for (let i = 0; i <= n; i++) {
            if(i===0 || a[i-1] === 'R') dpl[i] = i
            else if(i===1 || a[i-2] === 'L') dpl[i] = i-1
            else dpl[i] = dpl[i-2]

        }

        for (let i = n; i >=0; i--) {
            if(i===n || a[i] === 'L') dpr[i] = i
            else if(i===n-1 || a[i+1] === 'R') dpr[i] = i+1
            else dpr[i] = dpr[i+2]
        }

        var res = new Array(n)
        for (let i = 0; i <= n; i++) {
            res[i] = i- dpl[i]+1 + dpr[i] - i
        }

            // console.log(dpl)
        // console.log(dpr)
        console.log(res.join(' '))

        // x = x.sort((a, b) => {
        //     if (a.x - b.x === 0)
        //         return a.y - b.y
        //     return a.x - b.x
        // })
        // var res = []
    })
}


Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition:  These k dots are different: if i ≠ j then di is different from dj.  k is at least 4.  All dots belong to the same color.  For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field.

The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board. Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.

Output "Yes" if there exists a cycle, and "No" otherwise.

7 6
AAAAAB
ABBBAB
ABAAAB
ABABBB
ABAAAB
ABBBAB
AAAAAB

NoteIn first sample test all 'A' form a cycle.In second sample there is no such cycle.The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).

// author: Oscar Ramos

/// Source Code
// const input = require('competitive-programming-js').inputReader
// const { matrix, forn, fornm } = require('../utils/utils')
//
// const [n, m] = input.readNumberArray()
//
// const field = []
// forn(n, () => {
//   const line = input.readLine()
//   field.push(line)
// })
//
// let flag = false
//
// let visited = matrix(n, m, false)
//
// function dfs(i, j, previ, prevj, color) {
//   if (i >= 0 && i < n && j >= 0 && j < m && field[i][j] === color) {
//     if (visited[i][j]) {
//       return true
//     }
//     visited[i][j] = true
//     if(!(i - 1 === previ && j === prevj) && dfs(i - 1, j, i, j, color))
//       return true
//     if(!(i === previ && j - 1 === prevj) && dfs(i, j - 1, i, j, color))
//       return true
//     if(!(i === previ && j + 1 === prevj) && dfs(i, j + 1, i, j, color))
//       return true
//     if(!(i + 1 === previ && j === prevj) && dfs(i + 1, j, i, j, color))
//       return true
//     visited[i][j] = false
//   }
//   return false
// }
//
// fornm(n, m, (i, j) => {
//   visited = matrix(n, m, false)
//   flag = flag || dfs(i, j, -1, -1, field[i][j])
// })
//
// if (flag) {
//   console.log('Yes')
// } else {
//   console.log('No')
// }
//

!function(n){var r={};function t(e){if(r[e])return r[e].exports;var o=r[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=n,t.c=r,t.d=function(n,r,e){t.o(n,r)||Object.defineProperty(n,r,{enumerable:!0,get:e})},t.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t.t=function(n,r){if(1&r&&(n=t(n)),8&r)return n;if(4&r&&"object"==typeof n&&n&&n.__esModule)return n;var e=Object.create(null);if(t.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:n}),2&r&&"string"!=typeof n)for(var o in n)t.d(e,o,function(r){return n[r]}.bind(null,o));return e},t.n=function(n){var r=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(r,"a",r),r},t.o=function(n,r){return Object.prototype.hasOwnProperty.call(n,r)},t.p="",t(t.s=1)}([function(n,r){n.exports=function(n){return null!=n&&"object"==typeof n&&!0===n["@@functional/placeholder"]}},function(n,r,t){n.exports=t(2)},function(n,r,t){let e,o=0,u={readLine:function(){return e[o++]},readNumberArray:function(){return e[o++].split(" ").map(n=>Number(n))}};var i="";process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",(function(n){i+=n})).on("end",(function(){e=i.trim().split("\n").map(n=>n.trim());const{matrix:n,forn:r,fornm:o}=t(3),[f,c]=u.readNumberArray(),a=[];r(f,()=>{const n=u.readLine();a.push(n)});let s=!1,p=n(f,c,!1);o(f,c,(r,t)=>{p=n(f,c,!1),s=s||function n(r,t,e,o,u){if(r>=0&&r<f&&t>=0&&t<c&&a[r][t]===u){if(p[r][t])return!0;if(p[r][t]=!0,(r-1!==e||t!==o)&&n(r-1,t,r,t,u))return!0;if((r!==e||t-1!==o)&&n(r,t-1,r,t,u))return!0;if((r!==e||t+1!==o)&&n(r,t+1,r,t,u))return!0;if((r+1!==e||t!==o)&&n(r+1,t,r,t,u))return!0;p[r][t]=!1}return!1}(r,t,-1,-1,a[r][t])}),s?console.log("Yes"):console.log("No")}))},function(n,r,t){const e=t(4);n.exports={forn:(n,r)=>e(0,n).map(n=>r(n)),fornm:(n,r,t)=>e(0,n).map(n=>e(0,r).map(r=>t(n,r))),matrix:(n,r,t)=>e(0,n).map(()=>e(0,r).map(()=>t)),vector:(n,r)=>e(0,n).map(()=>r),range:e}},function(n,r,t){var e=t(5),o=t(7),u=e((function(n,r){if(!o(n)||!o(r))throw new TypeError("Both arguments to range must be numbers");for(var t=[],e=n;e<r;)t.push(e),e+=1;return t}));n.exports=u},function(n,r,t){var e=t(6),o=t(0);n.exports=function(n){return function r(t,u){switch(arguments.length){case 0:return r;case 1:return o(t)?r:e((function(r){return n(t,r)}));default:return o(t)&&o(u)?r:o(t)?e((function(r){return n(r,u)})):o(u)?e((function(r){return n(t,r)})):n(t,u)}}}},function(n,r,t){var e=t(0);n.exports=function(n){return function r(t){return 0===arguments.length||e(t)?r:n.apply(this,arguments)}}},function(n,r){n.exports=function(n){return"[object Number]"===Object.prototype.toString.call(n)}}]);

/// package.json
// {
//   "name": "competitive",
//   "version": "1.0.0",
//   "description": "",
//   "main": "src/index.js",
//   "scripts": {
//     "convert": "cp-convert -s src/index.js -d output/converted.js",
//     "bundle": "webpack --config ./webpack.config.js",
//     "test": "npm run convert && jest ./",
//     "production": "npm run convert && npm run bundle && node src/getOutput.js",
//     "start": "node src/index.js"
//   },
//   "author": "Oscar Ramos",
//   "dependencies": {
//     "child-process-promise": "^2.2.1",
//     "competitive-programming-js": "^1.0.10",
//     "mathball": "^0.4.0",
//     "ramda": "^0.27.1"
//   },
//   "devDependencies": {
//     "@types/jest": "^26.0.10",
//     "concat-stream": "^2.0.0",
//     "cross-spawn": "^7.0.3",
//     "jest": "^26.4.2",
//     "jest-expect-message": "^1.0.2",
//     "mock-stdin": "^1.0.0",
//     "terser-webpack-plugin": "^4.1.0",
//     "webpack": "^4.44.1",
//     "webpack-cli": "^3.3.12"
//   },
//   "jest": {
//     "setupFilesAfterEnv": ["jest-expect-message"]
//   }
// }
//


Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≤ i ≤ n). Help Polycarpus determine the length of the city phone code.

The first line of the input contains an integer n (2 ≤ n ≤ 3·104) — the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn — the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different.

Print the number of digits in the city phone code.

NoteA prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209".In the first sample the city phone code is string "00".In the second sample the city phone code is an empty string.In the third sample the city phone code is string "770123456789".

print(function(n) {
	var i, j, a = [];

	for (i = 0; i < n; i++)
		a.push(readline());

	for (i = 0; i < 20; i++)
		for (j = 0; j < n; j++)
			if (a[j][i] !== a[0][i]) return i;

	return 20;

}(+readline()));

;(function () {

	print(function (n) {

		var s = readline(), b, l;
		while (n--) {
			b = ''; l = readline();

			for (var i = 0, _i = Math.min(l.length, s.length); i < _i; i++) {
				if (s[i] === l[i]) b += l[i];
				else break;
			}

			s = b;
		}

		return s.length;

	}(+readline() - 1));

}.call(this));

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

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

  phones.push(d);

  c++;
});

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

  for (let i = 0; i < phones[0].length; i++) {
    let code = phones[0][i];
    let isDiffer = false;
    for(let j = 0; j < phones.length; j++) {
      if (code !== phones[j][i]) {
        isDiffer = true;
        break;
      }
    }

    if (isDiffer) {
      break;
    }
    else {
      ans++;
    }
  }

  console.log(ans);
});


Recently, the students of School 179 have developed a unique algorithm, which takes in a binary string $$$s$$$ as input. However, they soon found out that if some substring $$$t$$$ of $$$s$$$ is a palindrome of length greater than 1, the algorithm will work incorrectly. Can the students somehow reorder the characters of $$$s$$$ so that the algorithm will work correctly on the string?A binary string is a string where each character is either 0 or 1.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.A palindrome is a string that reads the same backwards as forwards.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the string $$$s$$$. The second line of each test case contains the string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.

For each test case, print YES (case-insensitive) if it is possible to reorder the characters of $$$s$$$ so that there are no substrings that are a palindrome of length greater than 1, or NO (case-insensitive) otherwise.

NoteIn the first three test cases, the given strings do not contain palindromes of length greater than 1, so the answers are YES.In the last test case, it is impossible to reorder the characters so that the string does not contain palindromes of length greater than 1, so the answer is NO.

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

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

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

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

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

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

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

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

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

function solve() {
    let _ = readSingleInt();
    while(_--){
        let n = readSingleInt();
        let st = readLine();
        if(n>2 || st=='11' || st=='00'){
            console.log("NO");
        }else{
            console.log("YES");
        }
    }

}

let data = "";
let some = 0;

process.stdin.on("data", (c) => (data += c));
process.stdin.on("end", () => {
  let [_, ...input] = data
    .trim()
    .split(/\n/)
    .map((el) => el.trim());

  input = input.filter((el, idx) => idx % 2 !== 0);
  input.forEach((el) => {
    if (el.length > 2) {
      console.log("NO");
    } else {
      if (el[0] === el[1]) {
        console.log("NO");
      } else console.log("YES");
    }
  });
});

let data = "";

process.stdin.on("data", (c) => (data += c));
process.stdin.on("end", () => {
  let [_, ...input] = data
    .trim()
    .split(/\n/)
    .map((el) => el.trim());

  input = input.filter((el, idx) => idx % 2 !== 0);
  input.forEach((el) => {
    if (el.length > 2) {
      console.log("NO");
    } else {
      if (el[0] === el[1]) {
        console.log("NO");
      } else console.log("YES");
    }
  });
});

let input = "";
process.stdin.on("data", (chunk) => {
  input += chunk;
});
function palindrome(arr) {
  if (arr.length <= 1) {
    return false;
  }
  for (let i = 0, j = arr.length - 1; i < j; i++, j--) {
    if (arr[i] !== arr[j]) {
      return false;
    }
  }
  return true;
}
function permutationGenerator(arr, n, permutation, permutations) {
  if (permutation.length === arr.length) {
    permutations.push(permutation.slice().join(""));
  } else {
    for (let i = n; i < arr.length; i++) {
      let temp = arr[n];
      arr[n] = arr[i];
      arr[i] = temp;
      permutation.push(arr[n]);
      permutationGenerator(arr, n + 1, permutation, permutations);
      temp = arr[n];
      arr[n] = arr[i];
      arr[i] = temp;
      permutation.pop();
    }
  }
}
function subsetGenerator(arr, n, subsets, subset) {
  if (n === arr.length) {
    subsets.push(subset.slice().join(""));
  } else {
    subsetGenerator(arr, n + 1, subsets, subset);
    subset.push(arr[n]);
    subsetGenerator(arr, n + 1, subsets, subset);
    subset.pop();
  }
}
process.stdin.on("end", () => {
  let lines = input.trim().split("\n");
  let t = parseInt(lines[0].trim());
  let i = 1;
  while (t--) {
    let n = parseInt(lines[i++].trim());
    let s = lines[i++].trim();
    if (n == 1) {
      console.log("YES");
    } else if (n == 2) {
      if (s[0] !== s[1]) {
        console.log("YES");
      } else {
        console.log("NO");
      }
    } else {
      console.log("NO");
    }
  }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

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

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

        if (s.length > 2) {
            output('NO');
        } else if (s[0] === s[1]) {
            output('NO');
        } else {
            output('YES');
        }
    }
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var S = nextCharArray();
		if(N >= 3){
			myout("NO");
			continue;
		}else if(N == 1){
			myout("YES");
		}else{
			var set = new Set(S);
			if(set.size == 1){
				myout("NO");
			}else{
				myout("YES");
			}
		}
	}
}

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    var e = 0;
    for(var l = 1; l <= n * 2; l++){
        if(l % 2 === 0){
            var k = lines[l].split('').map(Number);
            var one = 0;
            var zero = 0;
            for(var j = 0; j < e; j++){
                if(k[j] == 1){
                    one++;
                }else{
                    zero++;
                }
            }
            if(one <= 1 && zero <= 1){
                console.log('YES');
            }else{
                console.log('NO');
            }
        }else{
            e = lines[l];
        }
    }
});

'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 greeting() {
    let t = parseInt(readLine());
while(t > 0)
{
    let n = parseInt(readLine());
    let s = readLine();

    if(n < 2)
    console.log("YES");
    else if(n == 2 && s[0] != s[1])
    console.log("YES");
    else
    {
        console.log("NO");
    }

    t--;
}
}

function main() {
    greeting();
}

let data = '';
process.stdin.on('data', c => data += c);

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i = 0; i < t; i++){
		let n = nl.num();
		let s = nl.line().split('');
		ans.push((n == 2 && s[0] != s[1]) || n == 1);
	}
	console.log(ans.map(e => e?"YES":"NO").join('\n'));
};

process.stdin.on('end', sol);

'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++];
}
/* let arr = readLine().split(" ").map((x) => {return parseInt(x)});
let test = readLine();
while(test--)
{

}
*/
function main() {
    let test = readLine();
    while(test--)
        {
            let noNeed = readLine();
            let string = readLine();
            if (string == "0" || string == "01" || string == "10" || string == "10" || string == "1"){
            console.log("YES");
        }
        else {
            console.log("NO");
        }
        }
    return 0;
}

'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(){
 let noOfInputs = (readline());
 while(noOfInputs--){
     let trash = readline();
     let num = readline();
     let ones=0, zeroes =0;
     num.split("").forEach(x => (x==1 ? ones++ : zeroes++));
     if(zeroes+ones == 1) console.log("YES")
     else if(zeroes+ones == 2 && zeroes==ones) console.log("YES")
     else console.log("NO")
 }
}

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

let inputString = '';

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

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

    main(inputString);
});

function log(message){
    if(process.env.NODE_ENV === "debug"){
        console.log(message);
    }
}

const YES = "YES"
const NO = "NO"

function main(fileContents) {//input lines as an array
    // console.log(fileContents);
    fileContents.splice(0,1);
    for(let i = 1; i < fileContents.length; i+=2){
        const bs = fileContents[i];
        // console.log("BS",bs)
        if(bs.length == 1){
            console.log(YES) // 0 1
        }else if(bs.length == 2){
            if(bs.charAt(0) === bs.charAt(1)){
                console.log(NO) // 11 00
            }else{
                console.log(YES) // 01 10
            }
        }else{
            console.log(NO)
        }
    }
}

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 testCases = readline();

  for (let i = 0; i < testCases; i++) {
    let size = readline();
    let s = readline();

    if (
      size === "1" ||
      (size === "2" && s === "10") ||
      (size === "2" && s === "01")
    ) {
      console.log("YES");
    } else {
      console.log("NO");
    }
  }
}

//readline().split(" ").map(function(x) { return parseInt(x); });
var numbers = parseInt(readline());
var i =0;
while(i < numbers) {
	var n =parseInt(readline());
	var a =(readline());

	print(n > 2 || a === '00' || a === '11' ? 'NO' : 'YES'); // ends with newline
	i++;
}

//print(numbers[0] + numbers[1]); // ends with newline

var t = parseInt(readline());
while(t > 0)
{
    var n = parseInt(readline());
    var s = readline();

    if(n < 2)
    print("YES");
    else if(n == 2 && s[0] != s[1])
    print("YES");
    else
    {
        print("NO");
    }
    t--;
}

var x = parseInt(readline());
for(var i=0; i<x; i++) {
    var y = parseInt(readline());
    var z = readline();
    if(y >= 3 || (y == 2 && z[0] == z[1])) {
        print("NO");
    }
    else {
        print("YES");
    }
}

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

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

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

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

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

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

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

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

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

function solve() {
    let _ = readSingleInt();
    while(_--){
        let n = readSingleInt();
        let st = readLine();
        if(n>2){
            console.log("NO");
        }else{
            console.log("YES");
        }
    }

}

//readline().split(" ").map(function(x) { return parseInt(x); });
var numbers = parseInt(readline());
var i =0;
while(i < numbers) {
	var n =parseInt(readline());
	var a =parseInt(readline());

	print(n > 2 || a === '00' || a === '11' ? 'NO' : 'YES'); // ends with newline
	i++;
}

//print(numbers[0] + numbers[1]); // ends with newline

//readline().split(" ").map(function(x) { return parseInt(x); });
var numbers = parseInt(readline());
var i =0;
while(i < numbers) {
	var n =parseInt(readline());
	var a =parseInt(readline());

	print(n > 2 ? 'NO' : 'YES'); // ends with newline
	i++;
}

//print(numbers[0] + numbers[1]); // ends with newline

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

for (var i in numbers) {
	var n =parseInt(readline());
	var a =parseInt(readline());

	print(n > 2 ? 'NO' : 'YES'); // ends with newline
}

//print(numbers[0] + numbers[1]); // ends with newline


Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers $$$n$$$ pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the $$$i$$$-th from the left sushi as $$$t_i$$$, where $$$t_i = 1$$$ means it is with tuna, and $$$t_i = 2$$$ means it is with eel.Arkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment $$$[2, 2, 2, 1, 1, 1]$$$ is valid, but subsegment $$$[1, 2, 1, 2, 1, 2]$$$ is not, because both halves contain both types of sushi.Find the length of the longest continuous subsegment of sushi Arkady can buy.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100\,000$$$) — the number of pieces of sushi. The second line contains $$$n$$$ integers $$$t_1$$$, $$$t_2$$$, ..., $$$t_n$$$ ($$$t_i = 1$$$, denoting a sushi with tuna or $$$t_i = 2$$$, denoting a sushi with eel), representing the types of sushi from left to right. It is guaranteed that there is at least one piece of sushi of each type. Note that it means that there is at least one valid continuous segment.

Print a single integer — the maximum length of a valid continuous segment.

NoteIn the first example Arkady can choose the subsegment $$$[2, 2, 1, 1]$$$ or the subsegment $$$[1, 1, 2, 2]$$$ with length $$$4$$$.In the second example there is no way but to choose one of the subsegments $$$[2, 1]$$$ or $$$[1, 2]$$$ with length $$$2$$$.In the third example Arkady's best choice is the subsegment $$$[1, 1, 1, 2, 2, 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', function() {
    inputString = inputString
        .replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    console.log(findMaxSushiSeq(inputString[1].split(' ')));
});

const findMaxSushiSeq = (data) => {
    let high = 0;
    let low = 0;
    let i = 0;
    let max = 0;
    while (i < data.length) {
        if (data[i] !== data[high]) {
            low = high;
            high = i;
        }

        if (high > low) {
            max = Math.max(max, (Math.min(i - high + 1, high - low) * 2));
        }

        i++;
    }
    return max;
};

Array.prototype.eachTwo = function(callback) {
    for (let i = 0; i < this.length; i++) {
        if (i + 1 == this.length) break;

        callback(this[i], this[i + 1]);
    }
}

const readline = require('readline');

let iteration = 0, count, array, previous = 0, counters = [];

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

rl.on('line', (line) => {
    if (iteration == 0) {
        count = parseInt(line.trim());
        iteration++;

        if (count < 2 || count > 100000) {
            rl.close();
        }
    } else {
        array = line.trim().split(" ").map (symbol => parseInt(symbol));
        iteration++;

        rl.close();
    }

    if (iteration != 2) { return; }

    array.forEach(element => {
        if (element == 1) {
            if (previous == 1) {
                counters[counters.length - 1] += 1;
            } else {
                counters.push(1)
            }

            previous = 1
        }

        if (element == 2) {
            if (previous == 2) {
                counters[counters.length - 1] += 1;
            } else {
                counters.push(1)
            }

            previous = 2
        }
    });

    var result = 0

    counters.eachTwo(function(first, second) {
        let value = Math.min(first, second) * 2;

        if (value > result) {
            result = value
        }
    });

    console.log(result);
});

const readline = require('readline');

let count, array, previous = 0, counters = [];

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

rl.on('line', (line) => {
    if (!count) {
        count = parseInt(line.trim());

        if (count < 2 || count > 100000) {
            rl.close();
        }
    } else if (!array) {
        array = line.trim().split(" ").map (symbol => parseInt(symbol));

        rl.close();
    }
}).on('close', () => {
    array.forEach(element => {
        if (previous == element) {
            counters[counters.length - 1] += 1;
        } else {
            counters.push(1)
        }

        previous = element;
    });

    var result = 0;

    for (let i = 0; i < counters.length; i++) {
        if (i + 1 == counters.length) break;

        let value = Math.min(counters[i], counters[i + 1]) * 2;

        result = Math.max(value, result);
    }

    console.log(result);
});

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

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

  const arr = d.split(' ').map(Number);
  let max = 0;
  let count = 0;
  let ones = 0;
  let twos = 0;

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== arr[i - 1]) {
      count++;

      if (count === 2) {
        count = 1;

        if (arr[i - 1] === 1) {
          twos = 0;
        }

        if (arr[i - 1] === 2) {
          ones = 0;
        }
      }
    }

    if (arr[i] === 1) {
      ones++;
    }

    if (arr[i] === 2) {
      twos++;
    }

    max = Math.max(max, Math.min(ones, twos) * 2);
  }

  console.log(max);
  c++;
});

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  const { EOL } = require('os')
  const lines = input.split(EOL)
l = []
count = 0
lines[1] = lines[1].replace(/\ /g, '')
lines[1] = Array.from(lines[1])
lastchar = lines[1][0]
for (var i in lines[1]){
    if (lines[1][i] != lastchar){
    l.push(count)
    count = 1
    lastchar = lines[1][i]
    }
    else{
    count += 1
    }
}
l.push(count)
mx = 0
for (var i = 0; i < l.length -1; i++){
    mx = Math.max(mx, Math.min(l[i], l[i+1]))
}
console.log(mx * 2)
})

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
  const { EOL } = require('os')
  const lines = input.split(EOL)
  let line = lines[1]
  line = line.replace(/\ /g, '')
  let cache = ['1', 0, 0]
  let max = 0
  for (let i = 0; i < line.length; i++) {
    if (line[i] == cache[0]) {
      cache[2]++
    } else {
      cache[0] = line[i]
      cache[1] = cache[2]
      cache[2] = 1
    }
    if (Math.min(cache[1], cache[2]) > max) {
      max = Math.min(cache[1], cache[2])
    }
  }
  console.log(max * 2)
})

let data = '';
process.stdin.on('data', c => data += c);

const solution = () => {
	let line = data.split('\n');
	let n = parseInt(line[0],10);
	let a = line[1].split(' ').map(v => parseInt(v,10));
	let t = a[0];
	let c = 0;
	let x = [];
	for(let i of a){
		if (t == i){
			c++;
		} else {
			x.push(c);
			c = 1;
			t = i;
		}
	}
	x.push(c);

	let m = 0;
	t = 0;
	for(let i of x){
		if (Math.min(t,i) > m){
			m = Math.min(t,i);
		}
		t = i;
	}
	console.log(2 * m);
};

process.stdin.on('end', solution);

// const print = require('lol-io').print;
// const readline = require('lol-io').readline;

const t = readline();
const arr = readline().split(' ');

const obj = {
	0: 0,
	1: 0,
};

const a = arr.map(i => {
	return i == 1 ? 1 : 0;
});

var maxSegment = 0;
var flag = 0;

if (a[0] === 0) {
	flag = 0;
} else flag = 1;

for (var i = 0; i < a.length; i++) {
	obj[a[i]]++;

	// if (obj[0] <= obj[1] ) {
	if (flag !== a[i]) {
		obj[a[i]] = 1;
		flag = +(!flag);
	}

	maxSegment =
		Math.min(obj[0], obj[1]) > maxSegment
			? Math.min(obj[0], obj[1])
			: maxSegment;

	// if (obj[0] > maxSegment) maxSegment = obj[0];
	// obj[!a[i]] = 0;
	// } else if()
}
// console.log(maxSegment * 2);
maxSegment = maxSegment * 2;
print(maxSegment);

var numOfLines = readline();
var nums = readline().split(' ').map(function(num) {
  return parseInt(num);
})

function min(a, b) {
  if (a < b)
    return a;
  if (b <= a)
    return b;
}

function max(a, b) {
  if (a < b)
    return b;
  if (b <= a)
    return a;
}

function main() {
  var currentSegment = 1;
  var prevSegment = 0;
  var maxSegments = 0;
  var currentNum = nums[0];

  for (var i = 1; i < nums.length; i++) {
    if (nums[i] === currentNum)
      currentSegment++;
    else {
      maxSegments = max(maxSegments, 2 * min(prevSegment, currentSegment));
      prevSegment =  currentSegment;
      currentSegment = 1;
      currentNum = nums[i];
    }
  }

  maxSegments = max(maxSegments, 2 * min(prevSegment, currentSegment));

  write(maxSegments)
}

main()

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString
        .split('\n');

    console.log(findMaxSushiSeq(inputString[1].split(' ')));
});

const findMaxSushiSeq = (data) => {
    let high = 0;
    let low = 0;
    let i = 0;
    let max = 0;
    while (i < data.length) {
        if (data[i] !== data[high]) {
            low = high;
            high = i;
        }

        if (high > low) {
            max = Math.max(max, (Math.min(i - high + 1, high - low) * 2));
        }

        i++;
    }
    return max;
};

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

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

  const arr = d.split(' ').map(Number);
  let max = 0;
  let type1 = 0;
  let type2 = 0;
  let switchCount = 0;
  let prev = arr[0];

  for (let i = 0; i < arr.length; i++) {
    if (prev !== arr[i]) {
      switchCount++;

      if (switchCount === 2) {
        switchCount = 0
        if (prev === 1) {
          type2 = 0;
        }
        else {
          type1 = 0;
        }
      }
    }

    if (arr[i] === 1) {
      type1++;
    }

    if (arr[i] === 2) {
      type2++;
    }

    if (type1 === type2) {
      max = Math.max(max, type1 + type2);
    }

    prev = arr[i];
  }

  console.log(max);

  c++;
});

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

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

  const arr = d.split(' ').map(Number);
  let max = 0;
  let count = 0;
  let ones = 0;
  let twos = 0;

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== arr[i - 1]) {
      count++;

      if (count === 2) {
        count = 0;

        if (arr[i - 1] === 1) {
          twos = 0;
        }

        if (arr[i - 1] === 2) {
          ones = 0;
        }
      }
    }

    if (arr[i] === 1) {
      ones++;
    }

    if (arr[i] === 2) {
      twos++;
    }

    max = Math.max(max, Math.min(ones, twos) * 2);
  }

  console.log(max);
  c++;
});

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

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

    n = +d;
    return;
  }

  if (n === 100000) {
    console.log(d);
    return;
  }

  const arr = d.split(' ').map(Number);
  let max = 0;
  let count = 0;
  let ones = 0;
  let twos = 0;

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== arr[i - 1]) {
      count++;

      if (count === 2) {
        count = 0;

        if (arr[i - 1] === 1) {
          twos = 0;
        }

        if (arr[i - 1] === 2) {
          ones = 0;
        }
      }
    }

    if (arr[i] === 1) {
      ones++;
    }

    if (arr[i] === 2) {
      twos++;
    }

    max = Math.max(max, Math.min(ones, twos) * 2);
  }

  console.log(max);
  c++;
});

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

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

  const arr = d.split(' ').map(Number);
  let max = 0;
  let type1 = 0;
  let type2 = 0;
  let switchCount = 0;
  let prev = arr[0];

  for (let i = 0; i < arr.length; i++) {
    if (prev !== arr[i]) {
      switchCount++;

      if (switchCount === 2) {
        switchCount = 0
        if (prev === 1) {
          type2 = 0;
        }
        else {
          type1 = 0;
        }
      }
    }

    if (arr[i] === 1) {
      type1++;
    }

    if (arr[i] === 2) {
      type2++;
    }

    max = Math.max(max, Math.min(type1, type2) + Math.min(type1, type2));

    prev = arr[i];
  }

  console.log(max);

  c++;
});

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

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

  const arr = d.split(' ').map(Number);
  let max = 0;
  let count = 0;
  let ones = 0;
  let twos = 0;

  for (let i = 1; i < arr.length; i++) {
    if (arr[i] !== arr[i - 1]) {
      count++;

      if (count === 2) {
        count = 0;

        if (arr[i - 1] === 1) {
          twos = 0;
        }

        if (arr[i - 1] === 2) {
          ones = 0;
        }
      }
    }

    if (arr[i] === 1) {
      ones++;
    }

    if (arr[i] === 2) {
      twos++;
    }

    max = Math.max(max, Math.min(ones, twos) * 2);
  }

  console.log(max);
  c++;
});

var numOfLines = readline();
var nums = readline().split(' ').map(function(num) {
  return parseInt(num);
})

function min(a, b) {
  if (a < b)
    return a;
  if (b <= a)
    return b;
}

function max(a, b) {
  if (a < b)
    return b;
  if (b <= a)
    return a;
}

function main() {
  var currentSegment = 0;
  var prevSegment = 0;
  var maxSegments = 0;
  var currentNum = nums[0];

  for (var i = 1; i < nums.length; i++) {
    if (nums[i] === currentNum)
      currentSegment++;
    else {
      maxSegments = max(maxSegments, min(prevSegment, currentSegment));
      prevSegment =  currentSegment;
      currentSegment = 1;
      currentNum = nums[i];
    }
  }

  maxSegments = max(maxSegments, 2*min(prevSegment, currentSegment));

  write(maxSegments)
}

main()

var numOfLines = readline();
var nums = readline().split(' ').map(function(num) {
  return parseInt(num);
})

function min(a, b) {
  if (a < b)
    return a;
  if (b <= a)
    return b;
}

function max(a, b) {
  if (a < b)
    return b;
  if (b <= a)
    return a;
}

function main() {
  var currentSegment = 1;
  var prevSegment = 0;
  var maxSegments = 0;
  var currentNum = nums[0];

  for (var i = 1; i < nums.length; i++) {
    if (nums[i] === currentNum)
      currentSegment++;
    else {
      maxSegments = max(maxSegments, min(prevSegment, currentSegment));
      prevSegment =  currentSegment;
      currentSegment = 1;
      currentNum = nums[i];
    }
  }

  maxSegments = max(maxSegments, 2*min(prevSegment, currentSegment));

  write(maxSegments)
}

main()

var numOfLines = readline();
var nums = readline().split(' ').map(function(num) {
  return parseInt(num);
})

function min(a, b) {
  if (a < b)
    return a;
  if (b <= a)
    return b;
}

function max(a, b) {
  if (a < b)
    return b;
  if (b <= a)
    return a;
}

function main() {
  var currentSegment = 1;
  var prevSegment = 0;
  var maxSegments = 0;
  var currentNum = nums[0];

  for (var i = 1; i < nums.length; i++) {
    if (nums[i] === currentNum)
      currentSegment++;
    else {
      maxSegments = max(maxSegments, 2 * min(prevSegment, currentSegment));
      prevSegment =  currentSegment;
      currentSegment = 1;
      currentNum = nums[i];
    }
  }

  maxSegments = max(maxSegments, min(prevSegment, currentSegment));

  write(maxSegments)
}

main()


You have a permutation: an array $$$a = [a_1, a_2, \ldots, a_n]$$$ of distinct integers from $$$1$$$ to $$$n$$$. The length of the permutation $$$n$$$ is odd.Consider the following algorithm of sorting the permutation in increasing order.A helper procedure of the algorithm, $$$f(i)$$$, takes a single argument $$$i$$$ ($$$1 \le i \le n-1$$$) and does the following. If $$$a_i > a_{i+1}$$$, the values of $$$a_i$$$ and $$$a_{i+1}$$$ are exchanged. Otherwise, the permutation doesn't change.The algorithm consists of iterations, numbered with consecutive integers starting with $$$1$$$. On the $$$i$$$-th iteration, the algorithm does the following:   if $$$i$$$ is odd, call $$$f(1), f(3), \ldots, f(n - 2)$$$;  if $$$i$$$ is even, call $$$f(2), f(4), \ldots, f(n - 1)$$$. It can be proven that after a finite number of iterations the permutation will be sorted in increasing order.After how many iterations will this happen for the first time?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 999$$$; $$$n$$$ is odd) — the length of the permutation. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the permutation itself.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$999$$$.

For each test case print the number of iterations after which the permutation will become sorted in increasing order for the first time. If the given permutation is already sorted, print $$$0$$$.

NoteIn the first test case, the permutation will be changing as follows:   after the $$$1$$$-st iteration: $$$[2, 3, 1]$$$;  after the $$$2$$$-nd iteration: $$$[2, 1, 3]$$$;  after the $$$3$$$-rd iteration: $$$[1, 2, 3]$$$. In the second test case, the permutation will be changing as follows:   after the $$$1$$$-st iteration: $$$[4, 5, 1, 7, 2, 3, 6]$$$;  after the $$$2$$$-nd iteration: $$$[4, 1, 5, 2, 7, 3, 6]$$$;  after the $$$3$$$-rd iteration: $$$[1, 4, 2, 5, 3, 7, 6]$$$;  after the $$$4$$$-th iteration: $$$[1, 2, 4, 3, 5, 6, 7]$$$;  after the $$$5$$$-th iteration: $$$[1, 2, 3, 4, 5, 6, 7]$$$. In the third test case, the permutation is already sorted and the answer is $$$0$$$.

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var output = 0;
		while(true){
			var isOK = true;
			for(var i = 0; i < N - 1; i++){
				if(list[i] > list[i + 1]){
					isOK = false;
					break;
				}
			}
			if(isOK){
				break;
			}
			if(output % 2 == 0){
				for(var i = 0; i < N - 2; i += 2){
					if(list[i] > list[i + 1]){
						var tmp = list[i];
						list[i] = list[i + 1];
						list[i + 1] = tmp;
					}
				}
			}else{
				for(var i = 1; i < N - 1; i += 2){
					if(list[i] > list[i + 1]){
						var tmp = list[i];
						list[i] = list[i + 1];
						list[i + 1] = tmp;
					}
				}
			}
			output++;
		}
		myout(output);
	}
}

let i = ''
let lines;
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  lines = i.split('\n'); // your input text, split by lines
  main();
});

function isSorted(p) {
  for (let i = 0; i < p.length - 1; i++) {
    if (p[i] > p[i + 1]) {
      return false
    }
  }
  return true
}

function sort(p, i) {
  if (i % 2 === 0) {
    for (let j = 1; j < p.length - 1; j = j + 2) {
      if (p[j] > p[j + 1]) {
        const aux = p[j]
        p[j] = p[j + 1]
        p[j + 1] = aux
      }
    }
  } else {
    for (let j = 0; j < p.length - 1; j = j + 2) {
      if (p[j] > p[j + 1]) {
        const aux = p[j]
        p[j] = p[j + 1]
        p[j + 1] = aux
      }
    }
  }
}

function main() {
  let t = parseInt(lines.shift())

  while (t > 0) {
    lines.shift()
    let p = lines.shift().split(' ').map(x => parseInt(x))
    let op = 0
    while (!isSorted(p)) {
      op++
      sort(p, op)
    }
    console.log(op)
    t--
  }
}


Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.Mike has $$$n$$$ sweets with sizes $$$a_1, a_2, \ldots, a_n$$$. All his sweets have different sizes. That is, there is no such pair $$$(i, j)$$$ ($$$1 \leq i, j \leq n$$$) such that $$$i \ne j$$$ and $$$a_i = a_j$$$.Since Mike has taught for many years, he knows that if he gives two sweets with sizes $$$a_i$$$ and $$$a_j$$$ to one child and $$$a_k$$$ and $$$a_p$$$ to another, where $$$(a_i + a_j) \neq (a_k + a_p)$$$, then a child who has a smaller sum of sizes will be upset. That is, if there are two children who have different sums of sweets, then one of them will be upset. Apparently, Mike does not want somebody to be upset. Mike wants to invite children giving each of them two sweets. Obviously, he can't give one sweet to two or more children. His goal is to invite as many children as he can. Since Mike is busy preparing to his first lecture in the elementary school, he is asking you to find the maximum number of children he can invite giving each of them two sweets in such way that nobody will be upset.

The first line contains one integer $$$n$$$ ($$$2 \leq n \leq 1\,000$$$) — the number of sweets Mike has. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$) — the sizes of the sweets. It is guaranteed that all integers are distinct.

Print one integer — the maximum number of children Mike can invite giving each of them two sweets in such way that nobody will be upset.

NoteIn the first example, Mike can give $$$9+2=11$$$ to one child, $$$8+3=11$$$ to another one, and $$$7+4=11$$$ to the third child. Therefore, Mike can invite three children. Note that it is not the only solution.In the second example, Mike can give $$$3+9=12$$$ to one child and $$$1+11$$$ to another one. Therefore, Mike can invite two children. Note that it is not the only solution.

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

var inputs = [];
const PI = parseInt;

function main() {
    const sw = inputs[1].split(" ").map(_ => PI(_));
    let possibleSolution = {};
    sw.forEach((val, idx) => {
        for(let q = idx + 1 ; q < sw.length; q++) {
            let k = sw[q] + val;
            possibleSolution[k] = (possibleSolution[k]) ? possibleSolution[k] : 0;
            possibleSolution[k.toString()]++;

        }
    });
    let res = 0;
    Object.keys(possibleSolution).forEach((key) => {
        res = Math.max(res, possibleSolution[key]);
    });

    console.log(res);
}

readline.on('line', (input) => { inputs.push(input); });
readline.on('close', main)

let i = '';
process.stdin.on('data', (c) => {
  i += c;
});
process.stdin.on('end', () => {
  const { EOL } = require('os');
  const lines = i.split(EOL);
  let candy = lines[1].split(' ');
  candy = candy.map(c => parseInt(c, 10));
  // console.log(maxChildren(candy));
  console.log(maxChildrenFast(candy));
});

function maxChildrenFast(candies) {
  const arr = [];
  arr.length = 2 * (10 ** 5);
  arr.fill(0);
  let max = 1;
  for (let i = 0; i < candies.length - 1; i++) {
    for (let j = i + 1; j < candies.length; j++) {
      max = Math.max(++arr[candies[i] + candies[j] - 1], max);
    }
  }
  return max;
}


Mark has just purchased a rack of $$$n$$$ lightbulbs. The state of the lightbulbs can be described with binary string $$$s = s_1s_2\dots s_n$$$, where $$$s_i=\texttt{1}$$$ means that the $$$i$$$-th lightbulb is turned on, while $$$s_i=\texttt{0}$$$ means that the $$$i$$$-th lightbulb is turned off.Unfortunately, the lightbulbs are broken, and the only operation he can perform to change the state of the lightbulbs is the following:  Select an index $$$i$$$ from $$$2,3,\dots,n-1$$$ such that $$$s_{i-1}\ne s_{i+1}$$$.  Toggle $$$s_i$$$. Namely, if $$$s_i$$$ is $$$\texttt{0}$$$, set $$$s_i$$$ to $$$\texttt{1}$$$ or vice versa. Mark wants the state of the lightbulbs to be another binary string $$$t$$$. Help Mark determine the minimum number of operations to do so.

The first line of the input contains a single integer $$$q$$$ ($$$1\leq q\leq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$3\leq n\leq 2\cdot 10^5$$$) — the number of lightbulbs. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ — the initial state of the lightbulbs. The third line of each test case contains a binary string $$$t$$$ of length $$$n$$$ — the final state of the lightbulbs. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print a line containing the minimum number of operations Mark needs to perform to transform $$$s$$$ to $$$t$$$. If there is no such sequence of operations, print $$$-1$$$.

NoteIn the first test case, one sequence of operations that achieves the minimum number of operations is the following.   Select $$$i=3$$$, changing $$$\texttt{01}\color{red}{\texttt{0}}\texttt{0}$$$ to $$$\texttt{01}\color{red}{\texttt{1}}\texttt{0}$$$.  Select $$$i=2$$$, changing $$$\texttt{0}\color{red}{\texttt{1}}\texttt{10}$$$ to $$$\texttt{0}\color{red}{\texttt{0}}\texttt{10}$$$.  In the second test case, there is no sequence of operations because one cannot change the first digit or the last digit of $$$s$$$.In the third test case, even though the first digits of $$$s$$$ and $$$t$$$ are the same and the last digits of $$$s$$$ and $$$t$$$ are the same, it can be shown that there is no sequence of operations that satisfies the condition.In the fourth test case, one sequence that achieves the minimum number of operations is the following:   Select $$$i=3$$$, changing $$$\texttt{00}\color{red}{\texttt{0}}\texttt{101}$$$ to $$$\texttt{00}\color{red}{\texttt{1}}\texttt{101}$$$.  Select $$$i=2$$$, changing $$$\texttt{0}\color{red}{\texttt{0}}\texttt{1101}$$$ to $$$\texttt{0}\color{red}{\texttt{1}}\texttt{1101}$$$.  Select $$$i=4$$$, changing $$$\texttt{011}\color{red}{\texttt{1}}\texttt{01}$$$ to $$$\texttt{011}\color{red}{\texttt{0}}\texttt{01}$$$.  Select $$$i=5$$$, changing $$$\texttt{0110}\color{red}{\texttt{0}}\texttt{1}$$$ to $$$\texttt{0110}\color{red}{\texttt{1}}\texttt{1}$$$.  Select $$$i=3$$$, changing $$$\texttt{01}\color{red}{\texttt{1}}\texttt{011}$$$ to $$$\texttt{01}\color{red}{\texttt{0}}\texttt{011}$$$.

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const rn = () => Number(read());
  const n = rn(),
        a = read().split(''),
        b = read().split('');
  if (a[0] !== b[0] || a[n - 1] !== b[n - 1]) return -1;
  const c = [],
        d = [];
  for (let i = 0; i < n - 1; i++) {
    if (a[i] !== a[i + 1]) {
      c.push(i);
    }
    if (b[i] !== b[i + 1]) {
      d.push(i);
    }
  }
  if (c.length !== d.length) return -1;
  let res = 0;
  for (let i = 0; i < c.length; i++) {
    res += Math.abs(c[i] - d[i]);
  }
  return res;
}

function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < 100) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= 100) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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


Kate has a set $$$S$$$ of $$$n$$$ integers $$$\{1, \dots, n\} $$$. She thinks that imperfection of a subset $$$M \subseteq S$$$ is equal to the maximum of $$$gcd(a, b)$$$ over all pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are in $$$M$$$ and $$$a \neq b$$$. Kate is a very neat girl and for each $$$k \in \{2, \dots, n\}$$$ she wants to find a subset that has the smallest imperfection among all subsets in $$$S$$$ of size $$$k$$$. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size $$$k$$$, will name it $$$I_k$$$. Please, help Kate to find $$$I_2$$$, $$$I_3$$$, ..., $$$I_n$$$.

The first and only line in the input consists of only one integer $$$n$$$ ($$$2\le n \le 5 \cdot 10^5$$$)  — the size of the given set $$$S$$$.

Output contains only one line that includes $$$n - 1$$$ integers: $$$I_2$$$, $$$I_3$$$, ..., $$$I_n$$$.

NoteFirst sample: answer is 1, because $$$gcd(1, 2) = 1$$$.Second sample: there are subsets of $$$S$$$ with sizes $$$2, 3$$$ with imperfection equal to 1. For example, $$$\{2,3\}$$$ and $$$\{1, 2, 3\}$$$.

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

function solve(n) {
  const filter = new Array(n + 1).fill(0);
  filter[0] = filter[1] = 1;
  for (let i = 2; i <= n; ++i) {
    if (filter[i] !== 0) continue;
    filter[i] = 1;
    for (let j = i + i; j <= n; j += i) {
      if (filter[j] === 0) filter[j] = Math.floor(j / i);
    }
  }
  return filter.slice(2).sort((a, b) => a - b).join(' ');
}

function main() {
  let currentLine = 0;
  const readLine = (_) => lines[currentLine++].split(' ').map((val) => parseInt(val));

  const n = readLine()[0];
  console.log(solve(n));
}

wt = write;
rd = readline;

n = parseInt(rd());
arr = [];
for(i =  1; i <= n; i++){
	for(j = 2; j * i <= n; j++){
		arr[i * j] = i;
	}
}
arr.sort(function(a,b){ return a - b; });
for(i = 0; i < n - 1; i++){
	wt(arr[i] + " ");
}


There are $$$n$$$ piles of sand where the $$$i$$$-th pile has $$$a_i$$$ blocks of sand. The $$$i$$$-th pile is called too tall if $$$1 < i < n$$$ and $$$a_i > a_{i-1} + a_{i+1}$$$. That is, a pile is too tall if it has more sand than its two neighbours combined. (Note that piles on the ends of the array cannot be too tall.)You are given an integer $$$k$$$. An operation consists of picking $$$k$$$ consecutive piles of sand and adding one unit of sand to them all. Formally, pick $$$1 \leq l,r \leq n$$$ such that $$$r-l+1=k$$$. Then for all $$$l \leq i \leq r$$$, update $$$a_i \gets a_i+1$$$.What is the maximum number of piles that can simultaneously be too tall after some (possibly zero) operations?

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq k \leq n$$$) — the number of piles of sand and the size of the operation, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the sizes of the piles. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the maximum number of piles that are simultaneously too tall after some (possibly zero) operations.

NoteIn the first test case, we can perform the following three operations:   Add one unit of sand to piles $$$1$$$ and $$$2$$$: $$$[\color{red}{3}, \color{red}{10}, 2, 4, 1]$$$.  Add one unit of sand to piles $$$4$$$ and $$$5$$$: $$$[3, 10, 2, \color{red}{5}, \color{red}{2}]$$$.  Add one unit of sand to piles $$$3$$$ and $$$4$$$: $$$[3, 10, \color{red}{3}, \color{red}{6}, 2]$$$.  Now piles $$$2$$$ and $$$4$$$ are too tall, so in this case the answer is $$$2$$$. It can be shown that it is impossible to make more than $$$2$$$ piles too tall.In the second test case, any operation will increase all piles by $$$1$$$ unit, so the number of too tall piles will always be $$$0$$$.In the third test case, we can increase any pile by $$$1$$$ unit of sand. It can be shown that the maximum number of too tall piles is $$$1$$$.

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1) {
		write(parseInt((n[0] - 1) / 2));
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i === 0 || i == arr.length - 1) continue;
			count +=
				arr[i - 1] + arr[i + 1] < arr[i]

		}
		write(count);
	}
	print();
}

var tests = parseInt(readline());
for (var t=0; t < tests; t++) {
    var nk = readline().split(' ').map(x => parseInt(x));
    var n = nk[0];
    var k = nk[1];
    var arr = readline().split(' ').map(x => parseInt(x));
    var max = Math.floor((n - 1) / 2);
    if (k == 1) {
        print(max);
        continue;
    }
    var piles = 0;
    for (var i=1; i < n-1; i++) {
        if (arr[i-1]+arr[i+1] < arr[i]) piles++;
    }
    print(piles);
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseConstraints = readline().split(" ");
    var caseLength = parseInt(caseConstraints[0]);
    var caseOpLength = parseInt(caseConstraints[1]);
    var caseArray = readline().split(" ");
    var count = 0;
    var result = 0;
    if (caseOpLength == 1)
    {
        if (caseLength % 2 === 0)
        {
            result = (caseLength/2) - 1;
        }
        else result = Math.floor(caseLength/2);
    }
    else
    {
        for (var j = 1; j < caseLength-1; j++)
        {
            var term = parseInt(caseArray[j]);
            var oneLessTerm = parseInt(caseArray[j-1]);
            var onePlusTerm = parseInt(caseArray[j+1]);
            var sum = oneLessTerm + onePlusTerm;
            if (term > sum) count++;
        }
        result = count;
    }
    print(result);
}

"use strict";
function toInt(x) {
	return parseInt(x);
}
function readInt() {
	return toInt(readline());
}
function readLInt() {
	return readline().split(' ').map(toInt);
}
function divCeil(a, b) {
	return Math.floor((a - 1) / b) + 1;
}
function solve() {
	let n, k;
	let x = readLInt();
	n = x[0];
	k = x[1];
	let a = readLInt();
	if (k == 1) {
		print(Math.floor((n - 1) / 2));
		return 0;
	}
	let res = 0;
	for (let ind = 1; ind + 1 < n; ind++) {
		if (a[ind] > a[ind + 1] + a[ind - 1]) res++;
	}
	print(res);
}

let t = readInt();
while (t--) solve();

var t = +readline();

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

    var t1 = +readline().split(' ')[1]
    var t2 = readline().split(' ').map((t) => +t);
    print(ShuffleArray(t1,t2))

}

function ShuffleArray(k,arr){
  var count = 0;
  if (k == 1){
    return Math.floor((arr.length + 1) / 2) -1
  }
  for(var i = 0; i<arr.length-1;i++){
    if (arr[i] > arr[i-1] + arr[i+1]) count++;
  }

  return count;

}

'use strict';

function solve(n, m, a) {
  if (m === 1) {
    return Math.ceil(n / 2) - 1;
  }
  let res = 0;
  for (let i = 1; i < n - 1; i++) {
    if (a[i] > a[i - 1] + a[i + 1]) res++;
  }
  return res;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

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

    for (let i = 0; i < N; i++) {
        const [n, k] = readline().split(' ').map(Number);
        let arr = readline().split(' ').map(Number);
        if (k === 1) {
            output(Math.floor((n - 1) / 2));
        } else {
            let tooHigh = 0;
            for (let j = 1; j < arr.length - 1; j++) {
                if (arr[j - 1] + arr[j + 1] < arr[j]) {
                    tooHigh++;
                }
            }
            output(tooHigh);
        }
    }
}

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1) {
		write(n[0] - 2);
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i === 0 || i == arr.length - 1) continue;
			count +=
				arr[i - 1] + arr[i + 1] < arr[i] ||
				(arr[i - 1] + arr[i + 1] === arr[i] &&
					(i >= n[1] || arr.length - i - 1 >= n[1]));
		}
		write(count);
	}
	print();
}

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1) {
		write(n[0] - 2);
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i === 0 || i == arr.length - 1) continue;
			count +=
				arr[i - 1] + arr[i + 1] < arr[i] ||
				(arr[i - 1] + arr[i + 1] === arr[i] &&
					i >= n[1] &&
					arr.length - i >= n[1]);
		}
		write(count);
	}
	print();
}

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1) {
		write(n[0] - 2);
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i === 0 || i == arr.length - 1) continue;
			count +=
				arr[i - 1] + arr[i + 1] < arr[i] ||
				(arr[i - 1] + arr[i + 1] === arr[i] &&
					(i >= n[1] ||
						(i + 1 <= arr.length - 1 && arr.length - (i + 1) >= n[1]))) ||
				0;
		}
		write(count);
	}
	print();
}

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1) {
		write(n[0] - 2);
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i === 0 || i == arr.length - 1) continue;
			count +=
				arr[i - 1] + arr[i + 1] < arr[i] ||
				(arr[i - 1] + arr[i + 1] === arr[i] &&
					(i - 1 >= n[1] ||
						(i + 1 <= arr.length - 1 && arr.length - (i + 1) >= n[1]))) ||
				0;
		}
		write(count);
	}
	print();
}

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1 && n[0] > 2) {
		write(n[0] - 2);
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i === 0 || i == arr.length - 1) continue;
			count +=
				arr[i - 1] + arr[i + 1] < arr[i] ||
				(arr[i - 1] + arr[i + 1] === arr[i] &&
					(i - 1 >= n[1] ||
						(i + 1 <= arr.length - 1 && arr.length - (i + 1) + 1 >= n[1]))) ||
				0;
		}
		write(count);
	}
	print();
}

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1) {
		write(n[0] - 2);
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i === 0 || i == arr.length - 1) continue;
			count +=
				arr[i - 1] + arr[i + 1] < arr[i] ||
				(arr[i - 1] + arr[i + 1] === arr[i] &&
					(i - 1 >= n[1] ||
						(i + 1 <= arr.length - 1 && arr.length - (i + 1) + 1 >= n[1])));
		}
		write(count);
	}
	print();
}

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1) {
		write(n[0] - 2);
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i === 0 || i == arr.length - 1) continue;
			count +=
				arr[i - 1] + arr[i + 1] < arr[i] ||
				(arr[i - 1] + arr[i + 1] === arr[i] &&
					(i - 1 >= n[1] || (i + 1 <= arr.length - 1 && i + 1 >= n[1])));
		}
		write(count);
	}
	print();
}

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1) {
		write(n[0] - 2);
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i === 0 || i == arr.length - 1) continue;
			count +=
				arr[i - 1] + arr[i + 1] < arr[i] ||
				(arr[i - 1] + arr[i + 1] === arr[i] &&
					(i - 1 >= n[1] || (i + 1 < arr.length - 1 && i + 1 >= n[1])));
		}
		write(count);
	}
	print();
}

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1) {
		write(n[0] - 2);
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i === 0 || i == arr.length - 1) continue;
			count +=
				arr[i - 1] + arr[i + 1] < arr[i] ||
				(arr[i - 1] + arr[i + 1] === arr[i] && i - 1 >= n[1]);
		}
		write(count);
	}
	print();
}

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1) {
		write(n[0] - 2);
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i === 0 || i == arr.length - 1) continue;
			count +=
				arr[i - 1] + arr[i + 1] < arr[i] ||
				(arr[i - 1] + arr[i + 1] === arr[i] && i >= n[1]);
		}
		write(count);
	}
	print();
}

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1) {
		write(n[0] - 2);
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i === 0 || i == arr.length - 1) continue;
			count +=
				arr[i - 1] + arr[i + 1] < arr[i] ||
				(arr[i - 1] + arr[i + 1] === arr[i] && i >= n[0]);
		}
		write(count);
	}
	print();
}

var t = +readline();

while (t--) {
	var n = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});
	var arr = readline()
		.split(" ")
		.map(function (a) {
			return +a;
		});

	if (n[1] == 1) {
		write(n[0] - 2);
	} else {
		var count = 0;
		for (var i = 0; i < arr.length; i++) {
			if (i == 0 || i == arr.length - 1) continue;
			count += arr[i - 1] + arr[i + 1] < arr[i];
		}
		write(count);
	}
	print();
}

var tests = parseInt(readline());
for (var t=0; t < tests; t++) {
    var nk = readline().split(' ').map(x => parseInt(x));
    const n = nk[0];
    const k = nk[1];
    var arr = readline().split(' ').map(x => parseInt(x));
    var max = Math.floor((n - 1) / 2);
    if (k == 1) {
        print(max);
        continue;
    }
    var piles = 0;
    for (var i=1; i < n-1; i++) {
        if (arr[i-1]+arr[i+1] < arr[i]) piles++;
    }
    print(piles);
}

var tests = parseInt(readline());
for (var t=0; t < tests; t++) {
    const nk = readline().split(' ').map(x => parseInt(x));
    const n = nk[0];
    const k = nk[1];
    const arr = readline().split(' ').map(x => parseInt(x));
    var max = Math.floor((n - 1) / 2);
    if (k == 1) {
        print(max);
        continue;
    }
    var piles = 0;
    for (var i=1; i < n-1; i++) {
        if (arr[i-1]+arr[i+1] < arr[i]) {
            piles++;
        }
    }
    print(piles);
}

var tests = parseInt(readline());
for (var t=0; t < tests; t++) {
    const nk = readline().split(' ').map(x => parseInt(x));
    const n = nk[0];
    const k = nk[1];
    const arr = readline().split(' ').map(x => parseInt(x));
    var max = Math.floor((n - 1) / 2);
    if (k == 1) {
        print(max);
        continue;
    }
    var piles = 0;
    for (var i=1; i < n-1; i++) {
        if (arr[i-1]+arr[i+1] < arr[i]) piles++;
    }
    print(piles);
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseConstraints = readline().split(" ");
    var caseLength = parseInt(caseConstraints[0]);
    var caseOpLength = parseInt(caseConstraints[1]);
    var caseArray = readline().split(" ");
    var count = 0;
    var result = 0;
    if (caseOpLength == 1)
    {
        if (caseLength % 2 === 0)
        {
            result = (caseLength/2) - 1;
        }
        else result = Math.floor(caseLength/2);
    }
    else
    {
        for (var j = 1; j < caseLength-1; j++)
        {
            var term = parseInt(caseArray[j]);
            var oneLessTerm = parseInt(caseArray[j-1]);
            var onePlusTerm = parseInt(caseArray[j+1]);
            var sum = oneLessTerm + onePlusTerm;
            if (term > sum) count++;
        }
        reuslt = count;
    }
    print(result);
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseConstraints = readline().split(" ");
    var caseLength = parseInt(caseConstraints[0]);
    var caseOpLength = parseInt(caseConstraints[1]);
    var caseArray = readline().split(" ");
    var count = 0;
    var result = 0;
    if (caseOpLength == 1)
    {
        if (caseLength % 2 === 0)
        {
            result = (caseLength/2) - 1;
        }
        else result = Math.floor(caseLength/2);
    }
    else
    {
        for (var j = 1; j < caseLength-1; j++)
        {
            var term = parseInt(caseArray[j]);
            var oneLessTerm = parseInt(caseArray[j-1]);
            var onePlusTerm = parseInt(caseArray[j+2]);
            var sum = oneLessTerm + onePlusTerm;
            if (term > sum) count++;
        }
        reuslt = count;
    }
    print(result);
}

"use strict";
function toInt(x) {
	return parseInt(x);
}
function readInt() {
	return toInt(readline());
}
function readLInt() {
	return readline().split(' ').map(toInt);
}
function divCeil(a, b) {
	return Math.floor((a - 1) / b) + 1;
}
function solve() {
	let n, k;
	let x = readLInt();
	n = x[0];
	k = x[1];
	let a = readLInt();
	if (k == 1) {
		print(Math.floor(n / 2));
		return 0;
	}
	let res = 0;
	for (let ind = 1; ind + 1 < n; ind++) {
		if (a[ind] > a[ind + 1] + a[ind - 1]) res++;
	}
	print(res);
}

let t = readInt();
while (t--) solve();

var t = +readline();

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

    var t1 = readline();
    var t2 = readline().split(' ').map((t) => +t);
    print(ShuffleArray(t2))

}

function ShuffleArray(arr){
  var count = 0;
  for(var i = 0; i<arr.length-1;i++){
    if (arr[i] > arr[i-1] + arr[i+1]) count++;
  }

  return count;

}

'use strict';

function solve(n, m, a) {
  let res = 0;
  for (let i = 1; i < n - 1; i++) {
    if (a[i] > a[i - 1] + a[i + 1]) res++;
  }
  return res;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});


Alice and Bob are playing chess on a huge chessboard with dimensions $$$n \times n$$$. Alice has a single piece left — a queen, located at $$$(a_x, a_y)$$$, while Bob has only the king standing at $$$(b_x, b_y)$$$. Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to seize the victory for himself — he needs to march his king to $$$(c_x, c_y)$$$ in order to claim the victory for himself. As Alice is distracted by her sense of superiority, she no longer moves any pieces around, and it is only Bob who makes any turns.Bob will win if he can move his king from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check. Remember that a king can move to any of the $$$8$$$ adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen. Find whether Bob can win or not.

The first line contains a single integer $$$n$$$ ($$$3 \leq n \leq 1000$$$) — the dimensions of the chessboard. The second line contains two integers $$$a_x$$$ and $$$a_y$$$ ($$$1 \leq a_x, a_y \leq n$$$) — the coordinates of Alice's queen. The third line contains two integers $$$b_x$$$ and $$$b_y$$$ ($$$1 \leq b_x, b_y \leq n$$$) — the coordinates of Bob's king. The fourth line contains two integers $$$c_x$$$ and $$$c_y$$$ ($$$1 \leq c_x, c_y \leq n$$$) — the coordinates of the location that Bob wants to get to. It is guaranteed that Bob's king is currently not in check and the target location is not in check either. Furthermore, the king is not located on the same square as the queen (i.e. $$$a_x \neq b_x$$$ or $$$a_y \neq b_y$$$), and the target does coincide neither with the queen's position (i.e. $$$c_x \neq a_x$$$ or $$$c_y \neq a_y$$$) nor with the king's position (i.e. $$$c_x \neq b_x$$$ or $$$c_y \neq b_y$$$).

Print "YES" (without quotes) if Bob can get from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check, otherwise print "NO". You can print each letter in any case (upper or lower).

NoteIn the diagrams below, the squares controlled by the black queen are marked red, and the target square is marked blue.In the first case, the king can move, for instance, via the squares $$$(2, 3)$$$ and $$$(3, 2)$$$. Note that the direct route through $$$(2, 2)$$$ goes through check.  In the second case, the queen watches the fourth rank, and the king has no means of crossing it.  In the third case, the queen watches the third file.

function main(){

    function kingBehindQueenX(kingXCoor, queenXCoor){
        return kingXCoor < queenXCoor;
    }

    function kingBehindQueenY(kingYCoor, queenYCoor){
        return kingYCoor < queenYCoor;
    }

    function kingInFrontOfQueenX(kingXCoor, queenXCoor){
        return kingXCoor > queenXCoor;
    }

    function kingInFrontOfQueenY(kingYCoor, queenYCoor){
        return kingYCoor > queenYCoor;
    }

    function targetSquareInFrontOfQueenX(targetXCoor, queenXCoor){
        if(targetXCoor > queenXCoor){
            return true;
        }
    }

    function targetSquareBehindQueenX(targetXCoor, queenXCoor){
        if(targetXCoor < queenXCoor){
            return true;
        }
    }

    function targetSquareInFrontOfQueenY(targetYCoor, queenYCoor){
        if(targetYCoor > queenYCoor){
            return true;
        }
    }

    function targetSquareBehindQueenY(targetYCoor, queenYCoor){
        if(targetYCoor < queenYCoor){
            return true;
        }
    }

    function solution(n, a, b, c){
        // var boardDimensions = n;
        var queenXCoor = parseInt(a[0]);
        var queenYCoor = parseInt(a[1]);

        var kingXCoor = parseInt(b[0]);
        var kingYCoor = parseInt(b[1]);

        var targetXCoor = parseInt(c[0]);
        var targetYCoor = parseInt(c[1]);

        if(kingBehindQueenX(kingXCoor, queenXCoor)){
            // target square x must be behind
            if(targetSquareInFrontOfQueenX(targetXCoor, queenXCoor)){
                return false;
            }
        }

        if(kingInFrontOfQueenX(kingXCoor, queenXCoor)){
            // target square x must be in front
            if(targetSquareBehindQueenX(targetXCoor, queenXCoor)){
                return false;
            }
        }

        if(kingBehindQueenY(kingYCoor, queenYCoor)){
            // target square y must be behind
            if(targetSquareInFrontOfQueenY(targetYCoor, queenYCoor)){
                return false;
            }
        }

        if(kingInFrontOfQueenY(kingYCoor, queenYCoor)){
            // target square y must be behind
            if(targetSquareBehindQueenY(targetYCoor, queenYCoor)){
                return false;
            }
        }

        return true;
    }

    const line1 = readline().split(" ");
    const n = parseInt(line1[0]);
    const a = readline().split(" ");
    const b = readline().split(" ");
    const c = readline().split(" ");

    var s = solution(n, a, b, c);

    if(s){
        print("YES");
    }
    else {
        print("NO");
    }
}

main();

function main(){

    function kingBehindQueenX(kingXCoor, queenXCoor){
        return kingXCoor < queenXCoor;
    }

    function kingBehindQueenY(kingYCoor, queenYCoor){
        return kingYCoor < queenYCoor;
    }

    function targetSquareInFrontOfQueenX(targetXCoor, queenXCoor){
        if(targetXCoor > queenXCoor){
            return true;
        }
    }

    function targetSquareInFrontOfQueenY(targetYCoor, queenYCoor){
        if(targetYCoor > queenYCoor){
            return true;
        }
    }

    function solution(n, a, b, c){
        // var boardDimensions = n;
        var queenXCoor = parseInt(a[0]);
        var queenYCoor = parseInt(a[1]);

        var kingXCoor = parseInt(b[0]);
        var kingYCoor = parseInt(b[1]);

        var targetXCoor = parseInt(c[0]);
        var targetYCoor = parseInt(c[1]);

        if(kingBehindQueenX(kingXCoor, queenXCoor)){
            // target square x must be behind
            if(targetSquareInFrontOfQueenX(targetXCoor, queenXCoor)){
                return false;
            }
        }

        if(kingBehindQueenY(kingYCoor, queenYCoor)){
            // target square x must be behind
            if(targetSquareInFrontOfQueenY(targetYCoor, queenYCoor)){
                return false;
            }
        }

        return true;
    }

    const line1 = readline().split(" ");
    const n = parseInt(line1[0]);
    const a = readline().split(" ");
    const b = readline().split(" ");
    const c = readline().split(" ");

    var s = solution(n, a, b, c);

    if(s){
        print("YES");
    }
    else {
        print("NO");
    }
}

main();


You are given a binary matrix $$$A$$$ of size $$$n \times n$$$. Let's denote an $$$x$$$-compression of the given matrix as a matrix $$$B$$$ of size $$$\frac{n}{x} \times \frac{n}{x}$$$ such that for every $$$i \in [1, n], j \in [1, n]$$$ the condition $$$A[i][j] = B[\lceil \frac{i}{x} \rceil][\lceil \frac{j}{x} \rceil]$$$ is met.Obviously, $$$x$$$-compression is possible only if $$$x$$$ divides $$$n$$$, but this condition is not enough. For example, the following matrix of size $$$2 \times 2$$$ does not have any $$$2$$$-compression: $$$01$$$   $$$10$$$ For the given matrix $$$A$$$, find maximum $$$x$$$ such that an $$$x$$$-compression of this matrix is possible.Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.

The first line contains one number $$$n$$$ ($$$4 \le n \le 5200$$$) — the number of rows and columns in the matrix $$$A$$$. It is guaranteed that $$$n$$$ is divisible by $$$4$$$. Then the representation of matrix follows. Each of $$$n$$$ next lines contains $$$\frac{n}{4}$$$ one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from $$$0$$$ to $$$9$$$ or as uppercase Latin letters from $$$A$$$ to $$$F$$$). Binary representation of each of these numbers denotes next $$$4$$$ elements of the matrix in the corresponding row. For example, if the number $$$B$$$ is given, then the corresponding elements are 1011, and if the number is $$$5$$$, then the corresponding elements are 0101. Elements are not separated by whitespaces.

Print one number: maximum $$$x$$$ such that an $$$x$$$-compression of the given matrix is possible.

var qq = readline().split(" ").map(function(x) { return parseInt(x); });
//var numbers = prompt("Enter data: ").split(" ").map(function(x) { return parseInt(x); });   // Chrome run

var n = qq[0];
var matr = Array(n).fill([]);

for (var i=0; i<n; i++) {
	qq = readline();
	var ar = Array(n).fill(0);
	for (var j=0; j<Math.floor(n/4); j++) {
		var x = qq[j];
		if (x >= '0' && x <= '9')
			var val = parseInt(x);
		else
			var val = parseInt(x, 36) - parseInt('A', 36) + 10;
		for (var k=0; k<4; k++)
			ar[j*4+k] = (val>>(3-k)) & 1;
	}
	matr[i] = ar;
}

function def(x,y,dx,dy) {
	var value = matr[x][y];
	x += dx;
	y += dy;
	var MXX = 1;
	while (x >= 0 && x < n && y >= 0 && y < n) {
		var xx = x, yy = y;
		var Ok = true;
		while (xx >= 0 && xx < n && yy >= 0 && yy < n) {
			if (matr[xx][yy] !== value) {
				Ok = false;
				break;
			}
			xx -= dx;
		}
		xx = x; yy = y;
		while (Ok && xx >= 0 && xx < n && yy >= 0 && yy < n) {
			if (matr[xx][yy] !== value) {
				Ok = false;
				break;
			}
			yy -= dy;
		}
		if (Ok === false)
			return MXX;
		MXX++;
		x += dx;
		y += dy;
	}
	return n;
}

var qw = def(0,0,+1,+1);
qw = Math.min(qw, def(n-1,n-1,-1,-1));
qw = Math.min(qw, def(0,n-1,+1,-1));
qw = Math.min(qw, def(n-1,0,-1,+1));

for (var i=1; i<n; i++) matr[0][i] += matr[0][i-1];
for (var i=1; i<n; i++) matr[i][0] += matr[i-1][0];
for (var i=1; i<n; i++)
	for (var j=1; j<n; j++)
		matr[i][j] = matr[i][j] + matr[i-1][j] + matr[i][j-1] - matr[i-1][j-1];

var fnd = 0;
for (var x=qw; x>=1; x--)
	if (n % x === 0) {
		var Ok = true;
		var EE = Math.floor(n/x);
		for (var i=0; i<EE; i++)
			for (var j=0; j<EE; j++) {
				var x1 = i*x;
				var y1 = j*x;
				var x2 = x1 + x-1;
				var y2 = y1 + x-1;
				var res = matr[x2][y2];
				if (x1 > 0)
					res -= matr[x1-1][y2];
				if (y1 > 0)
					res -= matr[x2][y1-1];
				if (x1 > 0 && y1 > 0)
					res += matr[x1-1][y1-1];

				if (!((res === 0) || (res === x*x))) {
					Ok = false;
					break;
				}
			}

		/*for (var i=0; i<n && Ok; i++)
			for (var j=0; j<n && Ok; j++)
				if (matr[i][j] !== matr[Math.floor(i/x)*x][Math.floor(j/x)*x]) {
					Ok = false;
					break;
				}*/

		if (Ok) {
			fnd = 1;
			write(x);
			break;
		}
	}
if (fnd === 0) write("0");

 /*write("\n\n");
 for (var i=0; i<n; i++) {
     for (var j=0; j<n; j++)
              write(matr[i][j]);
     write("\n");
 }*/

var qq = readline().split(" ").map(function(x) { return parseInt(x); });
//var numbers = prompt("Enter data: ").split(" ").map(function(x) { return parseInt(x); });   // Chrome run

var n = qq[0];
var matr = Array(n).fill([]);

for (var i=0; i<n; i++) {
	qq = readline();
	var ar = Array(n).fill(0);
	for (var j=0; j<Math.floor(n/4); j++) {
		var x = qq[j];
		if (x >= '0' && x <= '9')
			var val = parseInt(x);
		else
			var val = parseInt(x, 36) - parseInt('A', 36) + 10;
		for (var k=0; k<4; k++)
			ar[j*4+k] = (val>>(3-k)) & 1;
	}
	matr[i] = ar;
}

var fnd = 0;
for (var x=n; x>=1; x--)
	if (n % x === 0) {
		var Ok = true;
		for (var i=1; i<=n && Ok; i++)
			for (var j=1; j<=n && Ok; j++)
				if (matr[i-1][j-1] !== matr[Math.floor((i+x-1)/x)-1][Math.floor((j+x-1)/x)-1]) {
					Ok = false;
					break;
				}
		if (Ok) {
			fnd = 1;
			write(x);
			break;
		}
	}
if (fnd === 0) write("0");

// for (var i=0; i<n; i++) {
//     for (var j=0; j<n; j++)
//         write(matr[i][j]);
//     write("\n");
// }

var qq = readline().split(" ").map(function(x) { return parseInt(x); });
//var numbers = prompt("Enter data: ").split(" ").map(function(x) { return parseInt(x); });   // Chrome run

var n = qq[0];
var matr = Array(n).fill([]);

for (var i=0; i<n; i++) {
	qq = readline();
	var ar = Array(n).fill(0);
	for (var j=0; j<Math.floor(n/4); j++) {
		var x = qq[j];
		if (x >= '0' && x <= '9')
			var val = parseInt(x);
		else
			var val = parseInt(x, 36) - parseInt('A', 36) + 10;
		for (var k=0; k<4; k++)
			ar[j*4+k] = (val>>(3-k)) & 1;
	}
	matr[i] = ar;
}

var fnd = 0;
for (var x=n; x>=1; x--)
	if (n % x === 0) {
		var Ok = true;
		for (var i=0; i<n && Ok; i++)
			for (var j=0; j<n && Ok; j++)
				if (matr[i][j] !== matr[Math.floor(i/x)][Math.floor(j/x)]) {
					Ok = false;
					break;
				}
		if (Ok) {
			fnd = 1;
			write(x);
			break;
		}
	}
if (fnd === 0) write("0");

// for (var i=0; i<n; i++) {
//     for (var j=0; j<n; j++)
//         write(matr[i][j]);
//     write("\n");
// }


Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place!This contest consists of n problems, and Pasha solves ith problem in ai time units (his solutions are always correct). At any moment of time he can be thinking about a solution to only one of the problems (that is, he cannot be solving two problems at the same time). The time Pasha spends to send his solutions is negligible. Pasha can send any number of solutions at the same moment.Unfortunately, there are too many participants, and the website is not always working. Pasha received the information that the website will be working only during m time periods, jth period is represented by its starting moment lj and ending moment rj. Of course, Pasha can send his solution only when the website is working. In other words, Pasha can send his solution at some moment T iff there exists a period x such that lx ≤ T ≤ rx.Pasha wants to know his best possible result. We need to tell him the minimal moment of time by which he is able to have solutions to all problems submitted, if he acts optimally, or say that it's impossible no matter how Pasha solves the problems.

The first line contains one integer n (1 ≤ n ≤ 1000) — the number of problems. The second line contains n integers ai (1 ≤ ai ≤ 105) — the time Pasha needs to solve ith problem. The third line contains one integer m (0 ≤ m ≤ 1000) — the number of periods of time when the website is working. Next m lines represent these periods. jth line contains two numbers lj and rj (1 ≤ lj < rj ≤ 105) — the starting and the ending moment of jth period. It is guaranteed that the periods are not intersecting and are given in chronological order, so for every j > 1 the condition lj > rj - 1 is met.

If Pasha can solve and submit all the problems before the end of the contest, print the minimal moment of time by which he can have all the solutions submitted. Otherwise print "-1" (without brackets).

NoteIn the first example Pasha can act like this: he solves the second problem in 4 units of time and sends it immediately. Then he spends 3 time units to solve the first problem and sends it 7 time units after the contest starts, because at this moment the website starts working again.In the second example Pasha invents the solution only after the website stops working for the last time.In the third example Pasha sends the solution exactly at the end of the first period.

var n = parseInt(readline());
var q = Array(n);
var arr = readline().split(' ');
var total = 0;
for (var i = 0; i < n; i ++)
{
    q[i] = parseInt(arr[i]);
    total += q[i];
}
var m = parseInt(readline());
var t = Array(m);
var ret = -1;
for (var i = 0; i < m; i ++)
{
    var arr = readline().split(' ');
    t[i] = [parseInt(arr[0]), parseInt(arr[1])];
    if (total < t[i][0])
    {
        ret = t[i][0];
        break;
    }
    else if (total >= t[i][0] && total <= t[i][1])
    {
        ret = total;
        break;
    }
}
print(ret);

  var n = parseInt(readline());
  var a = readline().split(' ').map(x => parseInt(x));
  var tot = 0;
  a.forEach(x => tot += x);
  var m = parseInt(readline());
  var l = [];
  var r = [];
  var res = Infinity;
  for(var i = 0; i < m; i += 1) {
    var tmp = readline().split(' ').map(x => parseInt(x));
    var l = tmp[0];
    var r = tmp[1];
    if(tot >= l && tot <= r) {
      res = tot;
      break;
    }
    if(tot <= l) {
      res = l;
      break;
    }
  }
  print(res === Infinity ? -1 : res);