You are given a palindromic string $$$s$$$ of length $$$n$$$.You have to count the number of indices $$$i$$$ $$$(1 \le i \le n)$$$ such that the string after removing $$$s_i$$$ from $$$s$$$ still remains a palindrome. For example, consider $$$s$$$ = "aba"  If we remove $$$s_1$$$ from $$$s$$$, the string becomes "ba" which is not a palindrome.  If we remove $$$s_2$$$ from $$$s$$$, the string becomes "aa" which is a palindrome.  If we remove $$$s_3$$$ from $$$s$$$, the string becomes "ab" which is not a palindrome. A palindrome is a string that reads the same backward as forward. For example, "abba", "a", "fef" are palindromes whereas "codeforces", "acd", "xy" are not.

The input consists of multiple test cases. The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^3)$$$  — the number of test cases. Description of the test cases follows. The first line of each testcase contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$  — the length of string $$$s$$$. The second line of each test case contains a string $$$s$$$ consisting of lowercase English letters. It is guaranteed that $$$s$$$ is a palindrome. It is guaranteed that sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer  — the number of indices $$$i$$$ $$$(1 \le i \le n)$$$ such that the string after removing $$$s_i$$$ from $$$s$$$ still remains a palindrome.

NoteThe first test case is described in the statement.In the second test case, the indices $$$i$$$ that result in palindrome after removing $$$s_i$$$ are $$$3, 4, 5, 6$$$. Hence the answer is $$$4$$$. In the third test case, removal of any of the indices results in "d" which is a palindrome. Hence the answer is $$$2$$$.

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

let currentLine = 0;
let inputString = "";

process.stdin.on("data", (raw_data) => {
  inputString += raw_data;
});

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

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

function solve() {
  const n = readLine();
  const string = readLine();
  let isFoundAnswer = false;

  if (n % 2 === 0) {
    for (let x = n / 2 - 1; x >= 0; x--) {
      if (string[x] != string[x - 1]) {
        console.log((n / 2 - x) * 2);
        isFoundAnswer = true;
        break;
      }
    }
  } else {
    for (let x = Math.floor(n / 2); x >= 0; x--) {
      if (string[x] != string[x - 1]) {
        console.log((n / 2 - x) * 2);
        isFoundAnswer = true;
        break;
      }
    }
  }

  if (isFoundAnswer === false) {
    console.log(n);
  }
}

function main() {
  let T = readLine();
  while (T--) {
    solve();
  }
}

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

    const isPalindrome = str => str === str.split('').reverse().join('');

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let s = readline();

        let mid = Math.floor(n / 2);
        if (!isPalindrome(s.substring(0, mid) + s.substring(mid + 1))) {
            output(0);
        }
        let m = s[mid];
        let left = mid - 1;
        let right = mid + 1;

        let total = 1;

        const isOk = index => index >=0 && index < n && s[index] === m;

        while (isOk(left)) {
            left--;
            total++;
        }

        while (isOk(right)) {
            right++;
            total++;
        }

        output(total);
    }
}

'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, s) {
  let res = 1,
      t = Math.floor((n - 1) / 2);
  for (let i = t + 1; i < n; i++) {
    if (s[i] === s[t]) res++;else break;
  }
  for (let i = t - 1; i >= 0; i--) {
    if (s[i] === s[t]) res++;else break;
  }
  return res;
}

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const n = Number(await read());
    const s = await read();
    res.push(solve(n, s));
  }
  console.log(res.join('\n'));
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

var num = parseInt(readline(), 10);

for(var i = 0; i < num; i++){
    var count = 0;
    var len = parseInt(readline(), 10);
    var str = readline();

    var k;
    if(len % 2 === 0) {
        k = len / 2;
    }else {
        k = (len - 1) / 2;
    }

    var char = str[k];
    while(str[k] == char && k > -1){
        count++;
        k--;
    }

    if(len % 2 === 0) {
        k = len / 2;
    }else {
        k = (len - 1) / 2;
    }

    while(str[k + 1] == char && k < len){
        count++;
        k++;
    }
    print(count);
}

T = readline()
while (T--) {
   n = +readline()
   a = readline().split('')

   repeat = 0
   half = 0
   half = Math.floor(n/2)

   for(i = half; i< n-1; i++){
      if(a[i] ===a[i+1])
         repeat++
      else
         break
   }

   if(n%2 != 0)
      ans = 1 + 2*repeat
   else
      ans = 2 * (1+ repeat)
   print( ans)
}

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

let currentLine = 0;
let inputString = "";

process.stdin.on("data", (raw_data) => {
  inputString += raw_data;
});

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

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

function solve() {
  const n = readLine();
  const string = readLine();
  let isFoundAnswer = false;

  if (n % 2 === 0) {
    for (let x = 1; x < n; x++) {
      if (string[x] !== string[x - 1]) {
        console.log(n / 2 - x + 1);
        isFoundAnswer = true;
        break;
      }
    }
    if (!isFoundAnswer) {
      console.log(n);
    }
  } else {
    for (let x = 1; x < n; x++) {
      if (string[x] !== string[x - 1]) {
        console.log(Math.round(n - x) - 1);
        isFoundAnswer = true;
        break;
      }
    }
    if (!isFoundAnswer) {
      console.log(n);
    }
  }
}

function main() {
  let T = readLine();
  while (T--) {
    solve();
  }
}

var num = parseInt(readline(), 10);

for(var i = 0; i < num; i++){
    var count = 0;
    var len = parseInt(readline(), 10);
    var str = readline();

    var k = Math.round(len / 2);
    var char = str[k];
    while(str[k] == char || k > -1){
        count++;
        k--;
    }
    k = Math.round(len / 2) + 1;
    while(str[k] == char || k < len){
        count++;
        k++;
    }
    print(count);
}

var num = parseInt(readline(), 10);

for(var i = 0; i < num; i++){
    var count = 0;
    var len = parseInt(readline(), 10);
    var str = readline();

    var k = Math.floor(len / 2);
    var char = str[k];
    while(str[k] == char){
        count++;
        if(k == len - 1){
            break;
        }
        k--;
    }
    while(str[k] == char){
        count++;
        if(k == len - 1){
            break;
        }
        k++;
    }
    print(count);
}

var num = parseInt(readline(), 10);

for(var i = 0; i < num; i++){
    var count = 0;
    var len = parseInt(readline(), 10);
    var str = readline();

    var k = Math.floor(len / 2);
    var char = str[k];
    while(str[k] == char){
        count++;
        if(k = len - 1){
            break;
        }
        k--;
    }
    while(str[k] == char){
        count++;
        if(k = len - 1){
            break;
        }
        k++;
    }
    print(count);
}

var num = parseInt(readline(), 10);

for(var i = 0; i < num; i++){
    var count = 0;
    var len = parseInt(readline(), 10);
    var str = readline();

    var k = Math.floor(len / 2);
    var char = str[k];
    while(str[k] == char){
        count++;
        if(k == len - 1){
            break;
        }
        k--;
    }
    while(str[k] == char){
        count++;
        if(k == len - 1){
            break;
        }
        k++;
    }
}

var num = parseInt(readline(), 10);

for(var i = 0; i < num; i++){
    var count = 0;
    var len = parseInt(readline(), 10);
    var str = readline();

    for(var k = 0; k < len; k++){
        var newStr = "";
        var newStrRev = "";

        var atrArr = str.split("").splice(k, 1);

        for(var j = 0; j < len - 1; j++){
            newStr += atrArr[j];
            newStrRev += atrArr[len - 2 - j];
        }
        if(newStr == newStrRev) count++;
    }
    print(count);
}

var num = parseInt(readline(), 10);

for(var i = 0; i < num; i++){
    var count = 0;
    var len = parseInt(readline(), 10);
    var str = readline();

    for(var k = 0; k < len; k++){
        var newStr = "";
        var newStrRev = "";

        str.split("").splice(k, 1);

        for(var j = 0; j < len - 1; j++){
            newStr += str[j];
            newStrRev += str[len - 2 - j];
        }
        if(newStr == newStrRev) count++;
    }
    print(count);
}

var num = parseInt(readline(), 10);

for(var i = 0; i < num; i++){
    var count = 0;
    var len = parseInt(readline(), 10);
    var str = readline();
    var newStr = "";
    var newStrRev = "";
    for(var k = 0; k < len; k++){
        str.split("").splice(k, 1);

        for(var j = 0; j < len - 1; j++){
            newStr += str[j];
            newStrRev += str[len - 2 - j];
        }
        if(newStr == newStrRev) count++;
    }
    print(count);
}

var num = parseInt(readline(), 10);

