A class of students got bored wearing the same pair of shoes every day, so they decided to shuffle their shoes among themselves. In this problem, a pair of shoes is inseparable and is considered as a single object.There are $$$n$$$ students in the class, and you are given an array $$$s$$$ in non-decreasing order, where $$$s_i$$$ is the shoe size of the $$$i$$$-th student. A shuffling of shoes is valid only if no student gets their own shoes and if every student gets shoes of size greater than or equal to their size. You have to output a permutation $$$p$$$ of $$$\{1,2,\ldots,n\}$$$ denoting a valid shuffling of shoes, where the $$$i$$$-th student gets the shoes of the $$$p_i$$$-th student ($$$p_i \ne i$$$). And output $$$-1$$$ if a valid shuffling does not exist.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq10^5$$$) — the number of students. The second line of each test case contains $$$n$$$ integers $$$s_1, s_2,\ldots,s_n$$$ ($$$1\leq s_i\leq10^9$$$, and for all $$$1\le i<n$$$, $$$s_i\le s_{i+1}$$$) — the shoe sizes of the students. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print the answer in a single line using the following format. If a valid shuffling does not exist, print the number $$$-1$$$ as the answer. If a valid shuffling exists, print $$$n$$$ space-separated integers — a permutation $$$p$$$ of $$$1,2,\ldots,n$$$ denoting a valid shuffling of shoes where the $$$i$$$-th student gets the shoes of the $$$p_i$$$-th student. If there are multiple answers, then print any of them.