for(var i = 0; i < num; i++){
    var count = 0;
    var len = parseInt(readline(), 10);
    var str = readline();

    var strNew = "";
    var strNewReversed = "";
    var temp = "";

    for(var k = 0; k < len; k++){
        strNew = str.split("").splice(k, 1).join("");
        var ispoll = true;
        for(var j = 0; j < strNew.length; j++){
            if(strNew[j] === strNew[strNew.length - j]) ispoll = false;
        }
        if(ispoll) {
            count++;
        }
    }
    print(count);
}

var num = parseInt(readline(), 10);

for(var i = 0; i < num; i++){
    var count = 0;
    var len = parseInt(readline(), 10);
    var str = readline();

    var strNew = "";
    var strNewReversed = "";
    var temp = "";

    for(var k = 0; k < len; k++){
        temp = str.split("").splice(k, 1);
        strNewReversed = temp.reverse().join("");
        strNew = temp.join("");
        if(strNew === strNewReversed) {
            count++;
        }
    }
    print(count);
}

var num = parseInt(readline(), 10);

for(var i = 0; i < num; i++){
    var count = 0;
    var len = parseInt(readline(), 10);
    var str = readline();
    var strNew = "";
    var strNewReversed = "";
    var temp = "";
    for(var k = 0; k < str.length; k++){
        temp = str.split("").splice(k, 1).join("");
        strNewReversed = str.split("").splice(k, 1).reverse().join("");
        strNew = str.split("").splice(k, 1).join("");
        if(strNew === strNewReversed) count++;
    }
    print(count);
}

T = readline()
while (T--) {
   n = +readline()
   a = readline().split('')

   repeat = 0
   half = 0
   half = Math.ceil(n/2)

   for(i = half; i< n-1; i++){
      if(a[i] ===a[i+1])
         repeat++
      else
         break
   }

   if(n%2 != 0)
      ans = 1 + 2*repeat
   else
      ans = 2 * (1+ repeat)

   print( ans)
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Initially all elements of $$$a$$$ are either $$$0$$$ or $$$1$$$. You need to process $$$q$$$ queries of two kinds:  1 x : Assign to $$$a_x$$$ the value $$$1 - a_x$$$.  2 k : Print the $$$k$$$-th largest value of the array. As a reminder, $$$k$$$-th largest value of the array $$$b$$$ is defined as following: Sort the array in the non-increasing order, return $$$k$$$-th element from it. For example, the second largest element in array $$$[0, 1, 0, 1]$$$ is $$$1$$$, as after sorting in non-increasing order it becomes $$$[1, 1, 0, 0]$$$, and the second element in this array is equal to $$$1$$$.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the length of the given array and the number of queries. The second line contains $$$n$$$ integers $$$a_1, a_2, a_3, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$) — elements of the initial array. Each of the following $$$q$$$ lines contains two integers. The first integer is $$$t$$$ ($$$1 \le t \le 2$$$) — the type of query.   If $$$t = 1$$$ the second integer is $$$x$$$ ($$$1 \le x \le n$$$) — the position of the modified number. You have to assign to $$$a_x$$$ the value $$$1 - a_x$$$. If $$$t = 2$$$ the second integer is $$$k$$$ ($$$1 \le k \le n$$$) — you need to print the $$$k$$$-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying $$$t = 2$$$).

For each query of the second type, print a single integer — the answer to the query.

NoteInitially $$$a = [1, 1, 0, 1, 0]$$$.The first operation is printing the third largest value, which is $$$1$$$.The second operation is assigning $$$a_2$$$ the value $$$0$$$, $$$a$$$ becomes $$$[1, 0, 0, 1, 0]$$$.The third operation is printing the third largest value, it is $$$0$$$.The fourth operation is printing the first largest value, it is $$$1$$$.The last operation is printing the fifth largest value, it is $$$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();
});
var mod = 1000000000 + 7

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

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

function main() {
    // var x = parseInt(readline())
    // var x = new Array(n)
    var [n, q] = readline().split(' ').map((x, iii) => {
        return x
    })
    var length1 = 0

    var a = readline().split(' ').map((x, iii) => {
        if (parseInt(x) === 1) length1++
        return parseInt(x)
    })

    for (let i = 0; i < q; i++) {
        var [x, k] = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        if (x === 1) {
            if (a[k - 1] === 1) length1--
            if (a[k - 1] === 0) length1++
            a[k - 1] = 1 - a[k - 1]
            continue
        }
        if (k > length1) console.log(0)
        else console.log(1)
    }
}

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

let inputString = '';
let currentLine = 0;

process.stdin.on('data', input => inputString += input);
process.stdin.on('end', () => {
    inputString = inputString.trim().split('\n').map(string => string.trim());
    main();
});

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

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

function readElements(parse = parseInt, separator = ' ') {
    return readLine().split(separator).map(input => parse ? parse(input) : input);
}

function main() {
    let zeros = 0;
    let ones = 0;
    const [_, queries] = readElements();
    const list = readLine().split(' ').map(input => {
        input = parseInt(input);
        if (input === 1) {
            ones++;
        } else {
            zeros++;
        }

        return input;
    });

    for (let q = 0; q < queries; q++) {
        const [type, value] = readElements();
        let index = value - 1;

        if(type === 2) {
            print((value <= ones) ? "1" : "0");
        } else {
            list[index] = 1 - list[index];
            if (list[index] === 1) {
                ones++;
                zeros--;
            } else{
                zeros++;
                ones--;
            }
        }
    }
}

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
let input = [];
rl.on('line', line => {
    input.push(line);
})
rl.on('close', line => {
    var [n, k] = input[0].split(" ").map((i) => {
        return Number(i);
    })
    var arr = input[1].split(" ").map((i) => {
        return Number(i);
    });
    var count = 0;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === 1) {
            count++;
        }
    }
    for (var i = 2; i < input.length; i++) {
        var [type, value] = input[i].split(" ").map((i) => {
            return Number(i);
        });
        if (type === 1) {
            var index = value - 1;
            arr[index] = 1 - arr[index];
            if (arr[index] === 0) {
                count--;
            } else {
                count++;
            }
        } else {
            if (value > count) {
                console.log(0);
            } else {
                console.log(1);
            }
        }
    }
})

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
function 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 N = nextInt();
	var Q = nextInt();
	var list = nextIntArray(N);
	var map = [0, 0];
	for(var i = 0; i < N; i++){
		map[list[i]]++;
	}
	for(var i = 0; i < Q; i++){
		var t = nextInt();
		var x = nextInt();
		if(t == 1){
			x--;
			map[list[x]]--;
			list[x] = 1 - list[x];
			map[list[x]]++;
		}else{
			if(map[1] >= x){
				myout(1);
			}else{
				myout(0);
			}
		}
	}
}

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

function main() {
  var nq = readNumArray();
  var n = nq[0];
  var q = nq[1];
  var arr = readNumArray();
  var ones = 0;
  for (var i = 0; i < n; i++) {
    if (arr[i] === 1) {
      ones++;
    }
  }
  for (var i = 0; i < q; i++) {
    var tx = readNumArray();
    var t = tx[0];
    var x = tx[1];
    if (t === 1) {
      arr[x-1] = 1 - arr[x-1];
      if (arr[x-1]) {
        ones++
      } else {
        ones--;
      }
    }
    if (t === 2) {
      if (x <= ones) {
        print('1')
      } else {
        print('0')
      }
    }
  }
}

main();

'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();
});
var mod = 1000000000 + 7

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

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

function main() {
    // var x = parseInt(readline())
    // var x = new Array(n)
    var [n, q] = readline().split(' ').map((x, iii) => {
        return x
    })
    var length1 = 0

    var a = readline().split(' ').map((x, iii) => {
        if (parseInt(x) === 1) length1++
        return parseInt(x)
    })

    for (let i = 0; i < q; i++) {
        var [x, k] = readline().split(' ').map((x, iii) => {
            return parseInt(x)
        })
        if (x === 1) {
            if(a[k-1] ===1) length1--
            a[k - 1] = 1 - a[k - 1]
            continue
        }
        if(k>length1) console.log(0)
        else console.log(1)
    }
}


One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2·m from left to right, then the j-th flat of the i-th floor has windows 2·j - 1 and 2·j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100) — the number of floors in the house and the number of flats on each floor respectively. Next n lines describe the floors from top to bottom and contain 2·m characters each. If the i-th window of the given floor has lights on, then the i-th character of this line is '1', otherwise it is '0'.

Print a single integer — the number of flats that have lights on in at least one window, that is, the flats where, according to Vitaly, people aren't sleeping.

NoteIn the first test case the house has two floors, two flats on each floor. That is, in total there are 4 flats. The light isn't on only on the second floor in the left flat. That is, in both rooms of the flat the light is off.In the second test case the house has one floor and the first floor has three flats. The light is on in the leftmost flat (in both windows) and in the middle flat (in one window). In the right flat the light is off.

var x = readline().split(' ');
var n = parseInt(x[0]);
var m = parseInt(x[1]);

var ans = 0;
for(var i=0;i<n;++i) {
    x = readline().split(' ');
    for(var j=0;j<m; ++j) {
        if (x[j*2]=='1' || x[j*2+1]=='1') ++ans;
    }
}
print(ans);

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

rl.on('line', (d) => {
  if (c === 0) {
    [n, m] = d.split(' ').map(Number);
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);

  for (let i = 0; i < arr.length; i += 2) {
    if (arr[i] === 1 || arr[i + 1] === 1) {
      ans++;
    }
  }

  c++;
});

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

let input = [];

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

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

RL.on('close', () => {
    let {0:n, 1:m} = {...input[0].split(' ')};
    n = parseInt(n); m = parseInt(m);

    let answer = 0;
    for(let i = 0; i < n; i++){
        const data = []; input[i+1].split(' ').forEach(j => data.push(parseInt(j)));
        for(j = 0; j < m*2; j+=2){
            if(data[j] === 1 || data[j+1] === 1)
                answer++;
            //console.log(`data[j] = ${data[j]}; data[j+1] = ${data[j+1]}`);
        }
    }

    console.log(answer);
});

function imp()
{
    var oneline = readline();
    var elements = oneline.split(" ");
    var n = parseInt(elements[0]);
    var m = parseInt(elements[1]);
    var count = 0;
    for(var i=1;i<=n;i++)
    {
        oneline  = readline();
        elements = oneline.split(" ");
        for(var j=0;j<2*m;j=j+2)
            if(elements[j] == '1' || elements[j+1] == '1')
                count++;
    }
    print(count);
}
imp();

var inputs = readline().split(' '),
	n = parseInt(inputs[0]),
	m = parseInt(inputs[1]),
	windows = [],
	res = 0;

for (var i = 0; i < n; i++) {
	inputs = readline().split(' ');
	windows = windows.concat(inputs);
}

for (var i = 0; i < windows.length; i+=2) {
	if (windows[i] == '1' || windows[i+1] == '1') ++res;
}

print(res);

var solve = function(a, n, m) {
    var ans = 0;
    for(var i=0;i<n;i++) {
        for(var j=0;j<m;j++) {
            if(a[i][2*j] == 1 || a[i][2*j+1] == 1) {
                ans ++;
            }
        }
    }
    return ans;
};
var x = readline().split(' ');
var n = parseInt(x[0]);
var m = parseInt(x[1]);
var a = [];
for(var i=0;i<n;i++) {
    x = readline().split(' ');
    var b = [];
    for(var j=0;j<x.length;j++) {
        b[j] = parseInt(x[j]);
    }
    a.push(b);
}
var ans = solve(a, n, m);
print(ans);

var line = readline().split(' ');
var kol = 0;

while(line[0] > 0) {
    var x = readline().split(' ');
    for(var i=1; i<line[1]*2; i+=2 ) {
            if(parseInt(x[i]) || parseInt(x[i-1])) {
                //write(x[i] + ' ' + i + '\n');
                kol ++;
            }
    }

    //write(kol)
    line[0] --;
}
write(kol)

function imp()
{
    var oneline = readline();
    var elements = oneline.split(" ");
    var n = parseInt(elements[0]);
    var m = parseInt(elements[1]);
    var count = 0;
    for(var i=1;i<=n;i++)
    {
        oneline  = readline();
        elements = oneline.split(" ");
        for(var j=0;j<m;j=j+2)
            if(elements[j] == '1' || elements[j+1] == '1')
                count++;
    }
    print(count);
}
imp();

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