NoteIn the first test case, any permutation $$$p$$$ of $$$1,\ldots,n$$$ where $$$p_i\ne i$$$ would represent a valid shuffling since all students have equal shoe sizes, and thus anyone can wear anyone's shoes.In the second test case, it can be shown that no valid shuffling is possible.

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = CALC(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

const lines = [];
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;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`\nTest #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

tests = [
``, // Test #1
``, // Test #2
``, // Test #3
``, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const CALC = (testN)=>{
  // READING:
  let [n] = ra();
  let A = ra();
  LT({n, A});
  // PROCESSING:
  if (n==1)
    return -1;
  let r = n-1;
  let perm = [];
  while (r>=0){
    let l = r;
    while (A[l-1]==A[r])
      l--;
    if (l==r)
      return -1;
    perm.push(l+1);
    for (let i=r; i>l; i--){
      perm.push(i+1);
    }
    r = l-1;
  }
  return perm.reverse();
};

function solve() {
   read();
   const a = readArray(Number);
   a.push(-1);
   const ans = [];
   let startIndex = 0;
   for (let i = 1; i < a.length; i++) {
      if (a[i] === a[startIndex]) {
         ans.push(i + 1);
         continue;
      }
      if (i === startIndex + 1) {
         write(-1);
         return;
      }
      ans.push(startIndex + 1);
      startIndex = i;
   }
   write(ans.join(' '));
}

function init() {
   try {
      var T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

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

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

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

   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

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

'use strict';

function solve(n, a) {
  let map = new Map();
  for (let i = 0; i < n; i++) {
    const num = a[i];
    if (!map.has(num)) map.set(num, []);
    map.get(num).push(i);
  }
  let res = [];
  for (let [, arr] of map) {
    if (arr.length === 1) return -1;
    const N = arr.length;
    for (let i = 0; i < N; i++) {
      const j = arr[i];
      res[j] = arr[(i + 1) % N];
    }
  }
  return res.map(num => num + 1).join(' ');
}

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

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

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = CALC(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

const lines = [];
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;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`\nTest #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

tests = [
``, // Test #1
``, // Test #2
``, // Test #3
``, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const CALC = (testN)=>{
  // READING:
  let [n] = ra();
  let A = ra();
  LT({n, A});
  // PROCESSING:
  if (n==1)
    return -1;
  let r = n-1;
  let perm = [];
  while (r>0){
    let l = r;
    while (A[l-1]==A[r])
      l--;
    if (l==r)
      return -1;
    perm.push(l+1);
    for (let i=r; i>l; i--){
      perm.push(i+1);
    }
    r = l-1;
  }
  return perm.reverse();
};

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = CALC(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

const lines = [];
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;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`\nTest #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

tests = [
``, // Test #1
``, // Test #2
``, // Test #3
``, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const CALC = (testN)=>{
  // READING:
  let [n] = ra();
  let A = ra();
  LT({n, A});
  // PROCESSING:
  if (n==1)
    return -1;
  let r = n-1;
  let perm = [];
  while (r>0){
    let l = r;
    while (A[l-1]==A[r])
      l--;
    if (l==r)
      return -1;
    perm.push(l+1);
    for (let i=l; i<r; i++){
      perm.push(i+2);
    }
    r = l-1;
  }
  return perm.reverse();
};


Mahmoud wrote a message s of length n. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number i in the English alphabet to be written on it in a string of length more than ai. For example, if a1 = 2 he can't write character 'a' on this paper in a string of length 3 or more. String "aa" is allowed while string "aaa" is not.Mahmoud decided to split the message into some non-empty substrings so that he can write every substring on an independent magical paper and fulfill the condition. The sum of their lengths should be n and they shouldn't overlap. For example, if a1 = 2 and he wants to send string "aaa", he can split it into "a" and "aa" and use 2 magical papers, or into "a", "a" and "a" and use 3 magical papers. He can't split it into "aa" and "aa" because the sum of their lengths is greater than n. He can split the message into single string if it fulfills the conditions.A substring of string s is a string that consists of some consecutive characters from string s, strings "ab", "abc" and "b" are substrings of string "abc", while strings "acb" and "ac" are not. Any string is a substring of itself.While Mahmoud was thinking of how to split the message, Ehab told him that there are many ways to split it. After that Mahmoud asked you three questions:   How many ways are there to split the string into substrings such that every substring fulfills the condition of the magical paper, the sum of their lengths is n and they don't overlap? Compute the answer modulo 109 + 7.  What is the maximum length of a substring that can appear in some valid splitting?  What is the minimum number of substrings the message can be spit in? Two ways are considered different, if the sets of split positions differ. For example, splitting "aa|a" and "a|aa" are considered different splittings of message "aaa".

The first line contains an integer n (1 ≤ n ≤ 103) denoting the length of the message. The second line contains the message s of length n that consists of lowercase English letters. The third line contains 26 integers a1, a2, ..., a26 (1 ≤ ax ≤ 103) — the maximum lengths of substring each letter can appear in.

Print three lines. In the first line print the number of ways to split the message into substrings and fulfill the conditions mentioned in the problem modulo 109  +  7. In the second line print the length of the longest substring over all the ways. In the third line print the minimum number of substrings over all the ways.

NoteIn the first example the three ways to split the message are:   a|a|b  aa|b  a|ab The longest substrings are "aa" and "ab" of length 2.The minimum number of substrings is 2 in "a|ab" or "aa|b".Notice that "aab" is not a possible splitting because the letter 'a' appears in a substring of length 3, while a1 = 2.

var NextChar = function(c){return String.fromCharCode(c.charCodeAt(0)+1)}
var Sms = []; var MinLine = []; var Method = [];  var MaxLen=0;
var n=readline(); var s=readline();
var temp = readline().split(' ').map(Number);
for(var ch='a'; ch<='z';  ch=NextChar(ch)) Sms[ch]=temp[ch.charCodeAt(0)-97];
for (var i=0; i<n; i++) {MinLine[i]= Infinity; Method[i]=0;}
Method[-1]=1; MinLine[-1]= 0;
for (var i=0; i<n; i++) {
    var l = Infinity;
    for(var j=i; j>=0; j--){
        l=Math.min(l, Sms[s[j]]);
        if (i-j+1<=l){
            Method[i]=(Method[i]+Method[j-1]) % 1000000007;
            MaxLen=Math.max(MaxLen,i-j+1);
            MinLine[i]=Math.min(MinLine[i],MinLine[j-1]+1);
        }
        else break;
    }
}
print(Method[n-1]+'\n'+MaxLen+'\n'+MinLine[n-1]);


Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.The world can be represented by the first quadrant of a plane and the wall is built along the identity line (i.e. the line with the equation x = y). Any point below the wall belongs to the first kingdom while any point above the wall belongs to the second kingdom. There is a gate at any integer point on the line (i.e. at points (0, 0), (1, 1), (2, 2), ...). The wall and the gates do not belong to any of the kingdoms. Fafa is at the gate at position (0, 0) and he wants to walk around in the two kingdoms. He knows the sequence S of moves he will do. This sequence is a string where each character represents a move. The two possible moves Fafa will do are 'U' (move one step up, from (x, y) to (x, y + 1)) and 'R' (move one step right, from (x, y) to (x + 1, y)). Fafa wants to know the number of silver coins he needs to pay to walk around the two kingdoms following the sequence S. Note that if Fafa visits a gate without moving from one kingdom to another, he pays no silver coins. Also assume that he doesn't pay at the gate at point (0, 0), i. e. he is initially on the side he needs.

The first line of the input contains single integer n (1 ≤ n ≤ 105) — the number of moves in the walking sequence. The second line contains a string S of length n consisting of the characters 'U' and 'R' describing the required moves. Fafa will follow the sequence S in order from left to right.

On a single line, print one integer representing the number of silver coins Fafa needs to pay at the gates to follow the sequence S.

NoteThe figure below describes the third sample. The red arrows represent the sequence of moves Fafa will follow. The green gates represent the gates at which Fafa have to pay silver coins.

let _inputLines;
let _lineNumber = 0;
let inputReader = _inputReader ();

function _main() {

	_inputLines = _inputData.trim().split('\n').map((string) => {
		return string.trim();
	});;
	let n = inputReader.readNumber();

	let str = inputReader.readLine();
	let i =0;
	let count = 0,x=0,y=0;
	while(i<str.length){
		if(str[i]=='U')
			y++;
		else
			x++;
		if(x===y){
			if(str[i]==str[i+1])
				count++;
		}
		i++;
	}
	console.log(count);

}

var _inputData = '';
function cacheInput(data) {
	_inputData += data;
}

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', cacheInput).on('end', _main);

function _inputReader () {
	function readNumber(){
		return Number(_inputLines[_lineNumber++]);
	}

	function readLine(){
		return _inputLines[_lineNumber++];
	}

	return {
		readNumber,
		readLine,
	}
}

n=+readline()
x=0
y=0
s=readline()
res=0
for (i=0;i<n;i++)
{
    if (s[i]=='R')
        ++x
    else
        ++y
    if (x==y&&i&&i<n-1&&s[i]==s[i+1])
        ++res
}
print(res)

readline();
var silverSpent = 0;
var currentKingdom;
var currPos = {x: 0, y: 0};
var moves = readline().split('');

function calcCurrentKingdom() {
  if (currPos.x > currPos.y) {
    return 'upperKingdom';
  } else if (currPos.y > currPos.x) {
    return 'lowerKingdom';
  }
}

function checkForChanges() {
  var kingdomAfterMove = calcCurrentKingdom();
  if (kingdomAfterMove && kingdomAfterMove !== currentKingdom) {
    if (currentKingdom) {
      silverSpent++;
    }
    currentKingdom = kingdomAfterMove;
  }
}

function goUp() {
  currPos.y++;
  checkForChanges();
}

function goRight() {
  currPos.x++;
  checkForChanges();
}

function makeTheMove(direction) {
  direction === 'U' ? goUp() : goRight();
}

moves.forEach(e => makeTheMove(e));

print(silverSpent);

var a = Number(readline());
var b = readline().split('');

var loc = {x:0, y:0};
var coins = 0;

for(var i = 0; i < a; i++){
	if(b[i] === 'R'){
		loc.x+=1;
	} else if (b[i] ==='U'){
		loc.y+=1;
	}
	if(loc.x === loc.y){
		if(b[i] === b[i+1]){
			coins++;
		}
	}
}

print(coins);

inputs = readline();
moves = parseInt(inputs);
movelist = readline();
// print(moves+" "+movelist)

var pos = {
    x:0,
    y:0,
    onGate: false,
    sides:"",
    goUp:()=>{
        pos.isOnGate();
        pos.y = pos.y+1;
        if(pos.onGate && pos.sides === "right"){
            pos.sides = "left"
            return 1;
        } else {
            return 0;
        }
    },
    goRight: ()=>{
        pos.isOnGate();
        pos.x = pos.x+1;
         if(pos.onGate && pos.sides === "left"){
             pos.sides = "right"
            return 1;
        } else {
            return 0;
        }
    },
    isOnGate:()=>{
        if(pos.x === pos.y && pos.x != 0){
            pos.onGate = true;
        }else{
            pos.onGate = false;
        }
    }
}

var cost = 0;
if(movelist[0] === "R"){
    pos.sides = "right";
    pos.goRight();
} else {
    pos.sides = "left";
    pos.goUp()
}
for(move = 1; move < moves; move++){
    if(movelist[move] === "R"){
        cost += pos.goRight();
    }else if(movelist[move] === "U"){
        cost += pos.goUp();
    }
    // print(pos.x+":"+pos.y +" ("+cost+")" )
}
print(cost);

n = readline();
str = readline().split('');

var x = 0, y = 0, side = 'UP', count = 0;

if (str[0] == 'R') {
	side = 'DOWN';
};

for (var i = 0; i < n; i++) {
	if (str[i] == 'U') {
		y++;
	} else if (str[i] == 'R') {
		x++;
	};

	if (side == 'DOWN' && y == x + 1) {
		count++;
		side = 'UP';
	} else if (side == 'UP' && x == y + 1) {
		count++;
		side = 'DOWN';
	};
};

print(count);

var a = Number(readline());
var b = readline().split('');

var loc = {x:0, y:0};
var coins = 0;

b.forEach(e=>{
	if(e === 'R'){
		loc.x+=1;
	} else if (e==='U'){
		loc.y+=1;
	}
	if(loc.x === loc.y){
		coins++;
	}
});
print(coins);


You play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice.The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked.Let's number the rows with integers from 1 to n from top to bottom and the columns with integers from 1 to m from left to right. Let's denote a cell on the intersection of the r-th row and the c-th column as (r, c). You are staying in the cell (r1, c1) and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell (r2, c2) since the exit to the next level is there. Can you do this?

The first line contains two integers, n and m (1 ≤ n, m ≤ 500) — the number of rows and columns in the cave description. Each of the next n lines describes the initial state of the level of the cave, each line consists of m characters "." (that is, intact ice) and "X" (cracked ice). The next line contains two integers, r1 and c1 (1 ≤ r1 ≤ n, 1 ≤ c1 ≤ m) — your initial coordinates. It is guaranteed that the description of the cave contains character 'X' in cell (r1, c1), that is, the ice on the starting cell is initially cracked. The next line contains two integers r2 and c2 (1 ≤ r2 ≤ n, 1 ≤ c2 ≤ m) — the coordinates of the cell through which you need to fall. The final cell may coincide with the starting one.

If you can reach the destination, print 'YES', otherwise print 'NO'.

NoteIn the first sample test one possible path is:After the first visit of cell (2, 2) the ice on it cracks and when you step there for the second time, your character falls through the ice as intended.

function toi(x){return parseInt(x);}
function dfs(){
    while(queue.length!=0){
	var now=queue.shift();
	for(var i=0;i<4;i++){
	    nexti=now[0]+di[i];
	    nextj=now[1]+dj[i];
	    if(0<=nexti&&nexti<n&&0<=nextj&&nextj<m){
		if(cave[nexti][nextj]=="X"){
		    if(nexti==e[0]&&nextj==e[1]){
			return true;
		    }else{
			continue;
		    }
		}else{
		    cave[nexti][nextj]="X";
		    queue.push([nexti,nextj]);
		}
	    }
	}
    }
    return false;
}

var di=[-1,0,1,0];
var dj=[0,-1,0,1];
var i0=readline().split(" ").map(toi);
var n=i0[0];
var m=i0[1];
var cave=[];
for(var i=0;i<n;i++){
    cave.push(readline().split(""));
}
var s=readline().split(" ").map(toi);
s=[s[0]-1,s[1]-1];
var e=readline().split(" ").map(toi);
e=[e[0]-1,e[1]-1];
var queue=[];
queue.push(s);
print(dfs()?"YES":"NO");


Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xi ≠ yi).In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(n - 1) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.

The first line contains a single integer n (2 ≤ n ≤ 105) — the number of teams. Next n lines contain the description of the teams. The i-th line contains two space-separated numbers xi, yi (1 ≤ xi, yi ≤ 105; xi ≠ yi) — the color numbers for the home and away kits of the i-th team.

For each team, print on a single line two space-separated integers — the number of games this team is going to play in home and away kits, correspondingly. Print the answers for the teams in the order they appeared in the input.

;(function () {
	print(function (n) {
		var a = [], m = {}, l = 2 * n - 2;

		for (var i = 0; i < n; i++) {
			s = readline().split(' ').map(Number);
			a.push(s); s = s[0];
			m[s] = m[s] ? m[s] + 1 : 1;
		}

		return a.map(function (e) {
			e = n - 1 + (m[e[1]] || 0 );
			return [e, l - e].join(' ');
		}).join('\n');
	}(+readline()));
}.call(this));

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

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

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

function main() {
	var teamNum = parseInt(readline());
	function makeHash() {
		var hash = {};
		hash.increment = function(key) {
			if (this[key] === undefined) {
				this[key] = 1;
			} else {
				this[key] += 1;
			}
		};
		hash.get = function(key) {
			return this[key] || 0;
		}
		return hash;
	}
	var homeCount = makeHash(), awayCount = makeHash(),
		teams = [];
	for (var i = 0; i < teamNum; ++i) {
		var data = tokenizeIntegers(readline()),
			home = data[0], away = data[1];
		homeCount.increment(home);
		awayCount.increment(away);
		teams.push({ home: home, away: away });
	}
	for (var i = 0; i < teamNum; ++i) {
		var team = teams[i],
			conflict = homeCount.get(team.away);
		print(teamNum-1+conflict, teamNum-1-conflict);
	}
}

main();

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

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

function sortNumber(a, b) {
    return a - b;
}

function main() {
    var cX = [];
    var arrY = [];
    var n = nextInt();
    for (var i = 0; i < n; i++) {
        var x = nextInt();
        var y = nextInt();
        arrY[i] = y;
        if (typeof (cX[x]) == 'undefined') {
            cX[x] = 1;
        } else {
            cX[x]++;
        }
    }
    for (var i = 0; i < n; i++) {
        var same = cX[arrY[i]]||0;
        print((n - 1 + same) + " " + (n - 1 - same));
    }
}

main();

function main() {

    var teamNum = readline().split(' ');

    function makeObj () {
         var hash = {};

         hash.add = function (key) {
             if(this[key] === undefined) {
                 this[key] = 1;
             }else {
                 this[key] +=1;
             }
         }

        hash.get = function (key) {
            return this[key] || 0;
        }

        return hash;

    }

    var homeCount = makeObj(), teams = [];

     for(var i =0; i < teamNum; i++){
         var colors = readline().split(' ');
         var home = colors[0];
         var away = colors[1];
         homeCount.add(home);

         teams.push({home : home, away : away})
     }

    for(var i=0; i < teamNum; i++) {
       var team=teams[i],
           confilct = homeCount.get(team.away);

        print(teamNum - 1 + confilct, teamNum - 1- confilct) ;
    }

}

main();

function main() {

    var teamNum = readline().split(' ');

    var teams = [];
    function makeObj () {
         var hash = {};

         hash.add = function (key) {
             if(this[key] === undefined) {
                 this[key] = 1;
             }else {
                 this[key] +=1;
             }
         }

        hash.get = function (key) {
            return this[key] || 0;
        }

        return hash;

    }

    var homeCount = makeObj(), awayCount = makeObj(),teams = [];

     for(var i =0; i < teamNum; i++){
         var colors = readline().split(' ');
         var home = colors[0];
         var away = colors[1];
         homeCount.add(home);
         awayCount.add(away);
         teams.push({home : home, away : away})
     }

    for(var i=0; i < teamNum; i++) {
       var team=teams[i],
           confilct = homeCount.get(team.away);

        print(teamNum - 1 + confilct, teamNum - 1- confilct) ;
    }

}

main();

var n = parseInt(readline());
function trav(n, cb) {
  var i;
  for (i = 1; i <= n; i ++) {
    cb(i);
  }
}
function createZeroFilledArray() {
  return Array.apply( void 0, Array( 1e5 + 1 ) ).map(Number.prototype.valueOf, 0);
}

var recX = createZeroFilledArray(),
    recY = createZeroFilledArray(),
    totX = createZeroFilledArray();

trav(n, function(cur) {
  recX[cur] = readline().split(" ");
  recY[cur] = parseInt(recX[cur][1], 10);
  recX[cur] = parseInt(recX[cur][0], 10);
  totX[ recX[cur] ] ++;
});

trav(n, function(cur) {
  var resX = (n - 1) + totX[ recY[cur] ],
    resY = 2 * (n - 1) - resX;
  print(resX, resY);
});


You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x < n$$$ and $$$1 \le y < m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 50$$$). Then $$$n$$$ lines follow, each containing $$$m$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line is $$$A_{i, j}$$$. Each integer is either $$$0$$$ or $$$1$$$.

If it is impossible to make $$$B$$$ equal to $$$A$$$, print one integer $$$-1$$$. Otherwise, print any sequence of operations that transforms $$$B$$$ into $$$A$$$ in the following format: the first line should contain one integer $$$k$$$ — the number of operations, and then $$$k$$$ lines should follow, each line containing two integers $$$x$$$ and $$$y$$$ for the corresponding operation (set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$). The condition $$$0 \le k \le 2500$$$ should hold.

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, m, resultArr = [];
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    m = parseInt(resOne[1]);
  } else {
    resultArr.push(line.trim().split(' ').map((item) => parseInt(item)));
  }
  if (lineCount === n) {
    console.log(squareFilling(n, m, resultArr))
    rl.close();
  }
  lineCount ++;
});

// let n = 3;
// let m = 3;

// let resultArray = [
//     [1,1,1],
//     [1,1,1],
//     [0,1,1]
// ];
// let resultArray = [
//   [1,0,1],
//   [1,0,1],
//   [0,0,0]
// ];
// let resultArray = [
//   [0,0],
//   [0,0],
//   [0,0]
// ];

// console.log(squareFilling(n, m, resultArray));

function squareFilling (n, m, resultArray) {
  let operateCount = 0;
  let operateSelect = [];
  let x = 0;
  let y = 0;

  function getSquare (x, y) {
    try {
      return {
        topLeft: resultArray[x][y],
        topRight: resultArray[x + 1][y],
        bottomLeft: resultArray[x][y + 1],
        bottomRight: resultArray[x + 1][y + 1]
      }
    } catch (e) {
      return null
    }

  }

  function isConform (x, y) {
    let square = getSquare(x, y)
    if (!square) {
      return false
    }
    let { topLeft, topRight, bottomLeft, bottomRight } = square;
    return (topLeft * topRight * bottomLeft * bottomRight === 1);
  }

  while (x < n) {
    if (isConform(x, y)) {
      operateCount+=1;
      operateSelect.push([x + 1,y + 1]);
    } else if (resultArray[x][y] === 1) {
      // 看周围有没有可以满足的，如果没有，return -1
      if (!isConform(x-1, y-1) && !isConform(x, y-1) && !isConform(x-1, y)) {
        return -1;
      }
    }
    // 从0 开始，也就是偶数开始
    if (x % 2 === 0) {
      // 偶数 向右
      y+=1;
      if (y === m) {
        x += 1;
      }
    } else {
      // 奇数 向左
      y-=1;
      if (y === -1) {
        x += 1;
      }
    }
  }
  if (!operateSelect.length) {
    return 0;
  }
  let resStr = `${operateCount}\n`
  let resArr = []
  operateSelect.forEach((item) => {
    resArr.push(item.join(' '))
  });
  return resStr + resArr.join('\n');
}

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {"use strict";
    // TODO
    var input = rdArN();
    var n = input[0];
    var m = input[1];
    var A = [];
    for (var i = 0; i < n; ++i) {
        A.push(rdArN());
    }
    var dx = [0,1,0,1];
    var dy = [0,0,1,1];
    var check = function(x, y) {
        var f = true;
        for (var k = 0; k < 4; ++k) {
            f = f && (A[x + dx[k]][y + dy[k]] > 0);
        }
        return f;
    };
    var fill = function (x, y) {
        for (var k = 0; k < 4; ++k) {
            A[x + dx[k]][y + dy[k]] = 2;
        }
    };
    var fillOrder = []
    for (var i = 0; i < n-1; ++i) {
        for (var j = 0; j < m-1; ++j) {
            if (check(i, j)) {
                fill(i, j);
                fillOrder.push([i+1, j+1]);
            }
        }
    }
    var isFilled = true;
    for (var i = 0; i < n; ++i) {
        for (var j = 0; j < m; ++j) {
            if (A[i][j] === 1) {
                isFilled = false;
            }
        }
    }
    if (isFilled) {
        pr(fillOrder.length);
        for (var i = 0; i < fillOrder.length; ++i) {
            prAr(fillOrder[i]);
        }
    } else {
        pr(-1);
    }
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
getPrimeFactors=function(n){var primes=getPrimes(Math.floor(Math.sqrt(n))),last=primes.push(n)-1,factors=[],i,p;for(i=0,p=primes[0];primes[last]>1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});

main();
return OUTPUT;
})();

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, m, resultArr = [];
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    m = parseInt(resOne[1]);
  } else {
    resultArr.push(line.trim().split(' ').map((item) => parseInt(item)));
  }
  if (lineCount === n) {
    console.log(squareFilling(n, m, resultArr))
    rl.close();
  }
  lineCount ++;
});

return

// let n = 3;
// let m = 2;

// let resultArray = [
//     [1,1,1],
//     [1,1,1],
//     [0,1,1]
// ];
// let resultArray = [
//   [1,0,1],
//   [1,0,1],
//   [0,0,0]
// ];
// let resultArray = [
//   [0,0],
//   [0,0],
//   [0,0]
// ];

function squareFilling (n, m, resultArray) {
  let operateCount = 0;
  let operateSelect = [];
  let x = 0;
  let y = 0;
  let hasOne = false;

  function isConform(x, y) {
    let topLeft = resultArray[x][y];
    let topRight = resultArray[x + 1][y];
    let bottomLeft = resultArray[x][y + 1];
    let bottomRight = resultArray[x + 1][y + 1];

    if (!hasOne && (topLeft === 1 || topRight === 1 || bottomLeft === 1 || bottomRight === 1)) {
      hasOne = true;
    }

    return (topLeft === 1 && topRight === 1 && bottomLeft === 1 && bottomRight === 1)
  }

  let operateIndex = 0;
// 变成一个方阵之后的总长度
  let len = (n -1) * (m - 1);

  while (operateIndex < len) {
    if (isConform(x, y)) {
      operateCount+=1;
      operateSelect.push([x + 1,y + 1]);
    }

    let curIdx = Math.floor((operateIndex + 1)/n);

    // 从0 开始，也就是偶数开始
    if (curIdx % 2 === 0) {
      // 偶数 向下
      x+=1;
      if (x === (n - 1)) {
        x -=1;
        y += 1;
      }
    } else {
      // 奇数 向上
      x-=1;
    }
    operateIndex++;
  }
  if (!operateSelect.length) {
    if (hasOne) {
      return '';
    }
    return - 1;
  }
  let resStr = `${operateCount}\n`
  operateSelect.forEach((item, idx) => {
    resStr += `${item[0]} ${item[1]}` + ((idx < operateSelect.length - 1) ? '\n' : '')
  });
  return resStr;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, m, resultArr = [];
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    m = parseInt(resOne[1]);
  } else {
    resultArr.push(line.trim().split(' ').map((item) => parseInt(item)));
  }
  if (lineCount === n) {
    console.log(squareFilling(n, m, resultArr))
    rl.close();
  }
  lineCount ++;
});

return

// let n = 3;
// let m = 2;

// let resultArray = [
//     [1,1,1],
//     [1,1,1],
//     [0,1,1]
// ];
// let resultArray = [
//   [1,0,1],
//   [1,0,1],
//   [0,0,0]
// ];
// let resultArray = [
//   [0,0],
//   [0,0],
//   [0,0]
// ];

function squareFilling (n, m, resultArray) {
  let operateCount = 0;
  let operateSelect = [];
  let x = 0;
  let y = 0;

  function isConform(x, y) {
    let topLeft = resultArray[x][y];
    let topRight = resultArray[x + 1][y];
    let bottomLeft = resultArray[x][y + 1];
    let bottomRight = resultArray[x + 1][y + 1];

    return (topLeft === 1 && topRight === 1 && bottomLeft === 1 && bottomRight === 1)
  }

  let operateIndex = 0;
// 变成一个方阵之后的总长度
  let len = (n -1) * (m - 1);

  while (operateIndex < len) {
    if (isConform(x, y)) {
      operateCount+=1;
      operateSelect.push([x + 1,y + 1]);
    }

    let curIdx = Math.floor((operateIndex + 1)/n);

    // 从0 开始，也就是偶数开始
    if (curIdx % 2 === 0) {
      // 偶数 向下
      x+=1;
      if (x === (n - 1)) {
        x -=1;
        y += 1;
      }
    } else {
      // 奇数 向上
      x-=1;
    }
    operateIndex++;
  }
  if (!operateSelect.length) {
    return - 1;
  }
  let resStr = `${operateCount}\n`
  operateSelect.forEach((item, idx) => {
    resStr += `${item[0]} ${item[1]}` + ((idx < operateSelect.length - 1) ? '\n' : '')
  });
  return resStr;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, m, resultArr = [];
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    m = parseInt(resOne[1]);
  } else {
    resultArr.push(line.trim().split(' ').map((item) => parseInt(item)));
  }
  if (lineCount === n) {
    console.log(squareFilling(n, m, resultArr))
    rl.close();
  }
  lineCount ++;
});

// let n = 3;
// let m = 3;

// let resultArray = [
//     [1,1,1],
//     [1,1,1],
//     [0,1,1]
// ];
// let resultArray = [
//   [1,0,1],
//   [1,0,1],
//   [0,0,0]
// ];
// let resultArray = [
//   [0,0],
//   [0,0],
//   [0,0]
// ];

// console.log(squareFilling(n, m, resultArray));

function squareFilling (n, m, resultArray) {
  let operateCount = 0;
  let operateSelect = [];
  let x = 0;
  let y = 0;
  let hasOne = false;

  function getSquare (x, y) {
    return {
      topLeft: resultArray[x][y],
      topRight: resultArray[x + 1][y],
      bottomLeft: resultArray[x][y + 1],
      bottomRight: resultArray[x + 1][y + 1]
    }
  }

  function isConform (x, y) {
    let { topLeft, topRight, bottomLeft, bottomRight } = getSquare(x, y);

    if (!hasOne && (topLeft === 1 || topRight === 1 || bottomLeft === 1 || bottomRight === 1)) {
      hasOne = true;
    }

    return (topLeft * topRight * bottomLeft * bottomRight !== 0);
  }

  while (x < n - 1) {
    if (
      x < n -1
      && x > 0
      && y > 0
      && y < m -1
      && resultArray[x][y] == 1
      && !isConform(x, y-1)
      && !isConform(x-1, y-1)
      && !isConform(x-1, y)
    ) {
      // 孤点
      return -1;
    }
    if (isConform(x, y)) {
      operateCount+=1;
      operateSelect.push([x + 1,y + 1]);
    }

    // 从0 开始，也就是偶数开始
    if (x % 2 === 0) {
      // 偶数 向右
      y+=1;
      if (y === (m - 1)) {
        y -=1;
        x += 1;
      }
    } else {
      // 奇数 向左
      y-=1;
      if (y === -1) {
        y = 0;
        x += 1;
      }
    }
  }
  if (!operateSelect.length) {
    if (hasOne) {
      return -1;
    }
    return 0;
  }
  let resStr = `${operateCount}\n`
  let resArr = []
  operateSelect.forEach((item) => {
    resArr.push(item.join(' '))
  });
  return resStr + resArr.join('\n');
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, m, resultArr = [];
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    m = parseInt(resOne[1]);
  } else {
    resultArr.push(line.trim().split(' ').map((item) => parseInt(item)));
  }
  if (lineCount === n) {
    console.log(squareFilling(n, m, resultArr))
    rl.close();
  }
  lineCount ++;
});

// let n = 3;
// let m = 3;

// let resultArray = [
//     [1,1,1],
//     [1,1,1],
//     [0,1,1]
// ];
// let resultArray = [
//   [1,0,1],
//   [1,0,1],
//   [0,0,0]
// ];
// let resultArray = [
//   [0,0],
//   [0,0],
//   [0,0]
// ];

// console.log(squareFilling(n, m, resultArray));

function squareFilling (n, m, resultArray) {
  let operateCount = 0;
  let operateSelect = [];
  let x = 0;
  let y = 0;
  let hasOne = false;

  function isConform(x, y) {
    let topLeft = resultArray[x][y];
    let topRight = resultArray[x + 1][y];
    let bottomLeft = resultArray[x][y + 1];
    let bottomRight = resultArray[x + 1][y + 1];

    if (!hasOne && (topLeft === 1 || topRight === 1 || bottomLeft === 1 || bottomRight === 1)) {
      hasOne = true;
    }

    return (topLeft === 1 && topRight === 1 && bottomLeft === 1 && bottomRight === 1)
  }

  while (x < n - 1) {
    if (isConform(x, y)) {
      operateCount+=1;
      operateSelect.push([x + 1,y + 1]);
    }

    // 从0 开始，也就是偶数开始
    if (x % 2 === 0) {
      // 偶数 向右
      y+=1;
      if (y === (m - 1)) {
        y -=1;
        x += 1;
      }
    } else {
      // 奇数 向左
      y-=1;
      if (y === -1) {
        y = 0;
        x += 1;
      }
    }
  }
  if (!operateSelect.length) {
    if (hasOne) {
      return -1;
    }
    return 0;
  }
  let resStr = `${operateCount}\n`
  operateSelect.forEach((item, idx) => {
    resStr += `${item[0]} ${item[1]}` + ((idx < operateSelect.length - 1) ? '\n' : '')
  });
  return resStr;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, m, resultArr = [];
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    m = parseInt(resOne[1]);
  } else {
    resultArr.push(line.trim().split(' ').map((item) => parseInt(item)));
  }
  if (lineCount === n) {
    console.log(squareFilling(n, m, resultArr))
    rl.close();
  }
  lineCount ++;
});

return

// let n = 3;
// let m = 2;

// let resultArray = [
//     [1,1,1],
//     [1,1,1],
//     [0,1,1]
// ];
// let resultArray = [
//   [1,0,1],
//   [1,0,1],
//   [0,0,0]
// ];
// let resultArray = [
//   [0,0],
//   [0,0],
//   [0,0]
// ];

function squareFilling (n, m, resultArray) {
  let operateCount = 0;
  let operateSelect = [];
  let x = 0;
  let y = 0;
  let hasOne = false;

  function isConform(x, y) {
    let topLeft = resultArray[x][y];
    let topRight = resultArray[x + 1][y];
    let bottomLeft = resultArray[x][y + 1];
    let bottomRight = resultArray[x + 1][y + 1];

    if (!hasOne && (topLeft === 1 || topRight === 1 || bottomLeft === 1 || bottomRight === 1)) {
      hasOne = true;
    }

    return (topLeft === 1 && topRight === 1 && bottomLeft === 1 && bottomRight === 1)
  }

  let operateIndex = 0;
// 变成一个方阵之后的总长度
  let len = (n -1) * (m - 1);

  while (operateIndex < len) {
    if (isConform(x, y)) {
      operateCount+=1;
      operateSelect.push([x + 1,y + 1]);
    }

    let curIdx = Math.floor((operateIndex + 1)/n);

    // 从0 开始，也就是偶数开始
    if (curIdx % 2 === 0) {
      // 偶数 向下
      x+=1;
      if (x === (n - 1)) {
        x -=1;
        y += 1;
      }
    } else {
      // 奇数 向上
      x-=1;
    }
    operateIndex++;
  }
  if (!operateSelect.length) {
    if (hasOne) {
      return -1;
    }
    return '';
  }
  let resStr = `${operateCount}\n`
  operateSelect.forEach((item, idx) => {
    resStr += `${item[0]} ${item[1]}` + ((idx < operateSelect.length - 1) ? '\n' : '')
  });
  return resStr;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, m, resultArr = [];
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    m = parseInt(resOne[1]);
  } else {
    resultArr.push(line.trim().split(' ').map((item) => parseInt(item)));
  }
  if (lineCount === n) {
    console.log(squareFilling(n, m, resultArr))
    rl.close();
  }
  lineCount ++;
});

// let n = 3;
// let m = 2;

// let resultArray = [
//     [1,1,1],
//     [1,1,1],
//     [0,1,1]
// ];
// let resultArray = [
//   [1,0,1],
//   [1,0,1],
//   [0,0,0]
// ];
// let resultArray = [
//   [0,0],
//   [0,0],
//   [0,0]
// ];

function squareFilling (n, m, resultArray) {
  let operateCount = 0;
  let operateSelect = [];
  let x = 0;
  let y = 0;
  let hasOne = false;

  function isConform(x, y) {
    let topLeft = resultArray[x][y];
    let topRight = resultArray[x + 1][y];
    let bottomLeft = resultArray[x][y + 1];
    let bottomRight = resultArray[x + 1][y + 1];

    if (!hasOne && (topLeft === 1 || topRight === 1 || bottomLeft === 1 || bottomRight === 1)) {
      hasOne = true;
    }

    return (topLeft === 1 && topRight === 1 && bottomLeft === 1 && bottomRight === 1)
  }

  let operateIndex = 0;
// 变成一个方阵之后的总长度
  let len = (n -1) * (m - 1);

  while (operateIndex < len) {
    if (isConform(x, y)) {
      operateCount+=1;
      operateSelect.push([x + 1,y + 1]);
    }

    let curIdx = Math.floor((operateIndex + 1)/n);

    // 从0 开始，也就是偶数开始
    if (curIdx % 2 === 0) {
      // 偶数 向下
      x+=1;
      if (x === (n - 1)) {
        x -=1;
        y += 1;
      }
    } else {
      // 奇数 向上
      x-=1;
      if (x === -1) {
        x = 0
      }
    }
    operateIndex++;
  }
  if (!operateSelect.length) {
    if (hasOne) {
      return -1;
    }
    return 0;
  }
  let resStr = `${operateCount}\n`
  operateSelect.forEach((item, idx) => {
    resStr += `${item[0]} ${item[1]}` + ((idx < operateSelect.length - 1) ? '\n' : '')
  });
  return resStr;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, m, resultArr = [];
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    m = parseInt(resOne[1]);
  } else {
    resultArr.push(line.trim().split(' ').map((item) => parseInt(item)));
  }
  if (lineCount === n) {
    console.log(squareFilling(n, m, resultArr))
    rl.close();
  }
  lineCount ++;
});

// let n = 3;
// let m = 2;

// let resultArray = [
//     [1,1,1],
//     [1,1,1],
//     [0,1,1]
// ];
// let resultArray = [
//   [1,0,1],
//   [1,0,1],
//   [0,0,0]
// ];
// let resultArray = [
//   [0,0],
//   [0,0],
//   [0,0]
// ];

function squareFilling (n, m, resultArray) {
  let operateCount = 0;
  let operateSelect = [];
  let x = 0;
  let y = 0;
  let hasOne = false;

  function isConform(x, y) {
    console.log(x)
    let topLeft = resultArray[x][y];
    let topRight = resultArray[x + 1][y];
    let bottomLeft = resultArray[x][y + 1];
    let bottomRight = resultArray[x + 1][y + 1];

    if (!hasOne && (topLeft === 1 || topRight === 1 || bottomLeft === 1 || bottomRight === 1)) {
      hasOne = true;
    }

    return (topLeft === 1 && topRight === 1 && bottomLeft === 1 && bottomRight === 1)
  }

  let operateIndex = 0;
// 变成一个方阵之后的总长度
  let len = (n -1) * (m - 1);

  while (operateIndex < len) {
    if (isConform(x, y)) {
      operateCount+=1;
      operateSelect.push([x + 1,y + 1]);
    }

    let curIdx = Math.floor((operateIndex + 1)/n);

    // 从0 开始，也就是偶数开始
    if (curIdx % 2 === 0) {
      // 偶数 向下
      x+=1;
      if (x === (n - 1)) {
        x -=1;
        y += 1;
      }
    } else {
      // 奇数 向上
      x-=1;
      if (x === -1) {
        x = 0
      }
    }
    operateIndex++;
  }
  if (!operateSelect.length) {
    if (hasOne) {
      return -1;
    }
    return 0;
  }
  let resStr = `${operateCount}\n`
  operateSelect.forEach((item, idx) => {
    resStr += `${item[0]} ${item[1]}` + ((idx < operateSelect.length - 1) ? '\n' : '')
  });
  return resStr;
}

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {"use strict";
    // TODO
    var input = rdArN();
    var n = input[0];
    var m = input[1];
    var A = [];
    for (var i = 0; i < n; ++i) {
        A.push(rdArN());
    }
    var dx = [0,1,0,1];
    var dy = [0,0,1,1];
    var check = function(x, y) {
        var f = true;
        for (var k = 0; k < 4; ++k) {
            f = f && (A[x + dx[k]][y + dy[k]] > 0);
        }
        return f;
    };
    var fill = function (x, y) {
        for (var k = 0; k < 4; ++k) {
            A[x + dx[k]][y + dy[k]] = 2;
        }
    };
    var fillOrder = []
    for (var i = 0; i < n-1; ++i) {
        for (var j = 0; j < m-1; ++j) {
            if (check(i, j)) {
                fill(i, j);
                fillOrder.push([i+1, j+1]);
            }
        }
    }
    var isFilled = true;
    for (var i = 0; i < n-1; ++i) {
        for (var j = 0; j < m-1; ++j) {
            if (A[i][j] === 1) {
                isFilled = false;
            }
        }
    }
    if (isFilled) {
        pr(fillOrder.length);
        for (var i = 0; i < fillOrder.length; ++i) {
            prAr(fillOrder[i]);
        }
    } else {
        pr(-1);
    }
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
getPrimeFactors=function(n){var primes=getPrimes(Math.floor(Math.sqrt(n))),last=primes.push(n)-1,factors=[],i,p;for(i=0,p=primes[0];primes[last]>1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});

main();
return OUTPUT;
})();


Each day in Berland consists of $$$n$$$ hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence $$$a_1, a_2, \dots, a_n$$$ (each $$$a_i$$$ is either $$$0$$$ or $$$1$$$), where $$$a_i=0$$$ if Polycarp works during the $$$i$$$-th hour of the day and $$$a_i=1$$$ if Polycarp rests during the $$$i$$$-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.

The first line contains $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — number of hours per day. The second line contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i=0$$$ if the $$$i$$$-th hour in a day is working and $$$a_i=1$$$ if the $$$i$$$-th hour is resting. It is guaranteed that $$$a_i=0$$$ for at least one $$$i$$$.

Print the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.

NoteIn the first example, the maximal rest starts in last hour and goes to the first hour of the next day.In the second example, Polycarp has maximal rest from the $$$4$$$-th to the $$$5$$$-th hour.In the third example, Polycarp has maximal rest from the $$$3$$$-rd to the $$$5$$$-th hour.In the fourth example, Polycarp has no rest at all.

     var n = readline()
   var arr = readline().split(' ').map(Number)
   var ans = 0,cnt = 0
   var p = 0
   var f = true
   for(var i=0; i<n; i++) {
        if(arr[i]===0){
            if(f) {
                p = cnt
            }
            ans = Math.max(ans,cnt)
            cnt = 0
            f = false
        }
        else {
            cnt++
        }
    }
    p = p + cnt
    ans = Math.max(ans,p)
    print(ans)

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

var inputs = [];
const PI = parseInt;

function main() {
    const n = inputs[0].split().map(_ => parseInt(_))[0];
    let str = "";
    for(let i = 1 ; i < inputs.length ; i++) {
        str += " " + inputs[i];
    }
    str = str + " " + str;
    //console.log(str);
    let count = 0, mn = 0;
    str.split(" ").map(_ => parseInt(_)).forEach( val => {
        if(val == 1) count++;
        else if(val == 0) {
            count = 0;
        }
        mn = Math.max(count, mn);
    });
    console.log(Math.min(n, mn));
}

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

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

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

  let arr = d.split(' ').map(Number);
  let ans = 0;
  let count = 0;

  for (let i = 0; i < 2 * arr.length; i++) {
    if (arr[i % arr.length] === 1) {
      count++;
    }
    else {
      count = 0;
    }

    ans = Math.max(ans, count);
  }

  console.log(ans);

  // const idxZero = arr.indexOf(0);

  // if (idxZero !== -1) {
  //   arr = [...arr.slice(idxZero + 1), ...arr.slice(0, idxZero + 1)];
  // }

  // for (let i = 0; i < arr.length; i++) {
  //   if (arr[i] === 1) {
  //     count++;
  //   }
  //   else {
  //     count = 0;
  //   }

  //   ans = Math.max(ans, count);
  // }

  // console.log(ans);

  c++;
});

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

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

  let arr = d.split(' ').map(Number);
  const idxZero = arr.indexOf(0);
  let ans = 0;
  let count = 0;

  if (idxZero !== -1) {
    arr = [...arr.slice(idxZero + 1), ...arr.slice(0, idxZero + 1)];
  }

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

    ans = Math.max(ans, count);
  }

  console.log(ans);

  c++;
});

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

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

let nl = nextLine();

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

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

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

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

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

const sol = () => {
	let n = nl.num();
	let a = nl.nums();
	a = a.concat(a);
	let cnt = 0;
	let c = 0;
	for(let i of a){
		if (i === 1){
			c++;
		} else if (c > cnt){
			cnt = c;
			c = 0;
		} else {
			c = 0;
		}
	}
	if (c > cnt) cnt = c;
	console.log(cnt);

};

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

     var n = readline()
   var arr = readline().split(' ').map(Number)
   var ans = 0,cnt = 0
   for(var i=0; i<n; i++) {
        if(arr[i]===0){
            ans = Math.max(ans,cnt)
            cnt = 0
        }
        else {
            cnt++
        }
    }
    ans = Math.max(ans,cnt)
    print(ans)

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

var inputs = [];
const PI = parseInt;

function main() {
    const n = inputs[0].split(" ").map(_ => parseInt(_))[0];
    const arr = inputs[1].split(" ").map(_ => parseInt(_));
    let s = arr[n - 1];
    let count = s;
    let i = 0;
    let mn = 0;
    while(i < n) {
        mn = Math.max(count, mn);
        if(arr[i] === 1) count++;
        if(arr[i] === 0) {
            count = 0;
        }
        i++;
    }
    console.log(Math.min(n, mn));
}

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

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

var inputs = [];
const PI = parseInt;

function main() {
    const n = inputs[0].split().map(_ => parseInt(_))[0];
    let str = "";
    for(let i = 1 ; i < inputs.length ; i++) {
        str += " " + inputs[i];
    }
    let s = str[str.length - 1];
    let count = parseInt(s);
    let mn = 0;
    str.split(" ").map(_ => parseInt(_)).forEach( val => {
        if(val == 1) count++;
        else if(val == 0) {
            count = 0;
        }
        mn = Math.max(count, mn);
    });
    console.log(Math.min(n, mn));
}

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

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

var inputs = [];
const PI = parseInt;

function main() {
    const n = inputs[0].split().map(_ => parseInt(_))[0];
    let str = "";
    for(let i = 1 ; i < inputs.length ; i++) {
        str += " " + inputs[i];
    }
    str = str + " " + str;
    let count = 0, mn = 0;
    inputs[1].split(" ").map(_ => parseInt(_)).forEach( val => {
        if(val == 1) count++;
        else if(val == 0) {
            count = 0;
        }
        mn = Math.max(count, mn);
    });
    console.log(Math.min(n, mn));
}

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

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

var inputs = [];
const PI = parseInt;

function main() {
    const n = inputs[0].split().map(_ => parseInt(_))[0];
    let s = inputs[1][inputs[1].length - 1];
    let count = parseInt(s);
    let mn = 0;
    inputs[1].split(" ").map(_ => parseInt(_)).forEach( val => {
        if(val == 1) count++;
        else if(val == 0) {
            count = 0;
        }
        mn = Math.max(count, mn);
    });
    console.log(Math.min(n, mn));
}

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

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

var inputs = [];
const PI = parseInt;

function main() {
    const n = inputs[0].split().map(_ => parseInt(_))[0];
    let s = inputs[1][inputs[1].length - 1];
    let count = parseInt(s);
    let mn = 0;
    inputs[1].split(" ").map(_ => parseInt(_)).forEach( val => {
        if(val === 1) count++;
        else if(val === 0) {
            count = 0;
        }
        mn = Math.max(count, mn);
    });
    console.log(Math.min(n, mn));
}

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

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

var inputs = [];
const PI = parseInt;

function main() {
    const n = inputs[0].split(" ").map(_ => parseInt(_))[0];
    let s = inputs[1][inputs[1].length - 1];
    let count = parseInt(s);
    let i = 0;
    let mn = 0;
    inputs[1].split(" ").map(_ => parseInt(_)).forEach( val => {
        mn = Math.max(count, mn);
        if(val === 1) count++;
        else if(val === 0) {
            count = 0;
        }
        mn = Math.max(count, mn);
        i++;
    });
    console.log(Math.min(n, mn));
}

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

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

var inputs = [];
const PI = parseInt;

function main() {
    const n = inputs[0].split(" ").map(_ => parseInt(_))[0];
    let s = inputs[1][inputs[1].length - 1];
    let count = parseInt(s);
    let i = 0;
    let mn = 0;
    inputs[1].split(" ").map(_ => parseInt(_)).forEach( val => {
        if(val === 1) count++;
        else if(val === 0) {
            count = 0;
        }
        mn = Math.max(count, mn);
        i++;
    });
    console.log(Math.min(n, mn));
}

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

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

var inputs = [];
const PI = parseInt;

function main() {
    const n = inputs[0].split(" ").map(_ => parseInt(_))[0];
    const arr = inputs[1].split(" ").map(_ => parseInt(_));
    let s = arr[n - 1];
    let count = s;
    let i = 0;
    let mn = 0;
    while(i < n) {
        mn = Math.max(count, mn);
        if(arr[i] === 1) count++;
        if(arr[i] === 0) {
            count = 0;
        }
        mn = Math.max(count, mn);
        i++;
    }
    console.log(Math.min(n, mn));
}

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


A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).

The first and only line consists of a string $$$S$$$ ($$$ 1 \le |S| \le 5\,000 $$$). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.

NoteConsider first example: the number of 'c' is equal to the number of 'a'. Consider second example: although the number of 'c' is equal to the number of the 'b', the order is not correct.Consider third example: the number of 'c' is equal to the number of 'b'.

var s = readline()
if (s != s.split('').sort().join('')) {
  print('NO')
} else {
  var a =0, b=0, c=0;
  for(var i=0; i<s.length; i++) {
    if (s[i] == 'a') a++
    else if (s[i] == 'b') b++
    else if (s[i] == 'c') c++
  }
  if (a == 0 || b == 0 || c == 0)  print('NO')
  else if (c == a || c == b) print('YES')
  else print('NO')
}

// A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.

// B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.

// You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
// Input

// The first and only line consists of a string S (1 ≤ |S| ≤ 5 000). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.
// Output

// Print "YES" or "NO", according to the condition.

var s = readline().split('');
// edge case

function checkString(s) {

  // var ans = '';
  if (s.indexOf('a') === -1
      || s.indexOf('b') === -1
      || s.indexOf('c') === -1
      || s.indexOf('a') > s.indexOf('b')
      || s.indexOf('b') > s.indexOf('c')
      || s.indexOf('a') > s.indexOf('c')
    ) {
    // print('NO')
    return 'NO';
  } else {
    var countA = null, countB = null, countC = null;

    for (var i = 0; i < s.length; i++) {
      if (s[i + 1] < s[i]) {
        // print('NO')
        return 'NO';
      }
      if (s[i] === 'a') countA += 1;
      if (s[i] === 'b') countB += 1;
      if (s[i] === 'c') countC += 1;
    }

    if ((countC === countA || countC === countB) /*&& s[s.length - 1] === 'c' */&& s[s.indexOf('c') - 1] === 'b') {
      if (s[s.length - 1] !== 'c') {
        // print('NO');
        return 'NO';
      } else {
        // print('YES');
        return 'YES';
      }
    } else {
      // print('NO');
      return 'NO';
    }
  }
}

print(checkString(s));

var inp = readline();

var spread = inp.split('').reduce(
    function(res, cur) {
        var lastItem = res[res.length - 1];

        if (lastItem && lastItem.char === cur) {
            lastItem.count++;
        } else {
            res.push({
                char: cur,
                count: 1,
            });
        }

        return res;
    },
    []
);

if (
    spread.map(function(item) {
        return item.char.toLowerCase();
    }).join('') !== 'abc'
) {
    print('NO');
} else {
    var aCount = spread[0].count;
    var bCount = spread[1].count;
    var cCount = spread[2].count;

    if (
        (!aCount || !bCount || !cCount) ||
        cCount !== aCount && cCount !== bCount
    ) {
        print('NO');
    } else {
        print('YES');
    }
}

#!/usr/bin/env node

/**
 * Module dependencies.
 */

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

rl.on("line", function(line) {
    var a, b, c;
    a = b = c = 0;
    if (line.indexOf('a') < 0 ||
        line.indexOf('b') < 0 ||
        line.indexOf('c') < 0) {
        console.log("NO");
        rl.close();
    }
    if (!(line.lastIndexOf('a') < line.indexOf('b') &&
            line.lastIndexOf('b') < line.indexOf('c'))) {
        console.log("NO");
        rl.close();
    }
    for (var i = 0; i < line.length; i++) {
        switch (line.charAt(i)) {
            case 'a': a++; break;
            case 'b': b++; break;
            case 'c': c++; break;
        }
    }
    console.log((a === c || b === c) ? "YES" : "NO");
    rl.close();
}).on("close", function() {
    process.exit();
});

var s = readline()
if (s != s.split('').sort().join('')) {
  print('NO')
} else {
  var a =0, b=0, c=0;
  for(var i=0; i<s.length; i++) {
    if (s[i] == 'a') a++
    else if (s[i] == 'b') b++
    else if (s[i] == 'c') c++
  }
  if (c == a || c == b) print('YES')
  else print('NO')
}

// A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.

// B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.

// You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
// Input

// The first and only line consists of a string S (1 ≤ |S| ≤ 5 000). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.
// Output

// Print "YES" or "NO", according to the condition.

var s = readline().split('');

// edge case

if (s.indexOf('a') === -1
    || s.indexOf('b') === -1
    || s.indexOf('c') === -1
    || s.indexOf('a') > s.indexOf('b')
    || s.indexOf('b') > s.indexOf('c')
    || s.indexOf('a') > s.indexOf('c')
  ) {
  print('NO')
} else {

  var countA = null, countB = null, countC = null;

  for (var i = 0; i < s.length; i++) {
    if (s[i] === 'a') countA += 1;
    if (s[i] === 'b') countB += 1;
    if (s[i] === 'c') countC += 1;
  }

  if (countC === countA || countC === countB && s[s.length - 1] === 'c') {
    print('YES');
  } else {
    print('NO');
  }
}

// A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.

// B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.

// You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
// Input

// The first and only line consists of a string S (1 ≤ |S| ≤ 5 000). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.
// Output

// Print "YES" or "NO", according to the condition.

var s = readline().split('');

// edge case

if (s.indexOf('a') === -1
    || s.indexOf('b') === -1
    || s.indexOf('c') === -1
    || s.indexOf('a') > s.indexOf('b')
    || s.indexOf('b') > s.indexOf('c')
    || s.indexOf('a') > s.indexOf('c')
  ) {
  print('NO')
} else {

  var countA = null, countB = null, countC = null;

  for (var i = 0; i < s.length; i++) {
    if (s[i] === 'a') countA += 1;
    if (s[i] === 'b') countB += 1;
    if (s[i] === 'c') countC += 1;
  }

  if (countC === countA || countC === countB) {
    print('YES');
  } else {
    print('NO');
  }
}

// A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.

// B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.

// You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
// Input

// The first and only line consists of a string S (1 ≤ |S| ≤ 5 000). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.
// Output

// Print "YES" or "NO", according to the condition.

var s = readline().split('');
// edge case

if (s.indexOf('a') === -1
    || s.indexOf('b') === -1
    || s.indexOf('c') === -1
    || s.indexOf('a') > s.indexOf('b')
    || s.indexOf('b') > s.indexOf('c')
    || s.indexOf('a') > s.indexOf('c')
  ) {
  print('NO')
} else {

  var countA = null, countB = null, countC = null;

  for (var i = 0; i < s.length; i++) {
    if (s[i] === 'a') countA += 1;
    if (s[i] === 'b') countB += 1;
    if (s[i] === 'c') countC += 1;
  }

  if ((countC === countA || countC === countB) /*&& s[s.length - 1] === 'c' */&& s[s.indexOf('c') - 1] === 'b') {
    if (s[s.length - 1] !== 'c') {
      print('NO');
    } else {
      print('YES');
    }
  } else {
    print('NO');
  }
}

// A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.

// B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.

// You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
// Input

// The first and only line consists of a string S (1 ≤ |S| ≤ 5 000). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.
// Output

// Print "YES" or "NO", according to the condition.

var s = readline().split('');
// edge case

if (s.indexOf('a') === -1
    || s.indexOf('b') === -1
    || s.indexOf('c') === -1
    || s.indexOf('a') > s.indexOf('b')
    || s.indexOf('b') > s.indexOf('c')
    || s.indexOf('a') > s.indexOf('c')
  ) {
  print('NO')
} else {

  var countA = null, countB = null, countC = null;

  for (var i = 0; i < s.length; i++) {
    if (s[i] === 'a') countA += 1;
    if (s[i] === 'b') countB += 1;
    if (s[i] === 'c') countC += 1;
  }

  if (countC === countA || countC === countB /*&& s[s.length - 1] === 'c' */&& s[s.indexOf('c') - 1] === 'b') {
    if (s[s.length - 1] !== 'c') {
      print('NO');
    } else {
      print('YES');
    }
  } else {
    print('NO');
  }
}

// A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.

// B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.

// You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
// Input

// The first and only line consists of a string S (1 ≤ |S| ≤ 5 000). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.
// Output

// Print "YES" or "NO", according to the condition.

var s = readline().split('');

// edge case

if (s.indexOf('a') === -1
    || s.indexOf('b') === -1
    || s.indexOf('c') === -1
    || s.indexOf('a') > s.indexOf('b')
    || s.indexOf('b') > s.indexOf('c')
    || s.indexOf('a') > s.indexOf('c')
  ) {
  print('NO')
} else {

  var countA = null, countB = null, countC = null;

  for (var i = 0; i < s.length; i++) {
    if (s[i] === 'a') countA += 1;
    if (s[i] === 'b') countB += 1;
    if (s[i] === 'c') countC += 1;
  }

  if (countC === countA || countC === countB && s[s.length - 1] === 'c' && s[s.indexOf('c') - 1] === 'b') {
    print('YES');
  } else {
    print('NO');
  }
}

var inp = readline();

var spread = inp.split('').reduce(
    function(res, cur) {
        var lastItem = res[res.length - 1];

        if (lastItem && lastItem.char === cur) {
            lastItem.count++;
        } else {
            res.push({
                char: cur,
                count: 1,
            });
        }

        return res;
    },
    []
);

if (
    spread.map(function(item) {
        return item.char.toLowerCase();
    }).join('') !== 'abc'
) {
    print('NO');
} else {
    var aCount = spread[0].count;
    var bCount = spread[1].count;
    var cCount = spread[2].count;

    if (
        (!aCount || !bCount || !cCount) ||
        cCount !== aCount && cCount !== bCount
    ) {
        print('NO');
    }

    print('YES');
}

#!/usr/bin/env node

/**
 * Module dependencies.
 */

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

rl.on("line", function(line) {
    var a, b, c;
    a = b = c = 0;
    if (line.indexOf('a') < 0 ||
        line.indexOf('b') < 0 ||
        line.indexOf('c') < 0) {
        console.log("NO");
        rl.close();
    }
    var ap = line.indexOf('a');
    var bp = line.indexOf('b');
    var cp = line.indexOf('c');
    if (!(ap < bp && bp < cp)) {
        console.log("NO");
        rl.close();
    }
    for (var i = 0; i < line.length; i++) {
        switch (line.charAt(i)) {
            case 'a': a++; break;
            case 'b': b++; break;
            case 'c': c++; break;
        }
    }
    console.log((a === c || b === c) ? "YES" : "NO");
    rl.close();
}).on("close", function() {
    process.exit();
});


Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).For any integer $$$k$$$ and positive integer $$$n$$$, let $$$k\bmod n$$$ denote the remainder when $$$k$$$ is divided by $$$n$$$. More formally, $$$r=k\bmod n$$$ is the smallest non-negative integer such that $$$k-r$$$ is divisible by $$$n$$$. It always holds that $$$0\le k\bmod n\le n-1$$$. For example, $$$100\bmod 12=4$$$ and $$$(-1337)\bmod 3=1$$$.Then the shuffling works as follows. There is an array of $$$n$$$ integers $$$a_0,a_1,\ldots,a_{n-1}$$$. Then for each integer $$$k$$$, the guest in room $$$k$$$ is moved to room number $$$k+a_{k\bmod n}$$$.After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 2\cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_0,a_1,\ldots,a_{n-1}$$$ ($$$-10^9\le a_i\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, output a single line containing "YES" if there is exactly one guest assigned to each room after the shuffling process, or "NO" otherwise. You can print each letter in any case (upper or lower).

NoteIn the first test case, every guest is shifted by $$$14$$$ rooms, so the assignment is still unique.In the second test case, even guests move to the right by $$$1$$$ room, and odd guests move to the left by $$$1$$$ room. We can show that the assignment is still unique.In the third test case, every fourth guest moves to the right by $$$1$$$ room, and the other guests move to the right by $$$5$$$ rooms. We can show that the assignment is still unique.In the fourth test case, guests $$$0$$$ and $$$1$$$ are both assigned to room $$$3$$$.In the fifth test case, guests $$$1$$$ and $$$2$$$ are both assigned to room $$$2$$$.

const mod = (k, n) => k >= 0 ? k % n : (n + (k%n))%n

const processData = (lines) => {
  const nums = +lines[0]
  for (let i =0; i<nums;i++) {
    const n = +lines[i*2 + 1]
    const arr = lines[i*2 + 2].split(' ').map(x => +x)

    const producedArr = arr.map(
      x => mod(x, n)
    )
    const res = {}
    for (let j=0; j<arr.length; j++) {
      const t = mod(j + producedArr[j], n)
      res[t] = 1
    }
    console.log(Object.keys(res).length === n ? 'YES' : 'NO')
  }
}

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

'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++];
}
/**
   6
1
14
2
1 -1
4
5 5 5 1
3
3 2 1
2
0 1
5
-239 -2 -100 -3 -11
**/

function main() {
    var range = readline();

    for(var r=0;r<range;r++) {
        let n = parseInt(readline());
        let h = readline().split(" ").map(Number);

        for(let i=0;i<n;i++) {
            h[i] = (i + n + (h[i] % n)) % n;
        }

        let nonD = [...new Set(h)]

        if(nonD.length !== n) {
            console.log('No');
        } else {
            console.log('Yes');
        }

    }
}

const processData = (lines) => {
  const nums = +lines[0]
  for (let i =0; i<nums;i++) {
    const n = +lines[i*2 + 1]
    const arr = lines[i*2 + 2].split(' ').map(x => +x)

    const producedArr = arr.map(
      x => {
        if (x >= 0) return x % arr.length
        return (arr.length * Math.ceil(Math.abs(x) / arr.length) - x) % arr.length
      }
    )
    const res = []
    for (let j=0; j<arr.length*2; j++) {
      res[j] = j + producedArr[j % arr.length]
    }
    console.log(Array.from(new Set(res)).length === res.length ? 'YES' : 'NO')
  }
}

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

const processData = (lines) => {
  const nums = +lines[0]
  for (let i =0; i<nums;i++) {
    const n = +lines[i*2 + 1]
    const arr = lines[i*2 + 2].split(' ').map(x => +x)

    const producedArr = arr.map(
      x => {
        if (x >= 0) return x % arr.length
        return (arr.length * Math.ceil(Math.abs(x) / arr.length) - x) % arr.length
      }
    )
    const res = []
    for (let j=0; j<arr.length*3; j++) {
      res[j] = j + producedArr[j % arr.length]
    }
    console.log(Array.from(new Set(res)).length === res.length ? 'YES' : 'NO')
  }
}

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

const processData = (lines) => {
  const nums = +lines[0]
  for (let i =0; i<nums;i++) {
    const n = +lines[i*2 + 1]
    const arr = lines[i*2 + 2].split(' ').map(x => +x)

    const producedArr = arr.map(
      x => x % arr.length
    )
    const res = {}
    for (let j=0; j<arr.length; j++) {
      const t = j + producedArr[j]
      res[t % n] = 1
    }
    console.log(Object.keys(res).length === n ? 'YES' : 'NO')
  }
}

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


School holidays come in Berland. The holidays are going to continue for n days. The students of school №N are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people are in charge of the daily watering of flowers in shifts according to the schedule. However when Marina Sergeyevna was making the schedule, she was so tired from work and so lost in dreams of the oncoming vacation that she perhaps made several mistakes. In fact, it is possible that according to the schedule, on some days during the holidays the flowers will not be watered or will be watered multiple times. Help Marina Sergeyevna to find a mistake.

The first input line contains two numbers n and m (1 ≤ n, m ≤ 100) — the number of days in Berland holidays and the number of people in charge of the watering respectively. The next m lines contain the description of the duty schedule. Each line contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), meaning that the i-th person in charge should water the flowers from the ai-th to the bi-th day inclusively, once a day. The duty shifts are described sequentially, i.e. bi ≤ ai + 1 for all i from 1 to n - 1 inclusively.

Print "OK" (without quotes), if the schedule does not contain mistakes. Otherwise you have to find the minimal number of a day when the flowers will not be watered or will be watered multiple times, and output two integers — the day number and the number of times the flowers will be watered that day.

NoteKeep in mind that in the second sample the mistake occurs not only on the second day, but also on the sixth day, when nobody waters the flowers. However, you have to print the second day, i.e. the day with the minimal number.

var rr = readline().split(' ');

var n = Number(rr[0]);
var m = Number(rr[1]);

var i, k;
var a=[], b=[], c=[];
var flag = -1;
var day = -1;

for(i=0; i<=n; i++)
{
  c[i] = 0;
}

for(i=0; i<m; i++)
{
  read = readline().split(' ');
  a[i] = Number(read[0]);
  b[i] = Number(read[1]);

  for(k=a[i]; k<=b[i]; k++)
  {
    c[k]++;
  }

}

for(i=0; i<n; i++)
{
  if(flag == -1 && c[i+1] == 0)
  {
    flag = 0;
    day = i+1;
  }
  if(flag == -1 && c[i+1] > 1)
  {
    flag = c[i+1];
    day = i+1;
  }
}
/**/

if(flag == -1) print('OK');
else print(day,' ',flag);

var rr = readline().split(' ');

var n = Number(rr[0]);
var m = Number(rr[1]);

var i, k;
var a=[], b=[], c=[];
var flag = -1;
var day = -1;

for(i=0; i<=n; i++)
{
  c[i] = 0;
  /*c.push(0);*/
}
/*
for(i=0; i<m; i++)
{
  read = readline().split(' ');
  a.push( Number(read[0]) );
  b.push( Number(read[1]) );

  for(k=a[i]; k<=b[i]; k++)
  {
    c[k]++;
  }
}

for(i=0; i<n; i++)
{
  if(flag == -1 and c[i+1] == 0)
  {
    flag = 0;
    day = i+1;
  }
  if(flag == -1 and c[i+1] > 1)
  {
    flag = c[i+1];
    day = i+1;
  }
}
*/

if(flag == -1) print('OK');
else print(day,' ',flag);

var rr = readline().split(' ');

/*

var n = Number(rr[0]);
var m = Number(rr[1]);
var i, k;
var a[], b[], c[];
var flag = -1;
var day = -1;

/*

for(i=0; i<110; i++)
{
  c.push(0);
}

/*

for(i=0; i<m; i++)
{
  read = readline().split(' ');
  a.push( Number(read[0]) );
  b.push( Number(read[1]) );

  for(k=a[i]; k<=b[i]; k++)
  {
    c[k]++;
  }
}

for(i=0; i<n; i++)
{
  if(flag == -1 and c[i+1] == 0)
  {
    flag = 0;
    day = i+1;
  }
  if(flag == -1 and c[i+1] > 1)
  {
    flag = c[i+1];
    day = i+1;
  }
}

if(flag == -1) print('OK');
else print(day,' ',flag);
*/

print('OK');

var rr = readline().split(' ');

var n = Number(rr[0]);
var m = Number(rr[1]);

var i, k;
var a=[], b=[], c=[];
var flag = -1;
var day = -1;

for(i=0; i<=n; i++)
{
  c[i] = 0;
}

for(i=0; i<m; i++)
{
  read = readline().split(' ');
  a[i] = Number(read[0]);
  b[i] = Number(read[1]);
  /*
  for(k=a[i]; k<=b[i]; k++)
  {
    c[k]++;
  }
  */
}

/*

for(i=0; i<n; i++)
{
  if(flag == -1 and c[i+1] == 0)
  {
    flag = 0;
    day = i+1;
  }
  if(flag == -1 and c[i+1] > 1)
  {
    flag = c[i+1];
    day = i+1;
  }
}
*/

if(flag == -1) print('OK');
else print(day,' ',flag);

var rr = readline().split(' ');

/*

var n = Number(rr[0]);
var m = Number(rr[1]);
var i, k;
var a[], b[], c[];
var flag = -1;
var day = -1;

/*

for(i=0; i<110; i++)
{
  c.push(0);
}

/*

for(i=0; i<m; i++)
{
  read = readline().split(' ');
  a.push( Number(read[0]) );
  b.push( Number(read[1]) );

  for(k=a[i]; k<=b[i]; k++)
  {
    c[k]++;
  }
}

for(i=0; i<n; i++)
{
  if(flag == -1 and c[i+1] == 0)
  {
    flag = 0;
    day = i+1;
  }
  if(flag == -1 and c[i+1] > 1)
  {
    flag = c[i+1];
    day = i+1;
  }
}

if(flag == -1) print('OK');
else print(day,' ',flag);
*/

print(55);

var rr = readline().split(' ');

var n = Number(rr[0]);
var m = Number(rr[1]);

var i, k;
var a=[], b=[], c=[];
var flag = -1;
var day = -1;

for(i=0; i<=n; i++)
{
  c[i] = 0;
}

for(i=0; i<m; i++)
{
  read = readline().split(' ');
  a[i] = Number(read[0]);
  b[i] = Number(read[1]);

  for(k=a[i]; k<=b[i]; k++)
  {
    c[k]++;
  }

}

/*

for(i=0; i<n; i++)
{
  if(flag == -1 and c[i+1] == 0)
  {
    flag = 0;
    day = i+1;
  }
  if(flag == -1 and c[i+1] > 1)
  {
    flag = c[i+1];
    day = i+1;
  }
}
/**/

if(flag == -1) print('OK');
else print(day,' ',flag);

/*

var rr = readline().split(' ');

var n = Number(rr[0]);
var m = Number(rr[1]);
var i, k;
var a[], b[], c[];
var flag = -1;
var day = -1;

/*

for(i=0; i<110; i++)
{
  c.push(0);
}

/*

for(i=0; i<m; i++)
{
  read = readline().split(' ');
  a.push( Number(read[0]) );
  b.push( Number(read[1]) );

  for(k=a[i]; k<=b[i]; k++)
  {
    c[k]++;
  }
}

for(i=0; i<n; i++)
{
  if(flag == -1 and c[i+1] == 0)
  {
    flag = 0;
    day = i+1;
  }
  if(flag == -1 and c[i+1] > 1)
  {
    flag = c[i+1];
    day = i+1;
  }
}

if(flag == -1) print('OK');
else print(day,' ',flag);
*/

print(55);

var rr = readline().split(' ');

var n = Number(rr[0]);
var m = Number(rr[1]);

/*
var i, k;
var a[], b[], c[];
var flag = -1;
var day = -1;

/*

for(i=0; i<110; i++)
{
  c.push(0);
}

/*

for(i=0; i<m; i++)
{
  read = readline().split(' ');
  a.push( Number(read[0]) );
  b.push( Number(read[1]) );

  for(k=a[i]; k<=b[i]; k++)
  {
    c[k]++;
  }
}

for(i=0; i<n; i++)
{
  if(flag == -1 and c[i+1] == 0)
  {
    flag = 0;
    day = i+1;
  }
  if(flag == -1 and c[i+1] > 1)
  {
    flag = c[i+1];
    day = i+1;
  }
}

if(flag == -1) print('OK');
else print(day,' ',flag);
*/

print('xOK');

var rr = readline().split(' ');

var n = Number(rr[0]);
var m = Number(rr[1]);

var i, k;
var a=[], b=[], c=[];
var flag = -1;
var day = -1;

/*

for(i=0; i<110; i++)
{
  c.push(0);
}

/*

for(i=0; i<m; i++)
{
  read = readline().split(' ');
  a.push( Number(read[0]) );
  b.push( Number(read[1]) );

  for(k=a[i]; k<=b[i]; k++)
  {
    c[k]++;
  }
}

for(i=0; i<n; i++)
{
  if(flag == -1 and c[i+1] == 0)
  {
    flag = 0;
    day = i+1;
  }
  if(flag == -1 and c[i+1] > 1)
  {
    flag = c[i+1];
    day = i+1;
  }
}

if(flag == -1) print('OK');
else print(day,' ',flag);
*/

print('xOK');