rl.on('line', (d) => {
  if (c === 0) {
    [n, m] = d.split(' ').map(Number);
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  let idx = 0;

  while (idx < m) {
    for (let i = idx * m; i < (idx + 1) * m; i++) {
      if (arr[i] === 1) {
        ans++;
        break;
      }
    }

    idx++;
  }

  c++;
});

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

function imp()
{
    var oneline = readline();
    var elements = oneline.split(" ");
    var n = elements[0];
    var m = elements[1];
    var count = 0;
    for(var i=1;i<=n;i++)
    {
        oneline  = readline();
        elements = oneline.split(" ");
        for(var j=0;j<m;j=j+2)
            if(elements[j] == 1 || elements[j+1]==1)
                count++;
    }
    print(count);
}
imp();

function imp()
{
    var firstline = readline();
    var elements = firstline.split(" ");
    var n = elements[0];
    var m = elements[1];
    var count = 0;
    for(var i=1;i<=n;i++)
    {
        var oneline  = readline();
        var ele = oneline.split(" ");
        for(var j=0;j<m;j=j+2)
            if(ele[j] == 1 || ele[j+1]==1)
                count++;
    }
    print(count);
}
imp();


After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested in the structure of this tree.After doing some research he formed q queries he is interested in. The i-th query asks to find a centroid of the subtree of the node vi. Your goal is to answer all queries.Subtree of a node is a part of tree consisting of this node and all it's descendants (direct or not). In other words, subtree of node v is formed by nodes u, such that node v is present on the path from u to root.Centroid of a tree (or a subtree) is a node, such that if we erase it from the tree, the maximum size of the connected component will be at least two times smaller than the size of the initial tree (or a subtree).

The first line of the input contains two integers n and q (2 ≤ n ≤ 300 000, 1 ≤ q ≤ 300 000) — the size of the initial tree and the number of queries respectively. The second line contains n - 1 integer p2, p3, ..., pn (1 ≤ pi ≤ n) — the indices of the parents of the nodes from 2 to n. Node 1 is a root of the tree. It's guaranteed that pi define a correct tree. Each of the following q lines contain a single integer vi (1 ≤ vi ≤ n) — the index of the node, that define the subtree, for which we want to find a centroid.

For each query print the index of a centroid of the corresponding subtree. If there are many suitable nodes, print any of them. It's guaranteed, that each subtree has at least one centroid.

Note  The first query asks for a centroid of the whole tree — this is node 3. If we delete node 3 the tree will split in four components, two of size 1 and two of size 2.The subtree of the second node consists of this node only, so the answer is 2.Node 3 is centroid of its own subtree.The centroids of the subtree of the node 5 are nodes 5 and 6 — both answers are considered correct.

var nq = readInts();
var n  = nq[0];
var q  = nq[1];

var total = new Array(n + 1);
var max   = new Array(n + 1);
var ans   = new Array(n + 1);
var p     = new Array(n + 1);
var e     = new Array(n + 1);
var done  = new Array(n + 1);

p[1] = 1;

var i = 0;
var ps = readInts();
for (; i < n - 1; i++) {
    p[i + 2] = ps[i];
    e[ps[i]] = e[ps[i]] || [];
    e[ps[i]].push(i + 2);
}

 // dfs(1);
var stack = [1];
while (stack.length) {
    var u = stack[stack.length - 1];
    // print (u, done[u]);
    if (done[u]) {
        if (u !== 1) {
            total[p[u]] += total[u];
            if (!max[p[u]] || total[u] > total[max[p[u]]]) {
                max[p[u]] = u;
            }
        }

        if (!max[u]) {
            max[u] = u;
        }

        ans[u] = find(u);
        stack.pop();
        continue;
    }

    done[u] = true;
    total[u] = 1;
    // print (u, done[u]);

    if (e[u]) {
        for (var i = 0, len = e[u].length; i < len; i++) {
            stack.push(e[u][i]);
        }
    }
}

// print(total);
// print(max);
// print(ans);

for (i = 0; i < q; i++) {
    var v = parseInt(readline(), 10);
    print(ans[v]);
}

/**
 * functions below
 */

function readInts() {
    return readline().split(' ').map(function(v) {
        return parseInt(v, 10);
    })
}

function find(u) {
    if (total[u] <= 2) {
        return u;
    }

    var half = total[u] / 2;

    if (total[max[u]] <= half) {
        return u;
    }

    var start = ans[max[u]];
    while (start != u) {
        var top = total[u] - total[start];
        var bottom = total[max[start]];
        if (top <= half && bottom <= half) {
            return start;
        }

        start = p[start];
    }

    return 0;
}

function dfs(u) {
    if (!e[u]) {
        ans[u] = u;
        max[u] = u;
        total[u] = 1;
        return 1;
    }

    var localMax = 0;
    var localMaxI = u;
    var tot = 1;
    for (var i = 0, len = e[u].length; i < len; i++) {
        var tmp = dfs(e[u][i]);
        tot += tmp;
        if (localMax < tmp) {
            localMax = tmp;
            localMaxI = e[u][i];
        }
    }

    total[u] = tot;
    max[u] = localMaxI;

    // calc ans
    ans[u] = find(u);

    return tot;
}

var nq = readInts();
var n  = nq[0];
var q  = nq[1];

var total = new Array(n + 1);
var max   = new Array(n + 1);
var ans   = new Array(n + 1);
var p     = new Array(n + 1);
var e     = new Array(n + 1);
var done  = new Array(n + 1);

p[1] = 1;
total[0] = 0;

var i = 0;
var ps = readInts();
for (; i < n - 1; i++) {
    p[i + 2] = ps[i];
    e[ps[i]] = e[ps[i]] || [];
    e[ps[i]].push(i + 2);
}

var queue = [1];
i = 0;
while (1) {
    var to = e[queue[i]];
    if (to) {
        for (var j = 0; j < to.length; j++) {
            queue.push(to[j]);
        }
    }
    i++;
    if (i === queue.length) {
        break;
    }
}
queue.reverse();

for (i = 0, len = queue.length; i < len; i++) {
    var u = queue[i];
    total[u] = 1;
    max[u] = 0;
    var to = e[u];
    if (to) {
        for (var j = 0; j < to.length; j++) {
            total[u] += total[to[j]];
            if (total[to[j]] > total[max[u]]) {
                max[u] = to[j];
            }
        }
    }
    if (!max[u]) {
        max[u] = u;
    }

    ans[u] = find(u);
}

 // dfs(1);
// var stack = [1];
// while (stack.length) {
//     var u = stack[stack.length - 1];
//     // print (u, done[u]);
//     if (done[u]) {
//         if (u !== 1) {
//             total[p[u]] += total[u];
//             if (!max[p[u]] || total[u] > total[max[p[u]]]) {
//                 max[p[u]] = u;
//             }
//         }

//         if (!max[u]) {
//             max[u] = u;
//         }

//         ans[u] = find(u);
//         stack.pop();
//         continue;
//     }

//     done[u] = true;
//     total[u] = 1;
//     // print (u, done[u]);

//     if (e[u]) {
//         for (var i = 0, len = e[u].length; i < len; i++) {
//             stack.push(e[u][i]);
//         }
//     }
// }

// print(total)
// print(max)
// print(ans)

for (i = 0; i < q; i++) {
    var v = parseInt(readline(), 10);
    print(ans[v]);
}

/**
 * functions below
 */

function readInts() {
    return readline().split(' ').map(function(v) {
        return parseInt(v, 10);
    })
}

function find(u) {
    if (total[u] <= 2) {
        return u;
    }

    var half = total[u] / 2;

    if (total[max[u]] <= half) {
        return u;
    }

    var start = ans[max[u]];
    while (start != u) {
        var top = total[u] - total[start];
        var bottom = total[max[start]];
        if (top <= half && bottom <= half) {
            return start;
        }

        start = p[start];
    }

    return 0;
}

function dfs(u) {
    if (!e[u]) {
        ans[u] = u;
        max[u] = u;
        total[u] = 1;
        return 1;
    }

    var localMax = 0;
    var localMaxI = u;
    var tot = 1;
    for (var i = 0, len = e[u].length; i < len; i++) {
        var tmp = dfs(e[u][i]);
        tot += tmp;
        if (localMax < tmp) {
            localMax = tmp;
            localMaxI = e[u][i];
        }
    }

    total[u] = tot;
    max[u] = localMaxI;

    // calc ans
    ans[u] = find(u);

    return tot;
}

var nq = readInts();
var n  = nq[0];
var q  = nq[1];

var total = new Array(n + 1);
var max   = new Array(n + 1);
var ans   = new Array(n + 1);
var p     = new Array(n + 1);
var e     = new Array(n + 1);
var done  = new Array(n + 1);

p[1] = 1;

var i = 0;
var ps = readInts();
for (; i < n - 1; i++) {
    p[i + 2] = ps[i];
    e[ps[i]] = e[ps[i]] || [];
    e[ps[i]].push(i + 2);
}

 // dfs(1);
var stack = [1];
while (stack.length) {
    var u = stack[stack.length - 1];
    // print (u, done[u]);
    if (done[u]) {
        if (u !== 1) {
            total[p[u]] += total[u];
            if (!max[p[u]] || total[u] > total[max[p[u]]]) {
                max[p[u]] = u;
            }
        }

        ans[u] = find(u);
        stack.pop();
        continue;
    }

    done[u] = true;
    total[u] = 1;
    // print (u, done[u]);

    if (e[u]) {
        for (var i = 0, len = e[u].length; i < len; i++) {
            stack.push(e[u][i]);
        }
    }
}

for (i = 0; i < q; i++) {
    var v = parseInt(readline(), 10);
    print(ans[v]);
}

/**
 * functions below
 */

function readInts() {
    return readline().split(' ').map(function(v) {
        return parseInt(v, 10);
    })
}

function find(u) {
    if (total[u] <= 2) {
        return u;
    }

    var half = total[u] / 2;

    if (max[u] <= half) {
        return u;
    }

    var start = ans[max[u]];
    while (start != u) {
        var top = total[u] - total[start];
        var bottom = total[max[start]];
        if (top <= half && bottom <= half) {
            return start;
        }

        start = p[start];
    }

    return 0;
}

function dfs(u) {
    if (!e[u]) {
        ans[u] = u;
        max[u] = u;
        total[u] = 1;
        return 1;
    }

    var localMax = 0;
    var localMaxI = u;
    var tot = 1;
    for (var i = 0, len = e[u].length; i < len; i++) {
        var tmp = dfs(e[u][i]);
        tot += tmp;
        if (localMax < tmp) {
            localMax = tmp;
            localMaxI = e[u][i];
        }
    }

    total[u] = tot;
    max[u] = localMaxI;

    // calc ans
    ans[u] = find(u);

    return tot;
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. For each $$$i$$$ ($$$1 \le i \le n$$$) the following inequality is true: $$$-2 \le a_i \le 2$$$.You can remove any number (possibly $$$0$$$) of elements from the beginning of the array and any number (possibly $$$0$$$) of elements from the end of the array. You are allowed to delete the whole array.You need to answer the question: how many elements should be removed from the beginning of the array, and how many elements should be removed from the end of the array, so that the result will be an array whose product (multiplication) of elements is maximal. If there is more than one way to get an array with the maximum product of elements on it, you are allowed to output any of them. The product of elements of an empty array (array of length $$$0$$$) should be assumed to be $$$1$$$.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. Then the descriptions of the input test cases follow. The first line of each test case description contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) —the length of array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_i| \le 2$$$) — elements of array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output two non-negative numbers $$$x$$$ and $$$y$$$ ($$$0 \le x + y \le n$$$) — such that the product (multiplication) of the array numbers, after removing $$$x$$$ elements from the beginning and $$$y$$$ elements from the end, is maximal. If there is more than one way to get the maximal product, it is allowed to output any of them. Consider the product of numbers on empty array to be $$$1$$$.

NoteIn the first case, the maximal value of the product is $$$2$$$. Thus, we can either delete the first three elements (obtain array $$$[2]$$$), or the last two and one first element (also obtain array $$$[2]$$$), or the last two elements (obtain array $$$[1, 2]$$$). Thus, in the first case, the answers fit: "3 0", or "1 2", or "0 2".In the second case, the maximum value of the product is $$$1$$$. Then we can remove all elements from the array because the value of the product on the empty array will be $$$1$$$. So the answer is "3 0", but there are other possible answers.In the third case, we can remove the first two elements of the array. Then we get the array: $$$[-2, 2, -1]$$$. The product of the elements of the resulting array is $$$(-2) \cdot 2 \cdot (-1) = 4$$$. This value is the maximum possible value that can be obtained. Thus, for this case the answer is: "2 0".

var n, a;

    function solve(s, e) {
        var negs = 0;
        var bits = 1;
        for (var i = s; i <= e; i++) {
            if (a[i] < 0) {
                negs++;
            }
            if (Math.abs(a[i]) == 2) {
                bits++;
            }
        }
        if (negs & 1) {
            var b = s;
            var bitsS = bits;
            while (a[b] > 0) {
                if (Math.abs(a[b]) == 2) {
                    bitsS--;
                }
                b++;
            }
            if (Math.abs(a[b]) == 2) {
                bitsS--;
            }
            var c = e;
            var bitsE = bits;
            while (a[c] > 0) {
                if (Math.abs(a[c]) == 2) {
                    bitsE--;
                }
                c--;
            }
            if (Math.abs(a[c]) == 2) {
                bitsE--;
            }
            //console.log(bits, bitsS, bitsE)
            if (bitsS > bitsE) {
                return [bitsS, b+1, e];
            } else {
                return [bitsE, s, c-1];
            }
        } else {
            return [bits, s, e];
        }
    }
    var tests = parseInt(readline());
    for (var t=0; t < tests; t++) {
        n = parseInt(readline());
        a = readline().split(' ').map(x=>parseInt(x));
        var start = 0;
        var ans = [1, 0, -1];
        while (start < n) {
            while (start < n && !a[start]) {
                start++;
            }
            var end = start+1;
            while (end < n && a[end]) {
                end++;
            }
            var reply = solve(start, end-1);
            //console.log(reply);
            if (reply[0] > ans[0]) {
                ans = reply;
            }
            start = end;
        }
        print(ans[1] + " " + (n - ans[2] - 1));
    }

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

function getMax(a, start, end) {
  var _a, _b
  const n = end - start + 1
  let first = -1,
    last = -1,
    sum = new Array(n).fill(0),
    count = 0
  for (let i = 0; i < n; i++) {
    sum[i] = ((_a = sum[i - 1]) !== null && _a !== void 0 ? _a : 0) + (Math.abs(a[i + start]) === 2 ? 1 : 0)
    if (first === -1 && a[i + start] < 0) first = i
    if (a[i + start] < 0) {
      count++
      last = i
    }
  }
  if (count % 2 === 0) {
    return [sum[n - 1] * 2, start, end]
  } else {
    let left = ((_b = sum[last - 1]) !== null && _b !== void 0 ? _b : 0) * 2 + (last > 0 ? 1 : 0),
      right = (sum[n - 1] - sum[first]) * 2 + (first < n - 1 ? 1 : 0)
    if (left >= right) {
      return [left, start, start + last - 1]
    } else {
      return [right, start + first + 1, end]
    }
  }
}
function solve(n, a) {
  let left = -1,
    right = -1,
    max = 1
  for (let i = 0; i < n; i++) {
    if (a[i] !== 0) {
      let j = i
      while (j < n - 1 && a[j + 1] !== 0) j++
      const [num, l, r] = getMax(a, i, j)
      if (max < num) {
        max = num
        left = l
        right = r
      }
      i = j
    }
  }
  if (left === -1) return [0, n]
  else return [left, n - right - 1]
}

void (function main() {
  let t = Number(inputs[0]),
    __ = 1,
    res = []
  for (let _ = 0; _ < t; _++) {
    const n = Number(inputs[__++])
    const a = inputs[__++].trim().split(' ').map(Number)
    const [l, r] = solve(n, a)
    res.push(`${l} ${r}`)
  }
  console.log(res.join('\n'))
})()

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		let ans, mx = 0;
		for (let round = 0; round < 2; round++) {
			let twos = 0, positive = 1, cnt = 0;
			for (let i = 0; i < n; i++) {
				if (a[i] == 0) cnt = 0, twos = 0, positive = 1; else cnt++;
				if (a[i] < 0) positive ^= 1;
				if (Math.abs(a[i]) == 2) twos++;
				if (positive & twos > mx) {
					mx = twos;
					ans = [(i + 1) - cnt, n - (i + 1)];
					if (round) ans.reverse();
				}
				//console.log({round, i, twos, positive, mx, cnt, ans});
			}
			a.reverse();
		}

		if (mx == 0) {
			console.log(n, 0);
		} else {
			console.log(ans.join(' '));
		}

	}
}

const readline = require('readline')

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

function solve(n, nums) {
    let ans = [-1, 3 * n]
    let pos
    let neg
    let pp = -1, pn = -1
    let seg
    nums.forEach((x, i) => {
        if (i) {
            const [sp, vp] = pos
            const [sn, vn] = neg
            if (x > 0) {
                // pos *= x
                // neg *= x
                const pow = x === 1 ? 0 : 1
                pos = [1, vp + pow]
                neg = [sn, vn + pow]
                // ans = Math.max(ans, pos, neg)
                if (pp < 0) pp = i
                if (pn < 0) pn = i
                // if (pos > ans) {
                if (cmp(pos, ans) > 0) {
                    ans = pos
                    seg = [pp, i]
                }
            } else if (x < 0) {
                const pow = x === -1 ? 0 : 1
                if (neg[0] < 0) {
                    if (pp < 0) pp = i
                    if (pn < 0) pn = i
                    // ;[pos, neg] = [neg * x, pos * x]
                    pos = [-sn, vn + pow]
                    neg = [-sp, vp + pow]
                    ;[pp, pn] = [pn, pp]
                    // ans = Math.max(ans, pos, neg)
                    if (cmp(pos, ans) > 0) {
                        ans = pos
                        seg = [pp, i]
                    }
                    if (cmp(neg, ans) > 0) {
                        ans = neg
                        seg = [pn, i]
                    }
                } else {
                    if (pp < 0) pp = i
                    // ;[pos, neg] = [1, pos * x]
                    ;[pp, pn] = [-1, pp]
                    pos = [1, 0]
                    neg = [-1, vp + pow]
                    // ans = Math.max(ans, neg)
                    //
                    if (cmp(neg, ans) > 0) {
                        ans = neg
                        seg = [pn, i]
                    }
                }
            } else {
                // pos = 1
                // neg = 1
                pos = [1, 0]
                neg = [1, 0]
                pp = -1
                pn = -1
                // ans = Math.max(ans, 0)
                //
                if (cmp([1, -1], ans) > 0) {
                    ans = [1, -1] // special 0
                    seg = [i, i]
                }
            }
        } else {
            if (x > 0) {
                // pos = x
                // neg = 1
                pos = [1, x === 1 ? 0 : 1] // pos, power
                neg = [1, 0]
                ans = pos
                pp = i
            } else if (x < 0) {
                // pos = 1
                // neg = x
                pos = [1, 0]
                neg = [-1, x === -1 ? 0 : 1]
                ans = neg
                pn = i
            } else {
                // pos = 1
                // neg = 1
                pos = [1, 0]
                neg = [1, 0]
                ans = [1, -1]
            }
            // ans = Math.max(ans, x)
            seg = [i, i]
        }
        // console.log(pos, neg, ans)
    })
// console.log(ans, seg)
// return
    const [a, b] = seg
    if (cmp(ans, [1, -1]) <= 0) return [0, n].join(' ')
    return [a, n - 1 - b].join(' ')
}
function cmp(a, b) {
    const [sa, va] = a
    const [sb, vb] = b
    if (sa > 0 && sb > 0) {
        return va - vb
    } else if (sa < 0 && sb < 0) {
        return vb - va
    } else if (sa > 0) {
        return 1
    } else {
        return -1
    }
}

'use strict';
const readline = require('readline');
const util = require('util');
const lineReader = readline.createInterface({
    input: process.stdin,
});
let inputPos = 0;
const inputWords = [];
lineReader.on('line', (line) => {
    inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));
});
lineReader.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(inputWords[inputPos++]));
}
function nextStr() {
    return inputWords[inputPos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
let n;
let a;
function solve() {
    const pre2 = af(n).fill(0);
    const preve = af(n).fill(0);
    for (let i = 0; i < n; i++) {
        if (i > 0) {
            pre2[i] = pre2[i - 1];
            preve[i] = preve[i - 1];
        }
        if (a[i] == 0) {
            pre2[i] = 0;
            preve[i] = 0;
        }
        if (a[i] < 0) {
            preve[i]++;
        }
        if (Math.abs(a[i]) == 2) {
            pre2[i]++;
        }
    }
    const lim = af(n).fill(n);
    const lastve = af(n).fill(INIT);
    for (let i = n - 1; i >= 0; i--) {
        if (i < n - 1) {
            lim[i] = lim[i + 1];
            lastve[i] = lastve[i + 1];
        }
        if (a[i] == 0) {
            lim[i] = i;
            lastve[i] = INIT;
        }
        if (a[i] < 0 && lastve[i] == INIT) {
            lastve[i] = i;
        }
    }
    // printf("lim: %j\n", lim);
    // printf("lastve: %j\n", lastve);
    let best2 = 0;
    let l = 0;
    let r = 0; // [l,r)
    for (let i = 0; i < n; i++) {
        if (a[i] == 0) {
            continue;
        }
        let j = lim[i];
        let cnt2 = pre2[j - 1] - (i > 0 ? pre2[i - 1] : 0);
        let cntve = preve[j - 1] - (i > 0 ? preve[i - 1] : 0);
        if ((cntve % 2) == 1) {
            j = lastve[i];
            if (j <= i) {
                continue;
            }
            cnt2 = pre2[j - 1] - (i > 0 ? pre2[i - 1] : 0);
            cntve = preve[j - 1] - (i > 0 ? preve[i - 1] : 0);
        }
        check((cntve % 2) == 0);
        if (cnt2 > best2) {
            best2 = cnt2;
            l = i;
            r = j;
        }
    }
    // printf("best2: %d\n", best2);
    printf("%d %d\n", l, n - r);
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        n = nextInt();
        a = af(n);
        for (let i = 0; i < n; i++) {
            a[i] = nextInt();
        }
        solve();
    }
}

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

module.exports = E;

const ra = ()=>readline().split(' ').map(a=>+a)

const EPS = 1e-6;

const get_cnt = ()=>{
  let cnt = new Map();
  for (let i=-2; i<=2; i++)
    cnt.set(i, 0);
  return cnt;
};

const split = (arr)=>{
  let i=0;
  let sets = [];
  let cur_set = {l: 0, cnt: get_cnt()}
  while (i<arr.length){
    if (arr[i]==0){
      cur_set.r = i;
      if (cur_set.cnt.size)
        sets.push(cur_set);
      cur_set = {l: i+1, cnt: get_cnt()};
      i++;
      continue;
    }
    cur_set.cnt.set(arr[i], cur_set.cnt.get(arr[i])+1);
    i++
  }
  cur_set.r = arr.length
  if (cur_set.cnt.size)
    sets.push(cur_set);
  return sets;
};

const processSet = ({l, r, cnt}, arr)=>{
  debugger
  let power = cnt.get(2) + cnt.get(-2);
  let sign = (cnt.get(-2)+cnt.get(-1));
  let rm_left = 0;
  let rm_right = 0;
  if (sign%2==0){
    return {power, rm_left, rm_right};
  }
  let left_cnt = new Map(cnt);
  let right_cnt = new Map(cnt);
  let i;
  // rm_left
  for (i=l; i<r; i++){
    left_cnt.set(arr[i], left_cnt.get(arr[i])-1)
    if (arr[i]<0){
      break;
    }
  }
  let left_ans = {power: left_cnt.get(2) + left_cnt.get(-2), rm_left: i-l+1, rm_right: 0};
  // rm_right
  for (i=r-1; i>=l; i--){
    right_cnt.set(arr[i], right_cnt.get(arr[i])-1)
    if (arr[i]<0){
      break;
    }
  }
  let right_ans = {power: right_cnt.get(2) + right_cnt.get(-2), rm_left: 0, rm_right: r-i};
  if (left_ans.power>right_ans.power)
    return left_ans;
  else
    return right_ans;
}

const calc = (arr, n)=>{
  let sets = split(arr);
  let maxPower = 0;
  let ans = [arr.length, 0];
  for (let set of sets){
    let {power, rm_left, rm_right} = processSet(set, arr);
    if (power>maxPower){
      maxPower = power;
      ans = [set.l+rm_left, n-set.r+rm_right];
    }
  }
  return ans.join(' ');
  //console.log(arr, '->', sets);
  return
  // set = {l: int, r: int, cnt: Map}
  let l=0, r=0;
  let cnt = new Map();
  for (let i=-2; i<=2; i++)
    cnt.set(i, 0);
  while (l<n){

  }
};

function main() {
    let T = +readline();
    while (T--){
      let n = +readline();
      let arr = ra();
      print(calc(arr, n))
    }
}

E.calc = calc;

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

function getMax(a, start, end) {
  var _a, _b
  const n = end - start + 1
  let first = -1,
    last = -1,
    sum = new Array(n).fill(0),
    count = 0
  for (let i = 0; i <= n; i++) {
    sum[i] = ((_a = sum[i - 1]) !== null && _a !== void 0 ? _a : 0) + (Math.abs(a[i]) === 2 ? 1 : 0)
    if (first === -1 && a[i + start] < 0) first = i
    if (a[i + start] < 0) {
      count++
      last = i
    }
  }
  if (count % 2 === 0) {
    return [sum[n - 1] * 2, start, end]
  } else {
    let left = ((_b = sum[last - 1]) !== null && _b !== void 0 ? _b : 0) * 2 + (last > 0 ? 1 : 0),
      right = (sum[n - 1] - sum[first]) * 2 + (first < n - 1 ? 1 : 0)
    if (left >= right) {
      return [left, start, start + last - 1]
    } else {
      return [right, start + first + 1, end]
    }
  }
}
function solve(n, a) {
  let left = -1,
    right = -1,
    max = 1
  for (let i = 0; i < n; i++) {
    if (a[i] !== 0) {
      let j = i
      while (j < n - 1 && a[j + 1] !== 0) j++
      const [num, l, r] = getMax(a, i, j)
      if (max < num) {
        max = num
        left = l
        right = r
      }
    }
  }
  if (left === -1) return [0, n]
  else return [left, n - right - 1]
}

void (function main() {
  let t = Number(inputs[0]),
    __ = 1,
    res = []
  for (let _ = 0; _ < t; _++) {
    const n = Number(inputs[__++])
    const a = inputs[__++].trim().split(' ').map(Number)
    const [l, r] = solve(n, a)
    res.push(`${l} ${r}`)
  }
  console.log(res.join('\n'))
})()

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

const _ = Number(inputs[0])

main(_, inputs)

function main(_, lines) {
  let res = []
  for (let i = 0; i < _; i++) {
    const n = Number(lines[i * 2 + 1])
    const data = lines[i * 2 + 2].split(' ').map(Number)
    const check = (l, r) => {
      if (l === r) return
      let product = 1,
        count = 0

      for (let i = l; i < r; i++) {
        product *= data[i]
        if (data[i] < 0) count++
      }
      if (count % 2 === 0) {
        if (ans < product) {
          ans = product
          x = l
          y = n - r
        }
        return
      }

      let left = -1
      product = 1
      for (let i = l; i < r; i++) {
        if (left !== -1) {
          product *= data[i]
        }
        if (data[i] < 0 && left === -1) {
          left = i
        }
      }
      if (ans < product) {
        ans = product
        x = left + 1
        y = n - r
      }
      let right = -1
      product = 1
      for (let i = r - 1; i >= l; i--) {
        if (right !== -1) {
          product *= data[i]
        }
        if (data[i] < 0 && right === -1) {
          right = i
        }
      }
      if (ans < product) {
        ans = product
        x = l
        y = n - right
      }
    }

    let x = n,
      y = 0,
      ans = 1
    for (let i = 0, j = 0; j <= n; j++) {
      if (j === n || data[j] === 0) {
        check(i, j)
        i = j + 1
      }
    }
    res.push([x, y])
  }

  console.log(res.map(arr => arr.join(' ')).join('\n'))
}

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

const _ = Number(inputs[0])

main(_, inputs)

function main(_, lines) {
  let res = []
  for (let i = 0; i < _; i++) {
    const n = Number(lines[i * 2 + 1])
    const data = lines[i * 2 + 2].split(' ').map(Number)
    const check = (l, r) => {
      if (l === r) return
      const products = []
      for (let i = l; i < r; i++) {
        products.push((products[products.length - 1] === undefined ? 1 : products[products.length - 1]) * data[i])
      }

      let pre = -1
      for (let i = 0; i < products.length; i++) {
        let max = products[i]
        if (max > 0 || pre === -1) {
          if (ans < max) {
            ans = max
            x = l
            y = n - 1 - (l + i)
          }
        } else {
          max = products[i] / products[pre]
          if (ans < max) {
            ans = max
            x = l + pre + 1
            y = n - 1 - (l + pre + i)
          }
        }

        if (max < 0 && pre === -1) {
          pre = i
        }
      }
    }

    let x = 0,
      y = 0,
      ans = -Infinity
    for (let i = 0, j = 0; j <= n; j++) {
      if (j === n || data[j] === 0) {
        check(i, j)
        i = j + 1
      }
    }
    res.push([x, y])
  }

  console.log(res.map(arr => arr.join(' ')).join('\n'))
}

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

const _ = Number(inputs[0])

main(_, inputs)

function main(_, lines) {
  let res = []
  for (let i = 0; i < _; i++) {
    const n = Number(lines[i * 2 + 1])
    const data = lines[i * 2 + 2].split(' ').map(Number)
    const check = (l, r) => {
      if (l === r) return
      const products = []
      for (let i = l; i < r; i++) {
        products.push((products[products.length - 1] === undefined ? 1 : products[products.length - 1]) * data[i])
      }

      let pre = -1
      for (let i = 0; i < products.length; i++) {
        let max = products[i]
        if (max > 0 || pre === -1) {
          if (ans < max) {
            ans = max
            x = l
            y = n - 1 - (l + i)
          }
        } else {
          max = products[i] / products[pre]
          if (ans < max) {
            ans = max
            x = l + pre + 1
            y = n - 1 - (l + pre + i)
          }
        }

        if (max < 0 && pre === -1) {
          pre = i
        }
      }
    }
    let x = 0,
      y = n,
      ans = 1
    for (let i = 0, j = 0; j <= n; j++) {
      if (j === n || data[j] === 0) {
        check(i, j)
        i = j + 1
      }
    }
    res.push([x, y])
  }

  console.log(res.map(arr => arr.join(' ')).join('\n'))
}

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

const _ = Number(inputs[0])

main(_, inputs)

function main(_, lines) {
  let res = []
  for (let i = 0; i < _; i++) {
    const n = Number(lines[i * 2 + 1])
    const data = lines[i * 2 + 2].split(' ').map(Number)
    const check = (l, r) => {
      if (l === r) return
      const products = []
      for (let i = l; i < r; i++) {
        products.push((products[products.length - 1] === undefined ? 1 : products[products.length - 1]) * data[i])
      }

      let pre = -1
      for (let i = 0; i < products.length; i++) {
        let max = products[i]
        if (max > 0 || pre === -1) {
          if (ans < max) {
            ans = max
            x = l
            y = n - 1 - (l + i)
          }
        } else {
          max = products[i] / products[pre]
          if (ans < max) {
            ans = max
            x = l + pre
            y = n - 1 - (l + pre + i)
          }
        }

        if (max < 0 && pre === -1) {
          pre = i
        }
      }
    }
    let x = 0,
      y = n,
      ans = 1
    for (let i = 0, j = 0; j <= n; j++) {
      if (j === n || data[j] === 0) {
        check(i, j)
        i = j + 1
      }
    }
    res.push([x, y])
  }

  console.log(res.map(arr => arr.join(' ')).join('\n'))
}

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

const _ = Number(inputs[0])

main(_, inputs)

function main(_, lines) {
  let res = []
  for (let i = 0; i < _; i++) {
    const n = Number(lines[i * 2 + 1])
    const data = lines[i * 2 + 2].split(' ').map(Number)
    const check = (l, r) => {
      if (l === r) return
      const products = []
      for (let i = l; i < r; i++) {
        products.push((products[products.length - 1] === undefined ? 1 : products[products.length - 1]) * data[i])
      }

      let pre = l
      for (let i = 0; i < products.length; i++) {
        let max = products[i]
        if (max > 0 || pre === -1) {
          if (ans < max) {
            ans = max
            x = l
            y = n - 1 - (l + i)
          }
        } else {
          max = products[i] / products[pre]
          if (ans < max) {
            ans = max
            x = pre + 1
            y = n - 1 - (pre + i)
          }
        }

        if (max < 0 && pre === -1) {
          pre = i
        }
      }
    }
    let x = 0,
      y = 0,
      ans = -Infinity
    for (let i = 0, j = 0; j <= n; j++) {
      if (j === n || data[j] === 0) {
        check(i, j)
        i = j + 1
      }
    }
    res.push([x, y])
  }

  console.log(res.map(arr => arr.join(' ')).join('\n'))
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		let ans, mx = 0;
		for (let round = 0; round < 2; round++) {
			let twos = 0, positive = 1, cnt = 0;
			for (let i = 0; i < n; i++) {
				if (a[i] == 0) cnt = 0, twos = 0; else cnt++;
				if (a[i] < 0) positive ^= 1;
				if (Math.abs(a[i]) == 2) twos++;
				if (positive & twos > mx) {
					mx = twos;
					ans = [(i + 1) - cnt, n - (i + 1)];
					if (round) ans.reverse();
				}
				//console.log({round, i, twos, positive, mx, cnt, ans});
			}
			a.reverse();
		}

		if (mx == 0) {
			console.log(n, 0);
		} else {
			console.log(ans.join(' '));
		}

	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		let ans, mx = 0;
		for (let round = 0; round < 2; round++) {
			let twos = 0, positive = 1, cnt = 0;
			for (let i = 0; i < n; i++) {
				if (a[i] == 0) cnt = 0, twos = 0; else cnt++;
				if (a[i] < 0) positive ^= 1;
				if (Math.abs(a[i]) == 2) {
					twos++;
					if (positive & twos > mx) {
						mx = twos;
						ans = [(i + 1) - cnt, n - (i + 1)];
						if (round) ans.reverse();
					}
					//console.log({round, i, twos, positive, mx, cnt, ans});
				}
			}
			a.reverse();
		}

		if (mx == 0) {
			console.log(n, 0);
		} else {
			console.log(ans.join(' '));
		}

	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		let mx = 1, l, r;
		for (let round = 0; round < 2; round++) {
			let prod = 0, left = 0;
			for (let i = 0; i < n; i++) {
				if (prod == 0) prod = 1;
				prod *= a[i];
				if (prod > mx) {
					mx = prod;
					if (round == 0) {
						l = left;
						r = i;
					} else {
						l = n - i - 1;
						r = n - left - 1;
					}
					//console.log({round, i, mx, l, r});
				}
				if (a[i] == 0) {
					left = i + 1;
				}
			}
			a.reverse();
		}
		//console.log({mx, l, r});

		if (mx == 1) {
			console.log(n, 0);
		} else {
			console.log(l, n - (r + 1));
		}
	}
}

const readline = require('readline')

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

function solve(n, nums) {
    let ans = [-1, 3 * n]
    let pos
    let neg
    let pp = -1, pn = -1
    let seg
    nums.forEach((x, i) => {
        if (i) {
            const [sp, vp] = pos
            const [sn, vn] = neg
            if (x > 0) {
                // pos *= x
                // neg *= x
                const pow = x === 1 ? 0 : 1
                pos = [1, vp + pow]
                neg = [sn, vn + pow]
                // ans = Math.max(ans, pos, neg)
                if (pp < 0) pp = i
                if (pn < 0) pn = i
                // if (pos > ans) {
                if (cmp(pos, ans) > 0) {
                    ans = pos
                    seg = [pp, i]
                }
            } else if (x < 0) {
                const pow = x === -1 ? 0 : 1
                if (neg[0] < 0) {
                    if (pp < 0) pp = i
                    if (pn < 0) pn = i
                    // ;[pos, neg] = [neg * x, pos * x]
                    pos = [-sn, vn + pow]
                    neg = [-sp, vp + pow]
                    ;[pp, pn] = [pn, pp]
                    // ans = Math.max(ans, pos, neg)
                    if (cmp(pos, ans) > 0) {
                        ans = pos
                        seg = [pp, i]
                    }
                    if (cmp(neg, ans) > 0) {
                        ans = neg
                        seg = [pn, i]
                    }
                } else {
                    if (pp < 0) pp = i
                    // ;[pos, neg] = [1, pos * x]
                    ;[pp, pn] = [-1, pp]
                    pos = [1, 0]
                    neg = [-1, vp + pow]
                    // ans = Math.max(ans, neg)
                    //
                    if (cmp(neg, ans) > 0) {
                        ans = neg
                        seg = [pn, i]
                    }
                }
            } else {
                // pos = 1
                // neg = 1
                pos = [1, 0]
                neg = [1, 0]
                pp = -1
                pn = -1
                // ans = Math.max(ans, 0)
                //
                if (cmp([1, -1], ans)) {
                    ans = [1, -1] // special 0
                    seg = [i, i]
                }
            }
        } else {
            if (x > 0) {
                // pos = x
                // neg = 1
                pos = [1, x === 1 ? 0 : 1] // pos, power
                neg = [1, 0]
                ans = pos
                pp = i
            } else if (x < 0) {
                // pos = 1
                // neg = x
                pos = [1, 0]
                neg = [-1, x === -1 ? 0 : 1]
                ans = neg
                pn = i
            } else {
                // pos = 1
                // neg = 1
                pos = [1, 0]
                neg = [1, 0]
                ans = [1, -1]
            }
            // ans = Math.max(ans, x)
            seg = [i, i]
        }
        // console.log(pos, neg, ans)
    })
// console.log(ans, seg)
// return
    const [a, b] = seg
    if (cmp(ans, [1, -1]) <= 0) return [0, n].join(' ')
    return [a, n - 1 - b].join(' ')
}
function cmp(a, b) {
    const [sa, va] = a
    const [sb, vb] = b
    if (sa > 0 && sb > 0) {
        return va - vb
    } else if (sa < 0 && sb < 0) {
        return vb - va
    } else if (sa > 0) {
        return 1
    } else {
        return -1
    }
}

const readline = require('readline')

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

function solve(n, nums) {
    let ans = -Infinity
    let pos
    let neg
    let pp = -1, pn = -1
    let seg
    nums.forEach((x, i) => {
        if (i) {
            if (x > 0) {
                pos *= x
                neg *= x
                // ans = Math.max(ans, pos, neg)
                if (pp < 0) pp = i
                if (pn < 0) pn = i
                if (pos > ans) {
                    ans = pos
                    seg = [pp, i]
                }
            } else if (x < 0) {
                if (neg < 0) {
                    if (pp < 0) pp = i
                    if (pn < 0) pn = i
                    ;[pos, neg] = [neg * x, pos * x]
                    ;[pp, pn] = [pn, pp]
                    ans = Math.max(ans, pos, neg)
                    //
                    if (pos === ans) {
                        seg = [pp, i]
                    } else if (neg === ans) {
                        seg = [pn, i]
                    }
                } else {
                    if (pp < 0) pp = i
                    ;[pos, neg] = [1, pos * x]
                    ;[pp, pn] = [-1, pp]
                    ans = Math.max(ans, neg)
                    //
                    if (neg === ans) {
                        seg = [pn, i]
                    }
                }
            } else {
                pos = 1
                neg = 1
                pp = -1
                pn = -1
                ans = Math.max(ans, 0)
                //
                if (ans === 0) {
                    seg = [i, i]
                }
            }
        } else {
            if (x > 0) {
                pos = x
                neg = 1
                pp = i
            } else if (x < 0) {
                pos = 1
                neg = x
                pn = i
            } else {
                pos = 1
                neg = 1
            }
            ans = Math.max(ans, x)
            seg = [i, i]
        }
        // console.log(pos, neg, ans)
    })
// console.log(ans, seg)
    const [a, b] = seg
    if (ans <= 0) return [0, n].join(' ')
    return [a, n - 1 - b].join(' ')
}


Once upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values $$$p_i$$$ — the index of the router to which the $$$i$$$-th router was connected after being purchased ($$$p_i < i$$$).There are $$$n$$$ routers in Boogle in total now. Print the sequence of routers on the path from the first to the $$$n$$$-th router.

The first line contains integer number $$$n$$$ ($$$2 \le n \le 200000$$$) — the number of the routers. The following line contains $$$n-1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$), where $$$p_i$$$ is equal to index of the router to which the $$$i$$$-th was connected after purchase.

Print the path from the $$$1$$$-st to the $$$n$$$-th router. It starts with $$$1$$$ and ends with $$$n$$$. All the elements in the path should be distinct.

var count = +readline(),
    routers = readline().split(' '),
    result = count;
for(var i = count - 2;i >= 0;) {
    var el = routers[i]
    result = el + ' ' + result;
    i = el - 2;
}
write(result);


Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan.There are $$$n$$$ cities in the republic, some of them are connected by $$$m$$$ directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary directed graph. Egor will arrive to the city $$$1$$$, travel to the city $$$n$$$ by roads along some path, give a concert and fly away.As any famous artist, Egor has lots of haters and too annoying fans, so he can travel only by safe roads. There are two types of the roads in Dagestan, black and white: black roads are safe at night only, and white roads — in the morning. Before the trip Egor's manager's going to make a schedule: for each city he'll specify it's color, black or white, and then if during the trip they visit some city, the only time they can leave it is determined by the city's color: night, if it's black, and morning, if it's white. After creating the schedule Egor chooses an available path from $$$1$$$ to $$$n$$$, and for security reasons it has to be the shortest possible.Egor's manager likes Dagestan very much and wants to stay here as long as possible, so he asks you to make such schedule that there would be no path from $$$1$$$ to $$$n$$$ or the shortest path's length would be greatest possible.A path is one city or a sequence of roads such that for every road (excluding the first one) the city this road goes from is equal to the city previous road goes into. Egor can move only along paths consisting of safe roads only. The path length is equal to the number of roads in it. The shortest path in a graph is a path with smallest length.

The first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 500000$$$, $$$0 \leq m \leq 500000$$$) — the number of cities and the number of roads. The $$$i$$$-th of next $$$m$$$ lines contains three integers — $$$u_i$$$, $$$v_i$$$ and $$$t_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$t_i \in \{0, 1\}$$$) — numbers of cities connected by road and its type, respectively ($$$0$$$ — night road, $$$1$$$ — morning road).

In the first line output the length of the desired path (or $$$-1$$$, if it's possible to choose such schedule that there's no path from $$$1$$$ to $$$n$$$). In the second line output the desired schedule — a string of $$$n$$$ digits, where $$$i$$$-th digit is $$$0$$$, if the $$$i$$$-th city is a night one, and $$$1$$$ if it's a morning one. If there are multiple answers, print any.

NoteFor the first sample, if we paint city $$$1$$$ white, the shortest path is $$$1 \rightarrow 3$$$. Otherwise, it's $$$1 \rightarrow 2 \rightarrow 3$$$ regardless of other cities' colors.For the second sample, we should paint city $$$3$$$ black, and there are both black and white roads going from $$$2$$$ to $$$4$$$. Note that there can be a road connecting a city with itself.

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

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

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

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

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

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

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

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

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let [n, m] = $(2), back = Arr(n, i => [])
  For(m, i => {
    let [u, v, w] = $(3)
    back[v - 1].push({ u: u - 1, w })
  })
  let ra = Arr(n, i => 2), ral = Arr(n, i => -1);
  ral[n - 1] = 0;
  let q = [n - 1];
  while (q.length) {
    let v = q.shift()
    back[v].forEach(({ u, w }) => {
      if (ra[u] != w) ra[u] = 1 - w;
      else {
        if (ral[u] == -1) {
          ral[u] = ral[v] + 1
          q.push(u)
        }
      }
    })
  }
  log(ral[0])
  log(ra.map(v => v != 2 ? v : 1).join(''))
}

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

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

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

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

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

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

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

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

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let [n, m] = $(2), back = Arr(n, i => [])
  For(m, i => {
    let [u, v, w] = $(3)
    back[v - 1].push({ u: u - 1, w })
  })
  let ra = Arr(n, i => 2), ral = Arr(n, i => -1);
  ral[-1] = 0;
  let q = [n - 1];
  while (q.length) {
    let v = q.shift()
    back[v].forEach(({ u, w }) => {
      if (ra[u] != w) ra[u] = 1 - w;
      else {
        if (ral[u] == -1) {
          ral[u] = ral[v] + 1
          q.push(u)
        }
      }
    })
  }
  log(ral[0] < 0 && n > 1 ? -1 : ral[0] + 1)
  log(ra.map(v => v != 2 ? v : 1).join(''))
}

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

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

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

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

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

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

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

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

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let [n, m] = $(2), back = Arr(n, i => [])
  For(m, i => {
    let [u, v, w] = $(3)
    back[v - 1].push({ u: u - 1, w })
  })
  let ra = Arr(n, i => 2), ral = Arr(n, i => -1);
  ral[-1] = 0;
  let q = [n - 1];
  while (q.length) {
    let v = q.shift()
    back[v].forEach(({ u, w }) => {
      if (ra[u] != w) ra[u] = 1 - w;
      else {
        if (ral[u] == -1) {
          ral[u] = ral[v] + 1
          q.push(u)
        }
      }
    })
  }
  log(ral[0] < 0 ? -1 : ral[0] + 1)
  log(ra.map(v => v != 2 ? v : 1).join(''))
}

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

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

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

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

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

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

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

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

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let [n, m] = $(2), back = Arr(n, i => [])
  For(m, i => {
    let [u, v, w] = $(3)
    back[v - 1].push({ u: u - 1, w })
  })
  let ra = Arr(n, i => 2), ral = Arr(n, i => -1);
  ral[-1] = 0;
  let q = [n - 1];
  while (q.length) {
    let v = q.shift()
    back[v].forEach(({ u, w }) => {
      if (ra[u] != w) ra[u] = 1 - w;
      else {
        if (ral[u] == -1) {
          ral[u] = ral[v] + 1
          q.push(u)
        }
      }
    })
  }
  log(ral[0] + 1)
  log(ra.map(v => v != 2 ? v : 1).join(''))
}