You are given a graph consisting of $$$n$$$ vertices and $$$m$$$ edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges.You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$$$) — the number of vertices and the number of edges in the graph, respectively. The next $$$m$$$ lines describe edges of the graph. The $$$i$$$-th edge is described with three integers $$$t_i$$$, $$$x_i$$$ and $$$y_i$$$ ($$$t_i \in [0; 1]$$$, $$$1 \le x_i, y_i \le n$$$) — the type of the edge ($$$t_i = 0$$$ if the edge is undirected and $$$t_i = 1$$$ if the edge is directed) and vertices this edge connects (the undirected edge connects vertices $$$x_i$$$ and $$$y_i$$$ and directed edge is going from the vertex $$$x_i$$$ to the vertex $$$y_i$$$). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair ($$$x_i, y_i$$$) there are no other pairs ($$$x_i, y_i$$$) or ($$$y_i, x_i$$$)). It is guaranteed that both sum $$$n$$$ and sum $$$m$$$ do not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$; $$$\sum m \le 2 \cdot 10^5$$$).

For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and $$$m$$$ lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any.

NoteExplanation of the second test case of the example:Explanation of the third test case of the example:

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    let [v, e] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const queue = [];
    const graph = {};
    const indegrees = Array(v + 1).fill(0);
    const directedpairs = [];
    const nonDirectedpairs = [];
    const positions = [];

    let [di, ndi] = [0, 0];
    for (let i = 0; i < e; i++) {
      let [directed, src, destination] = readLine()
        .split(" ")
        .map((n) => parseInt(n));
      if (directed) {
        if (!graph[src]) graph[src] = [destination];
        else graph[src].push(destination);
        directedpairs[di] = [src, destination];
        indegrees[destination]++;
        di++;
      } else {
        nonDirectedpairs[ndi] = [src, destination];
        ndi++;
      }
    }

    for (let i = 1; i <= v; i++) {
      if (indegrees[i] === 0) {
        queue.push(i);
      }
    }

    let index = 0;
    while (queue.length) {
      const u = queue.pop();
      positions[u] = index;
      index++;
      if (graph[u]) {
        for (let i = 0; i < graph[u].length; i++) {
          const v = graph[u][i];
          if (--indegrees[v] === 0) {
            queue.push(v);
          }
        }
      }
    }
    if (index !== v) {
      console.log("NO");
      continue;
    } else {
      console.log("YES");
      for (let i = 0; i < directedpairs.length; i++) {
        let [src, destination] = directedpairs[i];
        console.log(`${src} ${destination}`);
      }

      for (let i = 0; i < nonDirectedpairs.length; i++) {
        let [src, destination] = nonDirectedpairs[i];
        if (positions[src] < positions[destination]) {
          console.log(`${src} ${destination}`);
        } else {
          console.log(`${destination} ${src}`);
        }
      }
    }
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    let [v, e] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const queue = [];
    const graph = {};
    const indegrees = Array(v + 1).fill(0);
    const directedpairs = [];
    const nonDirectedpairs = [];
    const positions = [];

    for (let i = 0; i < e; i++) {
      let [directed, src, destination] = readLine()
        .split(" ")
        .map((n) => parseInt(n));
      if (directed) {
        if (!graph[src]) graph[src] = [destination];
        else graph[src].push(destination);
        directedpairs.push([src, destination]);
        indegrees[destination]++;
      } else {
        nonDirectedpairs.push([src, destination]);
      }
    }

    for (let i = 1; i <= v; i++) {
      if (indegrees[i] === 0) {
        queue.push(i);
      }
    }

    let index = 0;
    while (queue.length) {
      const u = queue.pop();
      positions[u] = index;
      index++;
      if (graph[u]) {
        for (let i = 0; i < graph[u].length; i++) {
          const v = graph[u][i];
          if (--indegrees[v] === 0) {
            queue.push(v);
          }
        }
      }
    }
    if (index !== v) {
      console.log("NO");
      continue;
    } else {
      console.log("YES");
      for (let i = 0; i < directedpairs.length; i++) {
        let [src, destination] = directedpairs[i];
        console.log(`${src} ${destination}`);
      }

      for (let i = 0; i < nonDirectedpairs.length; i++) {
        let [src, destination] = nonDirectedpairs[i];
        if (positions[src] < positions[destination]) {
          console.log(`${src} ${destination}`);
        } else {
          console.log(`${destination} ${src}`);
        }
      }
    }
  }
}


Vasya has a grid with $$$2$$$ rows and $$$n$$$ columns. He colours each cell red, green, or blue.Vasya is colourblind and can't distinguish green from blue. Determine if Vasya will consider the two rows of the grid to be coloured the same.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of columns of the grid. The following two lines each contain a string consisting of $$$n$$$ characters, each of which is either R, G, or B, representing a red, green, or blue cell, respectively — the description of the grid.

For each test case, output "YES" if Vasya considers the grid's two rows to be identical, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

6

2

RG

RB

4

GRBG

GBGB

5

GGGGG

BBBBB

7

BBBBBBB

RRRRRRR

8

RGBRRGBR

RGGRRBGR

1

G

G

NoteIn the first test case, Vasya sees the second cell of each row as the same because the second cell of the first row is green and the second cell of the second row is blue, so he can't distinguish these two cells. The rest of the rows are equal in colour. Therefore, Vasya will say that the two rows are coloured the same, even though they aren't.In the second test case, Vasya can see that the two rows are different.In the third test case, every cell is green or blue, so Vasya will think they are the same.

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

let lines = []

const createReadLine = () => {
  i = 0;
  return () => {
    return lines[i++]
  }
}

rl.on('line', line => lines.push(line))
rl.on('close', () => {
  const readLine = createReadLine();
  let t = parseInt(readLine())
  while (t--) {
    readLine()
    console.log(readLine().replace(/\G/g, 'B') == readLine().replace(/\G/g, 'B') ? 'YES' : 'NO')
  }
})

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0],e=0,f = false, k = 0, even = 1
    for(j = 1; j <= n *3; j+=even){
        if(j % 3 == 1){
            even=1
            e = lines[j], f = false
        }else{
            k = lines[j].split('')
            g = lines[j + 1].split('')
            for(l = 0; l < e; l++){
                if(k[l] == 'R' && g[l] == 'R' || k[l] == 'G' && g[l] == 'G' || k[l] == 'G' && g[l] == 'B' || k[l] == 'B' && g[l] == 'G' || k[l] == 'B' && g[l] == 'B' ){
                    f = true
                }else{
                    f = false
                    break;
                }
            }
            even =  2
            if(f){
                console.log('YES')
            }else{
                console.log('NO')
            }
        }
    }

});

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

let c = 0;
let str1, str2;

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

  if (c % 3 === 1) {
    c++;
    return;
  }

  if (c % 3 === 2) {
    str1 = d;
    c++;
    return;
  }

  str2 = d;
  let ans = "YES";

  for (let i = 0; i < str1.length; i++) {
    if (str1[i] !== str2[i] && (str1[i] === "R" || str2[i] === "R")) {
      ans = "NO";
      break;
    }
  }

  console.log(ans);

  c++;
});

rl.on("close", () => {});

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    var a = 0;
    for(i = 1; i <= t * 3; i++){
        if(i % 3 == 1){
            n = lines[i];
        }else if(i % 3 == 2){
            a = lines[i].split('');
        }else{
            var b = lines[i].split('');
            var flag = true;
            for(j = 0; j < n; j++){
                if(a[j] == b[j] || a[j] == 'G' && b[j] == 'B' || a[j] == 'B' && b[j] == 'G'){
                    continue;
                }
                flag = false;
            }
            console.log(flag ? 'YES' : 'NO');
        }
    }
});

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
    var t = parseInt(readline());
    for (let i = 0; i < t; i++) {
        var n = parseInt(readline());
        var x = Array.from(readline());
        var y = Array.from(readline());
        var ok = true;

        for (let i = 0;i < n;++i) {
            if (x[i] == 'G') {
                x[i] = 'B';
            }
            if (y[i] == 'G') {
                y[i] = 'B';
            }
            if (x[i] != y[i]) {
                ok = false;
            }
        }
        if (ok) {
            console.log('YES');
        } else {
            console.log('NO');
        }

    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

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

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        const cb = char => (char === 'G' || char === 'B') ? 'X' : char;
        let a = readline().split('').map(cb).join('');
        let b = readline().split('').map(cb).join('');
        output(a === b ? 'YES': 'NO');
    }
}

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

// Main Function, write code here

function main() {
  let T = readline();
  for (let i = 0; i < T; i++) {
    const n = readline();
    const row1 = readline()
      .split("")
      .map((color) => color.replace("G", "B"));
    const row2 = readline()
      .split("")
      .map((color) => color.replace("G", "B"));

    const identical = row1.join("") === row2.join("");
    console.log(identical ? "Yes" : "No");
  }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numberOfTest = Number.parseInt(readline());
    for(let i=0; i<numberOfTest; i++){
        const strLength = Number.parseInt(readline());
        const str1 = readline();
        const str2 = readline()
        Solution(strLength, str1, str2);
    }
}

function Solution(strLength, s1, s2){
    let result = "YES";
    for(let i=0; i<strLength; i++){
        const s1Char = s1.charAt(i);
        const s2Char = s2.charAt(i);
        if(s1Char == 'R' || s2Char == 'R'){
            if(s1Char !== s2Char){
                result = "NO"
                break;
            }
        }
    }
    console.log(result);
}

const rdline = require('readline');
const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];

solve = () => {
    const t = parseInt(readline());
    for (let i = 0; i < t; i++) {
        var n = parseInt(readline());
        var str1 = readline().replace(/[G]/g, 'B');
        var str2 = readline().replace(/[G]/g, 'B');

        if (str1 === str2) {
            console.log("YES");

        } else {
            console.log("NO");
        }
    }
}

let readline = require("readline");
const { start } = require("repl");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);

  if (input.length === +input[0] * 3 + 1) {
    // call your function here
    solve(input);
    rl.close();
  }
});

// let solve = (input) => {
//   let name = {
//     T: true,
//     i: true,
//     m: true,
//     u: true,
//     r: true,
//   };

//   for (let i = 1; i < input.length; i += 2) {
//     if (+input[i] !== 5) {
//       console.log("NO");
//       continue;
//     } else {
//       let count = 0;
//       for (let j = 0; j < input[i + 1].length; j++) {
//         if (name[input[i + 1][j]]) {
//           count++;
//         }
//       }
//       if (count === 5) {
//         console.log("YES");
//       } else {
//         console.log("NO");
//       }
//     }
//   }
// };

let solve = (input) => {
  for (let i = 1; i < input.length; i += 3) {
    let block1 = input[i + 1];
    let block2 = input[i + 2];
    let identical = true;
    for (let j = 0; j < block1.length; j++) {
      if (block1[j] === block2[j]) continue;
      else if (block1[j] === "B" && block2[j] === "G") continue;
      else if (block1[j] === "G" && block2[j] === "B") continue;
      else {
        identical = false;
      }
    }

    if (identical) {
      console.log("YES");
    } else {
      console.log("NO");
    }
  }
};

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var L = nextCharArray();
		var R = nextCharArray();
		var isOK = true;
		for(var i = 0; i < N; i++){
			if(L[i] != "R"){
				L[i] = "?";
			}
			if(R[i] != "R"){
				R[i] = "?";
			}
			if(L[i] != R[i]){
				isOK = false;
			}
		}
		myout((isOK) ? "Yes" : "No");
	}
}

let fs = require("fs");
let sc = {
    _buf: new Buffer.alloc(1 << 14),
    _bufPos: 0,
    _bufLen: 0,
    _ensure: function ()
    {
        if (this._bufPos === this._bufLen)
        {
            this._bufPos = 0;
            this._bufLen = fs.readSync(0, this._buf, 0, this._buf.length, null);
        }
    },
    _isws: function (ch)
    {
        return ch === 32 || ch === 9 || ch === 10 || ch === 13;
    },
    _islf: function (ch)
    {
        return ch === 10 || ch === 13;
    },
    _peekChar: function ()
    {
        this._ensure();
        return this._bufPos === this._bufLen ? 0 : this._buf[this._bufPos];
    },
    _skipWs: function ()
    {
        while (this._isws(this._peekChar()))
            this._bufPos++;
    },
    _readUntil: function (stop)
    {
        this._ensure();
        if (this._bufPos === this._bufLen)
            throw new Error("eof");
        let start = this._bufPos;
        let before = null;
        for (; ;)
        {
            if (this._bufPos === this._bufLen)
            {
                let len = this._bufPos - start, preLen = (before ? before.length : 0);
                let nbuf = new Buffer(len + preLen);
                if (before)
                    before.copy(nbuf);
                before = nbuf;
                this._buf.copy(before, preLen, start);
                this._ensure();
                start = this._bufPos;
            }
            if (this._bufPos === this._bufLen || stop(this._buf[this._bufPos])) break;
            this._bufPos++;
        }
        if (!before)
            return this._buf.toString("utf8", start, this._bufPos);
        let after = this._buf.slice(start, this._bufPos);
        let res = new Buffer(before.length + after.length);
        before.copy(res);
        after.copy(res, before.length);
        return res.toString();
    },

    nextToken: function ()
    {
        this._skipWs();
        return this._readUntil(this._isws);
    },
    L: function ()
    {
        let line = this._readUntil(this._islf);
        if (this._peekChar() === 13) this._bufPos++;
        if (this._peekChar() === 10) this._bufPos++;
        return line;
    },
    N: function ()
    {
        return +this.nextToken();
    },
    S: function ()
    {
        return this.nextToken();
    }
};

// DO NOT CHANGE TEMPLATE BEFORE

const Def = Number(1e9);

const LowerBound = (arr, val) =>
{
    let ng = -1;
    let ok = arr.length;
    while (ok - ng > 1)
    {
        let med = (ok + ng) / 2 | 0;
        if (arr[med] >= val)
        {
            ok = med;
        }
        else
        {
            ng = med;
        }
    }

    return ok;
}

const ReverseLowerBound = (arr, val) =>
{
    let ng = 0;
    let ok = arr.length;
    while (ok - ng > 1)
    {
        let med = (ok + ng) / 2 | 0;
        if (arr[med] <= val)
        {
            ng = med;
        }
        else
        {
            ok = med;
        }
    }
    // Находит наибольший элемент который меньше или равен val
    return ng;
}

const ReverseUpperBound = (arr, val) =>
{
    let ng = 0;
    let ok = arr.length;
    while (ok - ng > 1)
    {
        let med = (ok + ng) / 2 | 0;
        if (arr[med] < val)
        {
            ng = med;
        }
        else
        {
            ok = med;
        }
    }
    // Находит наибольший элемент который меньше val
    return ng;
}

const UpperBound = (arr, val) =>
{
    let ok = arr.length;
    let ng = -1;
    while (ok - ng > 1)
    {
        let med = (ok + ng) / 2 | 0;
        if (arr[med] > val)
        {
            ok = med;
        }
        else
        {
            ng = med;
        }
    }

    return ok;
}

const Solve = () =>
{
    let n = sc.N();
    let one = [...sc.S()];
    let two = [...sc.S()];

    for (let i = 0; i < n; ++i)
    {
        if (one[i] === 'R' && two[i] !== 'R')
        {
            console.log("NO");
            return;
        }

        if (one[i] !== 'R' && two[i] === 'R')
        {
            console.log("NO");
            return;
        }
    }

    console.log("YES");

}

const main = () =>
{
    let cases = +sc.L();
    while (cases-- > 0) Solve();

    // Solve();
}
main();

const readline = require('readline')

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

function solve(n, sa, sb) {
    for (let i = 0; i < sa.length; i++) {
        if (sa[i] !== sb[i]) {
            if (sa[i] === 'G' && sb[i] === 'B') continue
            if (sa[i] === 'B' && sb[i] === 'G') continue
            return 'NO'
        }
    }
    return 'YES'
}

var t = parseInt(readline());

for (var test = 0; test < t; test++) {
    var n = parseInt(readline());
    var str1 = readline().split('');
    var str2 = readline().split('');

    var ans = 'YES';

    for (var i = 0; i < n; i++) {
        if ((str1[i] === 'R' && str2[i] !== 'R') || str1[i] !== 'R' && str2[i] === 'R') {
            ans = 'NO';
            break;
        }
    }

    print(ans);
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var columns = parseInt(readline());
    var first = readline();
    var second = readline();
    var firstRow = "";
    var secondRow = "";
    for (var j = 0; j < columns; j++)
    {
        firstRow += (first[j] === 'G') ? "B" : first[j];
        secondRow += (second[j] === 'G') ? "B" : second[j];
    }
    (firstRow === secondRow) ? print("YES") : print("NO");
}

var t = parseInt(readline());

while(t--){
    var n = parseInt(readline());
    var r1 = readline().replace(/G/g, "B");
    var r2 = readline().replace(/G/g, "B");

    if(r1 === r2) print("YES"); else print("NO")

}

var t = readline();
for (var  i = 0 ; i < t ; i++){
    var n = readline();
        firstRow = readline().split('').map((e) =>{
        if(e == 'B' || e == 'G'){
            return 1;
        }
        else{
            return e;
        }
         }),
        secondRow = readline().split('').map((e) =>{
            if(e == 'B' || e == 'G'){
                return 1;
            }
            else{
                return e;
            }
             });
    if(firstRow.join('') == secondRow.join('')){
        print("YES");
    }
    else{
        print("NO");
    }
}

// import input from 'input'

var n = +(readline())

for (var i = 0; i < n; i++) {
    var ns = readline()
    var s1 = readline()
    var s2 = readline()

    if (compare(s1, s2)) {
        print("YES")
    } else {
        print("NO")
    }
}

function compare(s1, s2) {
    var s1Pos = s1.split('').map((i, ind) => i === 'R' && ind).filter(x=>x !== false).toString()
    var s2Pos = s2.split('').map((i, ind) => i === 'R' && ind).filter(x=>x !== false).toString()

    return s1Pos === s2Pos
}

var n, a, b;
    var tests = parseInt(readline());
    for (var t=0; t<tests;t++) {
        n = parseInt(readline());
        a = readline();
        b = readline();
        var ans = 'YES';
        for (var i = 0; i < n; i++) {
            var x = a.charAt(i);
            var y = b.charAt(i);
            if (x == y) continue;
            if ((x == 'B' && y == 'G') || (x == 'G' && y == 'B')) continue;
            ans = 'NO';
            break;
        }
        print(ans);
    }

var t = +readline();

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

      var nums = [];
    var t1 = +readline();
    var t2 = readline();
    var t3 = readline();
    print(Colourblindness(t2,t3));

}

function Colourblindness(str1,str2){

    for(var i = 0; i<str1.length; i++){
        if (str1[i] == 'R' && str1[i] != str2[i]){
            return 'NO';
        }
        if (str2[i] == 'R' && str1[i] != str2[i]){
            return 'NO';
        }
    }
    return 'YES'

}

var n = readline();
for(var i=0;i<n;i++){
  var columns = readline();
  var str1 = readline();
  var str2 = readline();
  str1 = str1.replace(/G/g, "B");
  str2 = str2.replace(/G/g, "B");
  if(str1 == str2){
    print("YES");
  } else {
    print("NO");
  }
}

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

let lines = []

const createReadLine = () => {
  i = 0;
  return () => {
    return lines[i++]
  }
}

rl.on('line', line => lines.push(line))
rl.on('close', () => {
  const readLine = createReadLine();
  console.log(readLine().replace(/\G/g, 'B') == readLine().replace(/\G/g, 'B') ? 'YES' : 'NO')
})

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0],e=0,f = false, k = 0, even = 1
    for(j = 1; j <= n *2; j+=even){
        if(j % 3 == 1){
            even=1
            e = lines[j], f = false
        }else{
            k = lines[j].split('')
            g = lines[j + 1].split('')
            for(l = 0; l < e; l++){
                if(k[l] == 'R' && g[l] == 'R' || k[l] == 'G' && g[l] == 'G' || k[l] == 'G' && g[l] == 'B' || k[l] == 'B' && g[l] == 'G' || k[l] == 'B' && g[l] == 'B' ){
                    f = true
                }else{
                    f = false
                    break;
                }
            }
            even =  2
            if(f === true){
                console.log('YES')
            }else{
                console.log('NO')
            }
        }
    }

});


William really likes the cellular automaton called "Game of Life" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing $$$n$$$ cells, with each cell either being alive or dead.Evolution of the array in William's cellular automaton occurs iteratively in the following way:  If the element is dead and it has exactly $$$1$$$ alive neighbor in the current state of the array, then on the next iteration it will become alive. For an element at index $$$i$$$ the neighbors would be elements with indices $$$i - 1$$$ and $$$i + 1$$$. If there is no element at that index, it is considered to be a dead neighbor.  William is a humane person so all alive elements stay alive. Check the note section for examples of the evolution.You are given some initial state of all elements and you need to help William find the state of the array after $$$m$$$ iterations of evolution.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^3, 1 \le m \le 10^9$$$), which are the total number of cells in the array and the number of iterations. The second line of each test case contains a string of length $$$n$$$ made up of characters "0" and "1" and defines the initial state of the array. "1" means a cell is alive and "0" means it is dead. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

In each test case output a string of length $$$n$$$, made up of characters "0" and "1"  — the state of the array after $$$m$$$ iterations of evolution.

NoteSequence of iterations of evolution for the first test case   01000000001  — initial state  11100000011  — first iteration of evolution  11110000111  — second iteration of evolution  11111001111  — third iteration of evolution Sequence of iterations of evolution for the second test case   0110100101  — initial state  1110111101  — first iteration of evolution  1110111101  — second iteration of evolution

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = input.split(EOL)
    const count = parseInt(lines[0]);
    for (let i = 0; i < count; i++) {
        const idx = 1 + i * 2;
        const nm = lines[idx].split(' ');
        const n = parseInt(nm[0]);
        const m = parseInt(nm[1]);
        const state = lines[idx+1];
        console.log(iter(state, n, m));
    }
})

function iter(state, n, m) {
    let result = '';
    for (let i = 0; i < m; i++) {
        let change = false;
        for (let j = 0; j < n; j++) {
            let live_neighbors = 0;
            if (j > 0 && state[j-1] === '1') live_neighbors++;
            if (j+1 < n && state[j+1] === '1') live_neighbors++;
            if (live_neighbors === 1 && state[j] === '0') { result += '1'; change = true }
            else result += state[j];
        }
        state = result;
        result = '';
        if (!change) break;
    }
    return state;
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var M = nextInt();
		var list = nextCharArray();
		while(M > 0){
			var queue = [];
			for(var i = 0; i < N; i++){
				if(list[i] == "1"){
					if(list[i + 1] == "0"){
						if(i < N - 2){
							if(list[i + 2] == "0"){
								queue.push(i + 1);
							}
						}else{
							queue.push(i + 1);
						}
					}
					if(list[i - 1] == "0"){
						if(i > 1){
							if(list[i - 2] == "0"){
								queue.push(i - 1);
							}
						}else{
							queue.push(i - 1);
						}

					}
				}
			}
			if(queue.length == 0){
				break;
			}
			for(var i = 0; i < queue.length; i++){
				list[queue[i]] = "1";
			}
			M--;
		}
		myout(myconv(list, 0));
	}
}
function ArrayDeque(add){
	var queue = {
		L : 0,//next add Area
		R : 0,//next add Area
		map : {},
		unshift : function(V){ return this.addFirst(V); },
		addFirst : function(V){
			this.map[this.L] = V;
			if(this.L == this.R){
				this.R++;
			}
			this.L--;
		},
		shift : function(){ return this.pollFirst(); },
		pollFirst : function(){
			if(this.L == this.R){
				return null;
			}
			var ret = this.map[this.L + 1];
			this.L++;
			if(Math.abs(this.L - this.R) == 1){
				this.R--;
			}
			return ret;
		},
		peekFirst : function(){
			if(this.L == this.R){
				return null;
			}
			return this.map[this.L + 1];
		},
		add : function(V){ return this.addLast(V); },
		push : function(V){ return this.addLast(V); },
		addLast : function(V){
			this.map[this.R] = V;
			if(this.L == this.R){
				this.L--;
			}
			this.R++;
		},
		pop : function(){ return this.pollLast(); },
		pollLast : function(){
			if(this.L == this.R){
				return null;
			}
			var ret = this.map[this.R - 1];
			this.R--;
			if(Math.abs(this.L - this.R) == 1){
				this.L++;
			}
			return ret;
		},
		peekLast : function(){
			if(this.L == this.R){
				return null;
			}
			return this.map[this.R - 1];
		},
		size : function(){
			if(this.L == this.R){
				return 0;
			}else{
				return Math.abs(this.L - this.R) - 1;
			}
		},
		toString : function(){
			var list = [];
			for(var i = this.L + 1; i < this.R; i++){
				list.push(this.map[i]);
			}
			return "[" + list.join(", ") + "]";
		},
		get : function(index){
			if(this.L + 1 + index >= this.R || index < 0){
				return null;
			}else{
				return this.map[this.L + 1 + index];
			}
		},
		set : function(index, V){
			if(this.L + 1 + index >= this.R || index < 0){
				throw 'ArrayIndexOutOfBoundsException can\'t set';
			}else{
				this.map[this.L + 1 + index] = V;
			}
		},
		isEmpty : function(){
			return this.size() == 0;
		},
		clear : function(){
			this.L = 0;
			this.R = 0;
			this.map = {}
		}
	}
	if(add){
		for(var i = 0; i < add.length; i++){
			queue.addLast(add[i]);
		}
	}
	return queue;
}

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function findAllStr(json, map, mapRev, index) {
   mapRev[index] = json;
   if (Array.isArray(json)) {
      for (var i = typeof json[0] === 'string' ? 1 : 0; i < json.length; i++) {
         findAllStr(json[i], map, mapRev, index + '_' + i);
      }
      return;
   }
   if (json && typeof json === 'string') {
      if (map[json]) {
         map[json].push(index);
      } else {
         map[json] = [index];
      }
   }
   return;
}

function solve() {
   var nm = readArray(Number);
   var n = nm[0];
   var m = Math.min(nm[1], n);
   var str = read().split('');
   var nextStr;
   for (var j = 0; j < m; j++) {
      nextStr = '';
      for (var i = 0; i < n; i++) {
         var left = str[i - 1] === '1' ? 1 : 0;
         var right = str[i + 1] === '1' ? 1 : 0;
         nextStr += (str[i] === '1' || left + right === 1) ? '1' : '0';
      }
      str = nextStr;
   }
   write(str);
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

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

let input = ''
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = input.split(EOL)
    const count = parseInt(lines[0]);
    for (let i = 0; i < count; i++) {
        const idx = 1 + i * 2;
        const nm = lines[idx].split(' ');
        const n = parseInt(nm[0]);
        const m = parseInt(nm[1]);
        const state = lines[idx+1];
        console.log(iter(state, n, m));
    }
})

function iter(state, n, m) {
    let result = '';
    for (let i = 0; i < m; i++) {
        let change = false;
        for (let j = 0; j < n; j++) {
            let live_neighbors = 0;
            if (j > 0 && state[j-1] === '1') live_neighbors++;
            if (j+1 < n && state[j+1] === '1') live_neighbors++;
            if (live_neighbors === 1) { result += '1'; change = true }
            else result += state[j];
        }
        if (!change) break;
    }
    return result;
}


Peter decided to wish happy birthday to his friend from Australia and send him a card. To make his present more mysterious, he decided to make a chain. Chain here is such a sequence of envelopes A = {a1,  a2,  ...,  an}, where the width and the height of the i-th envelope is strictly higher than the width and the height of the (i  -  1)-th envelope respectively. Chain size is the number of envelopes in the chain. Peter wants to make the chain of the maximum size from the envelopes he has, the chain should be such, that he'll be able to put a card into it. The card fits into the chain if its width and height is lower than the width and the height of the smallest envelope in the chain respectively. It's forbidden to turn the card and the envelopes. Peter has very many envelopes and very little time, this hard task is entrusted to you.

The first line contains integers n, w, h (1  ≤ n ≤ 5000, 1 ≤ w,  h  ≤ 106) — amount of envelopes Peter has, the card width and height respectively. Then there follow n lines, each of them contains two integer numbers wi and hi — width and height of the i-th envelope (1 ≤ wi,  hi ≤ 106).

In the first line print the maximum chain size. In the second line print the numbers of the envelopes (separated by space), forming the required chain, starting with the number of the smallest envelope. Remember, please, that the card should fit into the smallest envelope. If the chain of maximum size is not unique, print any of the answers. If the card does not fit into any of the envelopes, print number 0 in the single line.

var line = readline().split(' ').map( function(v){ return parseInt( v ); } );

var n = line[0];
var w = line[1];
var h = line[2];

var c = [];
for( var i=0; i<n; i++){
	line = readline().split(' ');
	c.push({
		w: parseInt( line[0] ),
		h: parseInt( line[1] ),
		m: 0,
		c: -1,
		i: i
	});
}

c.sort(function(a, b){
	if(a.w == b.w){
		return a.h>b.h ? 1 : -1;
	}else{
		return a.w>b.w ? 1 : -1;
	}
});
// print(c)
var max = 0;
var maxi = -1;
for( i=0; i<n; i++ ){
	var ci = c[i];
	// print('---');print(ci.m);

	if(  ci.w>w && ci.h>h ){
		if(ci.m+1>max){
			max=ci.m+1;
			maxi=i;
		}
		for(var j=i; j<n; j++){
			var cj=c[j];

			if( cj.w>ci.w && cj.h>ci.h && cj.m < ci.m+1){

				cj.m = ci.m+1;
				cj.c = i;
				if(cj.m>max){
					max=cj.m;
					maxi=j;
				}
			}
		};
	}
}

if(maxi != -1){
	print(max);

	var p = []
	for( i = maxi; c[i]; i = c[i].c){
		p.push( c[i].i+1 );
	}
	print( p.reverse().join(' ') );
}else{
	print(0)
}

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var numEnvelopes = integers[0],
		width0 = integers[1], height0 = integers[2];

	var envelopes = [];

	for (var i = 0; i < numEnvelopes; i += 1) {
		var integers = tokenizeIntegers(readline());
		var width = integers[0], height = integers[1];
		if (width <= width0 || height <= height0) {
			continue;
		}

		envelope = { width: width, height: height, id: i+1 };
		envelopes.push(envelope);
	}

	if (envelopes.length == 0) {
		print(0);
		return;
	}

	envelopes.sort(function(a, b) {
		if (a.width != b.width) {
			return a.width-b.width;
		}
		return a.height-b.height;
	});

	envelopes.unshift({ width: 0, height: 0, id: 0, depth: 0 });

	var maxDepth = 0, maxEnvelope;

	for (var i = 0; i < envelopes.length; i += 1) {
		var b = envelopes[i];
		b.depth = 0;
		for (var j = 0; j < i; j += 1) {
			var a = envelopes[j];
			if (a.width == b.width || a.height >= b.height) {
				continue;
			}
			if (b.depth < a.depth+1) {
				b.depth = a.depth+1;
				b.parent = a;
			}
		}
		if (b.depth > maxDepth) {
			maxDepth = b.depth;
			maxEnvelope = b;
		}
	}

	var envelope = maxEnvelope;
	var chain = [];
	while (envelope.depth > 0) {
		chain.unshift(envelope.id);
		envelope = envelope.parent;
	}

	print(chain.length+"\n"+chain.join(" "));

}

main();

'use strict';
var input = readline().split(' ').map(i => +i);
var n = input[0], w = input[1], h = input[2];

var cache = { fits: {} };
var envs = new Array(n);
for (var i = 0; i < n; i++) {
    var l = readline().split(' ').map(i => +i);
    envs[i] = [...l, i]; // w, h, i
}

envs = envs.filter(v => v[0] > w && v[1] > h).sort((a, b) => {
    if (a[0] == b[0]) return a[1] - b[1]; // order by widht, then height
    return a[0] - b[0];
});

function doDP(envs) {
    if (!envs.length) return [];
    // -- DP
    var dp = new Array(envs.length);
    dp[0] = { max: 1, i: 0 };
    var best = 0;
    for (var i = 1; i < envs.length; i++) {
        var envI = envs[i];
        var max = 0;
        var maxJ = -1;
        for (var j = 0; j < i; j++) {
            var envJ = envs[j];
            var fits = envI[0] > envJ[0] && envI[1] > envJ[1];
            if (fits && dp[j].max > max) {
                max = dp[j].max;
                maxJ = j;
            }
        }
        dp[i] = { max: max + 1, i: maxJ };
        if (dp[i].max > dp[best].max) {
            best = i;
        }
    }
    // - end DP

    // build path from indexes in reverse
    var index = best;
    var path = [];

    // print(dp, index)

    while (index > 0) {
        path.unshift(envs[index][2] + 1);
        index = dp[index].i
    }
    if (index === 0) {
        path.unshift(envs[index][2] + 1); // 0
    }
    return path;
}

const p = doDP(envs);

print(p.length);
if (p.length) {
    print(p.join(' '));
}

var line = readline().split(' ').map( function(v){ return parseInt( v ); } );

var n = line[0];
var w = line[1];
var h = line[2];

var c = [];
for( var i=0; i<n; i++){
	line = readline().split(' ');
	c.push({
		w: parseInt( line[0] ),
		h: parseInt( line[1] ),
		m: 0,
		c: -1,
		i: i
	});
}

c.sort(function(a, b){
	if(a.w == b.w){
		return a.h>b.h ? 1 : -1;
	}else{
		return a.w>b.w ? 1 : -1;
	}
});
// print(c)
var max = 0;
var maxi = 0;
for( i=0; i<n; i++ ){
	var ci = c[i];
	// print('---');print(ci.m);

	if(  ci.w>w && ci.h>h ){

		for(var j=i; j<n; j++){
			var cj=c[j];

			if( cj.w>ci.w && cj.h>ci.h && cj.m < ci.m+1){

				cj.m = ci.m+1;
				cj.c = i;
				if(cj.m>max){
					max=cj.m;
					maxi=j;
				}
			}
		};
	}
}
//print(c);
if(max>0){
	print(max+1);

	var p = []
	for( i = maxi; c[i]; i = c[i].c){
		p.push( c[i].i+1 );
	}
	print( p.reverse().join(' ') );
}else{
	print(0)
}

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var numEnvelopes = integers[0],
		width0 = integers[1], height0 = integers[2];

	var envelopes = [];

	for (var i = 0; i < numEnvelopes; i += 1) {
		var integers = tokenizeIntegers(readline());
		var width = integers[0], height = integers[1];
		if (width <= width0 || height <= height0) {
			continue;
		}

		envelope = { width: width, height: height, children: [],
				isChild: false, id: i+1 };
		envelopes.push(envelope);

		for (j = envelopes.length-2; j >= 0; j -= 1) {
			var candidate = envelopes[j];
			if (envelope.width > candidate.width &&
					envelope.height > candidate.height) {
				envelope.children.push(candidate);
				candidate.isChild = true;
			}
			if (candidate.width > envelope.width &&
					candidate.height > envelope.height) {
				candidate.children.push(envelope);
				envelope.isChild = true;
			}
		}
	}

	if (envelopes.length == 0) {
		print(0);
		return;
	}

	var order = [];

	function descend(envelope) {
		if (envelope.visited) {
			return;
		}
		envelope.visited = true;
		for (var i = 0; i < envelope.children.length; i += 1) {
			descend(envelope.children[i]);
		}
		order.unshift(envelope);
	}

	for (var i = 0; i < envelopes.length; i += 1) {
		descend(envelopes[i]);
	}

	write(order[0].id);
	for (var i = 1; i < order.length; i += 1) {
		write(" "+order[i].id);
	}
	print(" ("+order.length+")");

	var maxDepth = -1, maxEnvelope;

	for (var i = 0; i < order.length; i += 1) {
		var envelope = order[i];
		if (envelope.bestDepth === undefined) {
			var depth = envelope.bestDepth = 0;
		}
		else {
			var depth = envelope.bestDepth;
		}
		if (depth > maxDepth) {
			maxDepth = depth;
			maxEnvelope = envelope;
		}
		for (var j = 0; j < envelope.children.length; j += 1) {
			var child = envelope.children[j];
			if (child.bestDepth >= depth+1) {
				continue;
			}
			child.bestDepth = depth+1;
			child.bestParent = envelope;
		}
	}

	var envelope = maxEnvelope;
	var chain = [envelope.id];
	while (envelope.bestDepth > 0) {
		envelope = envelope.bestParent;
		chain.push(envelope.id);
	}

	print(chain.length+"\n"+chain.join(" "));

}

main();

'use strict';
var input = readline().split(' ').map(i => +i);
var n = input[0], w = input[1], h = input[2];

var cache = { fits: {} };
var envs = new Array(n);
for (var i = 0; i < n; i++) {
    var l = readline().split(' ').map(i => +i);
    envs[i] = [...l, i]; // w, h, i
}

envs = envs.filter(v => v[0] > w && v[1] > h).sort((a, b) => {
    if (a[0] == b[0]) return a[1] - b[1]; // order by widht, then height
    return a[0] - b[0];
});

// -- DP
var dp = new Array(envs.length);
// dp[0] = { max: 1, i: -1 };
var best = 0;
for (var i = 0; i < envs.length; i++) {
    var env = envs[i];
    var max = -1;
    dp[i] = { max: 1, i: 0 };
    for (var j = 0; j < i; j++) {
        var envJ = envs[j];
        var fits = env[0] > envJ[0] && env[1] > envJ[1];
        if (fits && dp[j].max >= max) {
            dp[i] = { max: dp[j].max + 1, i: j }
        }
    }
    if (dp[i] && dp[i].max > dp[best].max) {
        best = i;
    }
}
// - end DP

// build path from indexes in reverse
var index = best;
var path = [];

while (index > 0) {
    path.unshift(envs[index][2] + 1);
    index = dp[index].i
}
if (envs.length) {
    path.unshift(envs[index][2] + 1); // 0
    print(path.length);
    print(path.join(' '));
} else {
    print('0');
}

'use strict';
var input = readline().split(' ').map(i => +i);
var n = input[0], w = input[1], h = input[2];

var cache = { fits: {} };
var envs = new Array(n);
for (var i = 0; i < n; i++) {
    var l = readline().split(' ').map(i => +i);
    envs[i] = [...l, i]; // w, h, i
}

envs = envs.filter(v => v[0] > w && v[1] > h).sort((a, b) => {
    if (a[0] == b[0]) return a[1] - b[1]; // order by widht, then height
    return a[0] - b[0];
});

function doDP(envs) {
    if (!envs.length) return [];
    // -- DP
    var dp = new Array(envs.length);
    dp[0] = { max: 1, i: 0 };
    var best = 0;
    for (var i = 1; i < envs.length; i++) {
        var envI = envs[i];
        var max = 0; var maxIx;
        for (var j = 0; j < i; j++) {
            var envJ = envs[j];
            var fits = envI[0] > envJ[0] && envI[1] > envJ[1];
            if (fits && dp[j].max + 1 > max) {
                max = dp[j].max + 1;
                maxIx = j;
            }
        }
        dp[i] = { max: max, i: maxIx };
        if (dp[i].max > dp[best].max) {
            best = i;
        }
    }
    // - end DP

    // build path from indexes in reverse
    var index = best;
    var path = [];

    // print(dp, index)

    while (index > 0) {
        path.unshift(envs[index][2] + 1);
        index = dp[index].i
    }
    if (index === 0) {
        path.unshift(envs[index][2] + 1); // 0
    }
    return path;
}

const p = doDP(envs);

print(p.length);
if (p.length) {
    print(p.join(' '));
}

'use strict';
var input = readline().split(' ').map(i => +i);
var n = input[0], w = input[1], h = input[2];

var cache = { fits: {} };
var envs = new Array(n);
for (var i = 0; i < n; i++) {
    var l = readline().split(' ').map(i => +i);
    envs[i] = [...l, i]; // w, h, i
}

envs = envs.filter(v => v[0] > w && v[1] > h).sort((a, b) => {
    if (a[0] == b[0]) return a[1] - b[1]; // order by widht, then height
    return a[0] - b[0];
});

function doDP(envs) {
    if (!envs.length) return [];
    // -- DP
    var dp = new Array(envs.length);
    dp[0] = { max: 1, i: -1 };
    var best = 0;
    for (var i = 1; i < envs.length; i++) {
        var envI = envs[i];
        var max = -1;
        dp[i] = { max: 0, i: -1 };
        for (var j = 0; j < i; j++) {
            var envJ = envs[j];
            var fits = envI[0] > envJ[0] && envI[1] > envJ[1];
            if (fits && dp[j].max + 1 > dp[i].max) {
                dp[i] = { max: dp[j].max + 1, i: j };
            }
        }
        if (dp[i].max > dp[best].max) {
            best = i;
        }
    }
    // - end DP

    // build path from indexes in reverse
    var index = best;
    var path = [];

    while (index >= 0) {
        path.unshift(envs[index][2] + 1);
        index = dp[index].i
    }
    if (index === 0) {
        path.unshift(envs[index][2] + 1); // 0
    }
    return path;
}

const p = doDP(envs);

print(p.length);
if (p.length) {
    print(p.join(' '));
}

'use strict';
var input = readline().split(' ').map(i => +i);
var n = input[0], w = input[1], h = input[2];

var cache = {fits: {}};
var cards = new Array(n);
for (var i = 0; i < n; i++) {
    var l = readline().split(' ').map(i => +i);
    // var wi = l[0], hi = l[1];
    l.push(i);
    cards[i] = l;
}

cards = cards.filter(v => v[0] > w && v[1] > h).sort((a, b) => {
    if (a[0] == b[0]) return a[1] - b[1]; // order by widht, then height
    return a[0] - b[0];
});

function getChain(arr, w, h, ix) {
    if (ix >= arr.length) {
        return [];
    }
    var key = w + ':' + h + ':' + ix;
    if (cache[key]) {
        print('cached', key);
        return cache[key];
    }
    print('not cached', key);
    // if(car)
    var c = arr[ix];
    var fits = c[0] > w && c[1] > h;
    var res1 = [], res2 = [], res;
    res1 = getChain(arr, w, h, ix + 1);

    if (fits) {
        res2 = cache.fits[ix] || [ix, ...getChain(arr, c[0], c[1], ix + 1)]
        cache.fits[ix] = res2;
        // res2.unshift(ix);
    }
    if (res1.length > res2.length) {
        res = res1;
    } else {
        res = res2;
    }
    cache[key] = res;
    return res;

}
var res = getChain(cards, w, h, 0);

print(res.length);
print(res.map(c => cards[c][2] + 1).join(' '));

'use strict';
var input = readline().split(' ').map(i => +i);
var n = input[0], w = input[1], h = input[2];

var cache = { fits: {} };
var envs = new Array(n);
for (var i = 0; i < n; i++) {
    var l = readline().split(' ').map(i => +i);
    envs[i] = [...l, i]; // w, h, i
}

envs = envs.filter(v => v[0] > w && v[1] > h).sort((a, b) => {
    if (a[0] == b[0]) return a[1] - b[1]; // order by widht, then height
    return a[0] - b[0];
});

// -- DP
var dp = new Array(envs.length);
dp[0] = { max: 1, i: -1 };
var best = 0;
for (var i = 1; i < envs.length; i++) {
    var env = envs[i];
    var max = -1;
    dp[i] = { max: 0, i: 0 };
    for (var j = 0; j < i; j++) {
        var envJ = envs[j];
        var fits = env[0] > envJ[0] && env[1] > envJ[1];
        if (fits && dp[j].max >= dp[i].max) {
            dp[i] = { max: dp[j].max + 1, i: j };
        }
    }
    if (dp[i] && dp[i].max > dp[best].max) {
        best = i;
    }
}
// - end DP

// build path from indexes in reverse
var index = best;
var path = [];

while (index > 0) {
    path.unshift(envs[index][2] + 1);
    index = dp[index].i
}
if (envs.length) {
    path.unshift(envs[index][2] + 1); // 0
    print(path.length);
    print(path.join(' '));
} else {
    print('0');
}

'use strict';
var input = readline().split(' ').map(i => +i);
var n = input[0], w = input[1], h = input[2];

var cache = { fits: {} };
var envs = new Array(n);
for (var i = 0; i < n; i++) {
    var l = readline().split(' ').map(i => +i);
    envs[i] = [...l, i]; // w, h, i
}

envs = envs.filter(v => v[0] > w && v[1] > h).sort((a, b) => {
    if (a[0] == b[0]) return a[1] - b[1]; // order by widht, then height
    return a[0] - b[0];
});

function doDP(envs) {
    if (!envs.length) return [];
    // -- DP
    var dp = new Array(envs.length);
    dp[0] = { max: 1, i: 0 };
    var best = 0;
    for (var i = 1; i < envs.length; i++) {
        var envI = envs[i];
        var max = 0;
        var maxJ = 0;
        for (var j = 0; j < i; j++) {
            var envJ = envs[j];
            var fits = envI[0] > envJ[0] && envI[1] > envJ[1];
            if (fits && dp[j].max > max) {
                max = dp[j].max;
                maxJ = j;
            }
        }
        dp[i] = { max: max + 1, i: maxJ };
        if (dp[i].max > dp[best].max) {
            best = i;
        }
    }
    // - end DP

    // build path from indexes in reverse
    var index = best;
    var path = [];

    // print(dp, index)

    while (index > 0) {
        path.unshift(envs[index][2] + 1);
        index = dp[index].i
    }
    if (index === 0) {
        path.unshift(envs[index][2] + 1); // 0
    }
    return path;
}

const p = doDP(envs);

print(p.length);
if (p.length) {
    print(p.join(' '));
}

'use strict';
var input = readline().split(' ').map(i => +i);
var n = input[0], w = input[1], h = input[2];

var cache = { fits: {} };
var envs = new Array(n);
for (var i = 0; i < n; i++) {
    var l = readline().split(' ').map(i => +i);
    envs[i] = [...l, i]; // w, h, i
}

envs = envs.filter(v => v[0] > w && v[1] > h).sort((a, b) => {
    if (a[0] == b[0]) return a[1] - b[1]; // order by widht, then height
    return a[0] - b[0];
});

function doDP(envs) {
    if (!envs.length) return [];
    // -- DP
    var dp = new Array(envs.length);
    dp[0] = { max: 1, i: 0 };
    var best = 0;
    for (var i = 1; i < envs.length; i++) {
        var envI = envs[i];
        dp[i] = { max: 0, i: -1 };
        for (var j = 0; j < i; j++) {
            var envJ = envs[j];
            var fits = envI[0] > envJ[0] && envI[1] > envJ[1];
            if (fits && dp[j].max + 1 > dp[i].max) {
                dp[i] = { max: dp[j].max + 1, i: j };
            }
        }
        if (dp[i].max > dp[best].max) {
            best = i;
        }
    }
    // - end DP

    // build path from indexes in reverse
    var index = best;
    var path = [];

    // print(dp, index)

    while (index > 0) {
        path.unshift(envs[index][2] + 1);
        index = dp[index].i
    }
    if (index === 0) {
        path.unshift(envs[index][2] + 1); // 0
    }
    return path;
}

const p = doDP(envs);

print(p.length);
if (p.length) {
    print(p.join(' '));
}


Consider a sequence of digits of length $$$2^k$$$ $$$[a_1, a_2, \ldots, a_{2^k}]$$$. We perform the following operation with it: replace pairs $$$(a_{2i+1}, a_{2i+2})$$$ with $$$(a_{2i+1} + a_{2i+2})\bmod 10$$$ for $$$0\le i<2^{k-1}$$$. For every $$$i$$$ where $$$a_{2i+1} + a_{2i+2}\ge 10$$$ we get a candy! As a result, we will get a sequence of length $$$2^{k-1}$$$.Less formally, we partition sequence of length $$$2^k$$$ into $$$2^{k-1}$$$ pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth $$$\ldots$$$, the last pair consists of the ($$$2^k-1$$$)-th and ($$$2^k$$$)-th numbers. For every pair such that sum of numbers in it is at least $$$10$$$, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by $$$10$$$ (and don't change the order of the numbers).Perform this operation with a resulting array until it becomes of length $$$1$$$. Let $$$f([a_1, a_2, \ldots, a_{2^k}])$$$ denote the number of candies we get in this process. For example: if the starting sequence is $$$[8, 7, 3, 1, 7, 0, 9, 4]$$$ then:After the first operation the sequence becomes $$$[(8 + 7)\bmod 10, (3 + 1)\bmod 10, (7 + 0)\bmod 10, (9 + 4)\bmod 10]$$$ $$$=$$$ $$$[5, 4, 7, 3]$$$, and we get $$$2$$$ candies as $$$8 + 7 \ge 10$$$ and $$$9 + 4 \ge 10$$$.After the second operation the sequence becomes $$$[(5 + 4)\bmod 10, (7 + 3)\bmod 10]$$$ $$$=$$$ $$$[9, 0]$$$, and we get one more candy as $$$7 + 3 \ge 10$$$. After the final operation sequence becomes $$$[(9 + 0) \bmod 10]$$$ $$$=$$$ $$$[9]$$$. Therefore, $$$f([8, 7, 3, 1, 7, 0, 9, 4]) = 3$$$ as we got $$$3$$$ candies in total.You are given a sequence of digits of length $$$n$$$ $$$s_1, s_2, \ldots s_n$$$. You have to answer $$$q$$$ queries of the form $$$(l_i, r_i)$$$, where for $$$i$$$-th query you have to output $$$f([s_{l_i}, s_{l_i+1}, \ldots, s_{r_i}])$$$. It is guaranteed that $$$r_i-l_i+1$$$ is of form $$$2^k$$$ for some nonnegative integer $$$k$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the sequence. The second line contains $$$n$$$ digits $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \le s_i \le 9$$$). The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$, $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — $$$i$$$-th query. It is guaranteed that $$$r_i-l_i+1$$$ is a nonnegative integer power of $$$2$$$.

Output $$$q$$$ lines, in $$$i$$$-th line output single integer — $$$f([s_{l_i}, s_{l_i + 1}, \ldots, s_{r_i}])$$$, answer to the $$$i$$$-th query.

NoteThe first example illustrates an example from the statement.$$$f([7, 3, 1, 7]) = 1$$$: sequence of operations is $$$[7, 3, 1, 7] \to [(7 + 3)\bmod 10, (1 + 7)\bmod 10]$$$ $$$=$$$ $$$[0, 8]$$$ and one candy as $$$7 + 3 \ge 10$$$ $$$\to$$$ $$$[(0 + 8) \bmod 10]$$$ $$$=$$$ $$$[8]$$$, so we get only $$$1$$$ candy.$$$f([9]) = 0$$$ as we don't perform operations with it.

var n1 = readline();
var currSum = 0;
var arr = readline().split(' ').map(item => currSum += parseInt(item));
var n2 = +readline();
for (var i = 0; i < n2; i++) {
  var part = readline().split(' ').map(item => +item - 1);
  var sum = part[0] === 0 ? arr[part[1]] : arr[part[1]] - arr[part[0] - 1];
  print(parseInt(sum / 10));
}

readline();
var arr = readline().split(' ').map(item => +item);
var n = +readline();
for (var i = 0; i < n; i++) {
  var part = readline().split(' ').map(item => +item);
  print(parseInt(arr.slice(part[0]--, part[1]).reduce((prev, curr) => prev + curr, 0) / 10));
}

readline();
var arr = readline().split(' ').map(item => +item);
var n = +readline();
for (var i = 0; i < n; i++) {
  var part = readline().split(' ').map(item => +item);
  print(parseInt(arr.slice(...part).reduce((prev, curr) => prev + curr, 0) / 10));
}


This is an interactive problem.Jury initially had a sequence $$$a$$$ of length $$$n$$$, such that $$$a_i = i$$$.The jury chose three integers $$$i$$$, $$$j$$$, $$$k$$$, such that $$$1 \leq i < j < k \leq n$$$, $$$j - i > 1$$$. After that, Jury reversed subsegments $$$[i, j - 1]$$$ and $$$[j, k]$$$ of the sequence $$$a$$$.Reversing a subsegment $$$[l, r]$$$ of the sequence $$$a$$$ means reversing the order of elements $$$a_l, a_{l+1}, \ldots, a_r$$$ in the sequence, i. e. $$$a_l$$$ is swapped with $$$a_r$$$, $$$a_{l+1}$$$ is swapped with $$$a_{r-1}$$$, etc.You are given the number $$$n$$$ and you should find $$$i$$$, $$$j$$$, $$$k$$$ after asking some questions.In one question you can choose two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) and ask the number of inversions on the subsegment $$$[l, r]$$$ of the sequence $$$a$$$. You will be given the number of pairs $$$(i, j)$$$ such that $$$l \leq i < j \leq r$$$, and $$$a_i > a_j$$$.Find the chosen numbers $$$i$$$, $$$j$$$, $$$k$$$ after at most $$$40$$$ questions.The numbers $$$i$$$, $$$j$$$, and $$$k$$$ are fixed before the start of your program and do not depend on your queries.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Description of the test cases follows. The single line of each test case contains a single integer $$$n$$$ ($$$4 \leq n \leq 10^9$$$). After reading it you should start an interaction process by asking questions for that test case. After giving an answer you should:   Terminate your program if that is the last test case.  Proceed to the next test case otherwise.

var readline = require('readline');

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

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

function* main() {
    let input

    input = yield 1
    var t = +input
    for (var i = 0; i < t; i++) {
        input = yield 1
        yield* solve(BigInt(input))
    }
    process.exit(0)
}

function* solve(n) {
  const total = yield* ask(1n, n)

  const l = yield* binarySearch(1n, n, function* (x) {
    const ps = yield* ask(x, n)
    return ps === total
  })
  const count = yield* ask(l + 1n, n)
  // middle - l - 1 = total - count
  const middle = total - count + l + 1n
// console.log(total, count)

  const r = middle - 1n + getRange(total - getPairs(middle - l))

  answer(l, middle, r)
}
// console.log(getPairs(2n), 1n * 2n)
// console.log(getRange(1n))
function getRange(ps) {
  // return Math.ceil(Math.sqrt(ps * 2))
  const r = bs(1n, 1000000000n, x => getPairs(x) < ps) + 1n
// console.log(ps, r)
  return r
}
function getPairs(n) {
  return n * (n - 1n) / 2n
}
function* ask(l, r) {
  console.log(`? ${l} ${r}`)
  return BigInt(yield 1)
}
function answer(l, k, r) {
  console.log(`! ${l} ${k} ${r}`)
}
function bs(l, r, fn) {
    while (l <= r) {
        const m = (l + r) / 2n
        // const m = Math.floor((l + r) / 2)
        const ok = fn(m)
      // console.log(m, ok)
        if (ok) {
            l = m + 1n
        } else {
            r = m - 1n
        }
    }
    return r
}
function* binarySearch(l, r, fn) {
    while (l <= r) {
        const m = (l + r) / 2n
        // const m = Math.floor((l + r) / 2)
        const ok = yield* fn(m)
        if (ok) {
            l = m + 1n
        } else {
            r = m - 1n
        }
    }
    return r
}

var readline = require('readline');

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

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

function* main() {
    let input

    input = yield 1
    var t = +input
    for (var i = 0; i < t; i++) {
        input = yield 1
        const n = +input
        yield* solve(n)
    }
    process.exit(0)
}

function* solve(n) {
  const total = yield* ask(1, n)

  const l = yield* binarySearch(1, n, function* (x) {
    const ps = yield* ask(x, n)
    return ps === total
  })
  const count = yield* ask(l + 1, n)
  // middle - l - 1 = total - count
  const middle = total - count + l + 1
// console.log(total, count)

  const r = middle - 1 + getRange(total - getPairs(middle - l))

  answer(l, middle, r)
}
function getRange(ps) {
  return Math.ceil(Math.sqrt(ps * 2))
}
function getPairs(n) {
  return n * (n - 1) / 2
}
function* ask(l, r) {
  console.log(`? ${l} ${r}`)
  return yield 1
}
function answer(l, k, r) {
  console.log(`! ${l} ${k} ${r}`)
}
function* binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        const ok = yield* fn(m)
        if (ok) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}


Sereja loves integer sequences very much. He especially likes stairs.Sequence a1, a2, ..., a|a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met: a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|.For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't.Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?

The first line contains integer m (1 ≤ m ≤ 105) — the number of Sereja's cards. The second line contains m integers bi (1 ≤ bi ≤ 5000) — the numbers on the Sereja's cards.

In the first line print the number of cards you can put on the table. In the second line print the resulting stairs.

var m = parseInt( readline() );
var a = readline().split(' ').map(function(v){ return +v; });

a.sort(function(a,b){ return a===b?0: a>b?1:-1; });

var left = [];
var right = [];
var p = left;
for(var i=0; i<m; i++){
	if( left[left.length-1] !== a[i] ){
		left.push( a[i] );
	}else if( right[right.length-1] !== a[i]){
		right.push( a[i] );
	}
}

right.reverse();
if( left[left.length-1] === right[0] ){
	left.pop();
}
left = left.concat(right)

print(left.length);
print(left.join(' '));

var n = Number(readline().split());
var A = readline().split(' ').map((x)=>Number(x));
var H = [];

for(var i=1; i<=5000; i++)
H[i]=0;

for(var x of A)
H[x]++;

var ats= [];

for(var i=1; i<=5000; i++)
if(H[i] > 0)
{
H[i]--;
ats.push(i);
}

for(var i=5000; i>=1; i--)
if(H[i] > 0 && ats[ats.length-1]!=i)
{
H[i]--;
ats.push(i);
}

print(ats.length);
var res = "";
for(var x of ats)
res+=x+" ";
print(res);

;(function () {
	print(function (n, a) {
		var b = a.filter(function (e, i, a) { return i === a.lastIndexOf(e); }).sort(function (a, b) { return a - b; }), t = [];

		for (var i = 0, _i = b.length, k; i < _i; i++)
			if ((k = a.indexOf(b[i])) !== -1) {
				a[k] = -1; t.push(b[i]);
			}

		for (var i = b.length - 2; i > -1; i--)
			if ((k = a.indexOf(b[i])) !== -1) {
				a[k] = -1; t.push(b[i]);
			}

		return t.length + '\n' + t.join(' ');
	}.apply(null, [+readline()].concat([readline().split(' ').map(Number)])));
}).call(this);

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var numCards = integers[0];

	var cards = tokenizeIntegers(readline());
	var counts = {};
	var values = [];
	for (var i = 0; i < cards.length; i += 1) {
		var card = cards[i];
		if (counts[card] === undefined) {
			counts[card] = 1;
			values.push(card);
		}
		else {
			counts[cards[i]] += 1;
		}
	}

	values.sort(function(a, b) {
		return a-b;
	});

	var tail = [];
	for (var i = values.length-2; i >= 0; i -= 1) {
		if (counts[values[i]] > 1) {
			tail.push(values[i]);
		}
	}

	print(values.length+tail.length);
	print(values.join(' '), tail.join(' '));
}

main();

var
    num      = parseInt(readline()),
    arr      = readline().split(" "),
    map      = {},
    map2     = {},
    left     = [],
    right    = []
;

for(var i in arr) {
    arr[i] = parseInt(arr[i]);
    var index = arr[i];
    if (!map[index]) {
        map[index] = 1;
        left.push(index);
    } else {
        if (map2[index]) continue;
        right.push(index);
        map2[index] = 1;
    }
}

left.sort(function(a, b){if(a == b) return 0; return a < b ? -1 : 1})
right.sort(function(a, b){if(a == b) return 0; return a < b ? -1 : 1});
right.reverse();

if (right.length && left.length) {
    if (right[0] == left[left.length -1]) right.shift();
}

print(left.length + right.length);
print(left.join(" ") + (right.length > 0 ? " " + right.join(" ") : ""));

var m = parseInt( readline() );
var a = readline().split(' ').map(function(v){ return +v; });

a.sort(function(a,b){ return a===b?0: a>b?1:-1; });

var left = [];
var right = [];
var p = left;
for(var i=0; i<m; i++){
	if( left[left.length-1] !== a[i] ){
		left.push( a[i] );
	}else if( right[right.length-1] !== a[i]){
		right.push( a[i] );
	}
}

right.reverse();
if( left[left.length-1] === right[0] ){
	left.pop();
}
left = left.concat(right)

print(left.join(' '));


Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.

The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost. It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.

In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes). In the second line print the state of server b in the similar format.

NoteConsider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.

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

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

  const [t, x, y] = d.split(' ').map(Number);

  if (t === 1) {
    a += x;
    maxA += 10;
  }
  else {
    b += x;
    maxB += 10;
  }

  c++;
});

rl.on('close', () => {
  if (a < maxA - a) {
    console.log('DEAD');
  }
  else {
    console.log('LIVE');
  }

  if (b < maxB - b) {
    console.log('DEAD');
  }
  else {
    console.log('LIVE');
  }
});

print(function(n) {

	var i, cnt = [0, 0],
		sum = [0, 0];
	for (i = 0; i < n; i++)
		readline().split(' ', 2).map(Number).reduce(function(t, a) {
			cnt[t - 1]++;
			sum[t - 1] += a;
		});

	return sum.map(function(v, i) {
		return v >= cnt[i] * 5 ? 'LIVE' : 'DEAD';
	}).join('\n');

} .apply(0, readline().split(' ').map(Number)));

;(function () {
	print(function (n) {
		var s = [[0, 0], [0, 0]];
		while (n--) {
			var l = readline().split(' ').map(Number),
				k = l[0] === 1 ? 0 : 1;

			s[k] = [s[k][0] + l[1], s[k][1] + l[2]];
		}

		return s.map(function (e) { return e[0] >= e[1] ? 'LIVE' : 'DEAD' }).join('\n');
	}(+readline()));
}).call(this);

function imp()
{
    var n = parseInt(readline());
    var a_count_x = 0, b_count_x = 0;
    var a_count_y = 0, b_count_y = 0;

    for(var i=1;i<=n;i++)
    {
        var line = readline().split(" ");
        if(line[0]=='1')
        {
            a_count_x += parseInt(line[1]);
            a_count_y += parseInt(line[2]);
        }
        else
        {
            b_count_x += parseInt(line[1]);
            b_count_y += parseInt(line[2]);
        }
    }
    if(a_count_x>=a_count_y)
        print("LIVE");
    else
        print("DEAD");

    if(b_count_x>=b_count_y)
        print("LIVE");
    else
        print("DEAD");
}
imp();

// ################# //
// 14th October 2019 //
// ################# //

// ########################################################## //
// For storing succesfully received packets for each server.
var serverACount = 0,serverBCount = 0;
// For Storing number of pings made to each server.
var serverAPings = 0,serverBPings = 0;
// Computing packet counts for both servers.
var commandCount = parseInt(readline());
for(var i = 0; i<commandCount;++i){
  interim = readline().split(" ").map(function(e){
     return parseInt(e);
  });
  interim[0] == 1? serverAPings++:serverBPings++;
  interim[0] == 1? serverACount+=interim[1]:
    serverBCount+=interim[1];
}
// Solution.
serverACount>=(10*serverAPings)/2 ? print('LIVE'):
  print('DEAD');
serverBCount>=(10*serverBPings)/2 ? print('LIVE'):
  print('DEAD');
// ########################################################## //

print(function(n) {

	var i, cnt = [0, 0],
		sum = [0, 0];
	for (i = 0; i < n; i++)
		readline().split(' ', 2).reduce(function(t, a) {
			cnt[t - 1]++;
			sum[t - 1] += a;
		});

	return sum.map(function(v, i) {
		return v >= cnt[i] * 5 ? 'LIVE' : 'DEAD';
	}).join('\n');

} .apply(0, readline().split(' ').map(Number)));

;(function () {
	print(function (n) {
		var s = [null, null];
		while (n--) {
			var l = readline().split(' ').map(Number);
			s[l[0] === 1 ? 0 : 1] = l[1];
		}

		return s.map(function (e) { return e > 4 ? 'LIVE' : 'DEAD' }).join('\n');
	}(+readline()));
}).call(this);

;(function () {
	print(function (n) {
		var s = [[0, 0], [0, 0]];
		while (n--) {
			var l = readline().split(' ').map(Number),
				k = l[0] === 1 ? 0 : 1;

			s[k] = [s[k][0] + l[1], s[k][1] + l[2]];
		}

		return s.map(function (e) { return e[0] > e[1] ? 'LIVE' : 'DEAD' }).join('\n');
	}(+readline()));
}).call(this);


Ivan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test have the following form:  You are given two positive integers $$$u$$$ and $$$v$$$, find any pair of integers (not necessarily positive) $$$x$$$, $$$y$$$, such that: $$$$$$\frac{x}{u} + \frac{y}{v} = \frac{x + y}{u + v}.$$$$$$  The solution $$$x = 0$$$, $$$y = 0$$$ is forbidden, so you should find any solution with $$$(x, y) \neq (0, 0)$$$. Please help Ivan to solve some equations of this form.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The next lines contain descriptions of test cases. The only line of each test case contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq 10^9$$$) — the parameters of the equation.

For each test case print two integers $$$x$$$, $$$y$$$ — a possible solution to the equation. It should be satisfied that $$$-10^{18} \leq x, y \leq 10^{18}$$$ and $$$(x, y) \neq (0, 0)$$$. We can show that an answer always exists. If there are multiple possible solutions you can print any.

const readline = require('readline')

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

function solve(u, v) {
    return [u * u, -v * v].join(' ')
}


One day, Vogons wanted to build a new hyperspace highway through a distant system with $$$n$$$ planets. The $$$i$$$-th planet is on the orbit $$$a_i$$$, there could be multiple planets on the same orbit. It's a pity that all the planets are on the way and need to be destructed.Vogons have two machines to do that.  The first machine in one operation can destroy any planet at cost of $$$1$$$ Triganic Pu.  The second machine in one operation can destroy all planets on a single orbit in this system at the cost of $$$c$$$ Triganic Pus. Vogons can use each machine as many times as they want.Vogons are very greedy, so they want to destroy all planets with minimum amount of money spent. Can you help them to know the minimum cost of this project?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$c$$$ ($$$1 \le n, c \le 100$$$) — the number of planets and the cost of the second machine usage. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the orbit of the $$$i$$$-th planet.

For each test case print a single integer — the minimum cost of destroying all planets.

NoteIn the first test case, the cost of using both machines is the same, so you can always use the second one and destroy all planets in orbit $$$1$$$, all planets in orbit $$$2$$$, all planets in orbit $$$4$$$, all planets in orbit $$$5$$$.In the second test case, it is advantageous to use the second machine for $$$2$$$ Triganic Pus to destroy all the planets in orbit $$$2$$$, then destroy the remaining two planets using the first machine.In the third test case, you can use the first machine twice or the second machine once.In the fourth test case, it is advantageous to use the first machine twice.

function solve(a, b) {
  var arr = a
    .split(" ")
    .map((i) => +i);

  var c = arr[1];
  var p = b.split(" ").map((i) => +i);

  var cc = {};

  for (var i = 0; i < p.length; i++) {
    if (!cc[p[i]]) {
      cc[p[i]] = 0;
    }

    cc[p[i]]++;
  }

  var k = 0, keys = Object.keys(cc)

  for (var i = 0; i < keys.length; i++) {
    if (cc[keys[i]] <= c) {
      k += cc[keys[i]];
    } else {
      k += c;
    }
  }

  return k
}

var t = +readline()

while (t--) {
  print(solve(readline(), readline()))
}

const readNum = () => +readline();
const readNumArr = () => readline().split(' ').map(item => +item);

function run(n, c, arr) {
  temp = [];
  for(var i = 0; i < n; i++) {
    temp[arr[i]] = (temp[arr[i]] || 0) + 1;
  }
  var count = 0;
  for(i = 0; i < temp.length; i++) {
    if(!temp[i]) {
      continue;
    }
    if(temp[i] && temp[i] < c) {
      count += temp[i];
    }else{
      count += c;
    }
  }
  return count;
}

const n = readNum();

for(var i = 0; i < n; i++) {
  var line1 = readNumArr(), line2 = readNumArr();
  print(run(line1[0], line1[1], line2));
}

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

const getResult = (n, c, planets) => {
	if ( n === 1 ) return 1

    let frequency = {}
    planets.forEach( p => {
    	frequency[p] = ( frequency.hasOwnProperty(p) ) ? frequency[p] + 1 : 1
    })

    if( c === 1 ) return Object.keys(frequency).length

    let min = 0
    Object.values(frequency).forEach( f => {
        min += ( f <= c ) ? f : c
    })

    return min
}

function main() {
    let testcases = parseInt(readline())
    while (testcases--) {
        let inputs = readline().split(' ').map(Number)
        let n = inputs[0]
        let c = inputs[1]
        let planets = readline().split(' ').map(Number)

        let res = getResult(n, c, planets)
        console.log(res)
    }
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0, k = 0;
    for(i = 1; i <= t * 2; i++){
        var a = lines[i].split(' ').map(Number);
        if(i % 2 == 1){
            n = a[0], c = a[1];
        }else{
            var ans = 0;
            var m = new Array(101);
            for(j = 0; j < 101; j++){
                m[j] = 0;
            }
            for(j = 0; j < n; j++){
                m[a[j]]++;
                if(m[a[j]] <= c){
                    ans++;
                }
            }
            console.log(ans);
        }
    }
});

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

let currentLine = 0;
let inputString = "";

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

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

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

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

function readArrayInt() {
  return inputString[currentLine++].split(" ").map(Number);
}

function readArray() {
  return inputString[currentLine++].split(" ");
}

function solve() {
  const T = readInt();

  for (let i = 0; i < T; ++i) {
    const [n, c] = readArrayInt();
    const arr = readArrayInt();

    const asd = [...new Set(arr)];

    const countObj = {};

    let ans = 0;

    arr.map((e, index) => {
      if (!countObj[e]) {
        countObj[e] = 1;
      } else {
        countObj[e]++;
      }
    });

    for (const [key, value] of Object.entries(countObj)) {
      ans += Math.min(value, c);
    }

    console.log(ans);
  }
}

function main() {
  solve();
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
     let t = parseInt(readline());
     while(t--){
          let [n,c] = readline().trim().split(" ").map(cur=>parseInt(cur));
          let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
          let obj = {};
          for(let i=0;i<n;i++){
               if(obj[arr[i]]===undefined) obj[arr[i]] = 1;
               else obj[arr[i]]++;
          }
          let k = Object.keys(obj);
          let cnt = 0;
          for(let i=0;i<k.length;i++){
               let j = obj[k[i]];
               if(j<=c) cnt+=j;
               else cnt+=c;
          }
          console.log(cnt);
     }
};
solve();

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

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

function main() {
  const t = readline();
  for (let i = 0; i < t; i++) {
    let price = 0;
    const [n, c] = readline()
      .split(" ")
      .map((x) => parseInt(x));
    const a = readline()
      .split(" ")
      .map((x) => parseInt(x));

    let obj = {};

    a.forEach((e) => {
      if (obj[e] == undefined) obj[e] = 1;
      else obj[e]++;
    });

    Object.keys(obj).forEach((key) => {
      if (obj[key] <= c) price += obj[key];
      else price += c;
    });

    console.log(price);
  }
}

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        c = rn();
  const cnt = new Array(110).fill(0);
  for (let i = 0; i < n; i++) {
    cnt[rn()]++;
  }
  let res = 0;
  for (let i = 0; i < 110; i++) {
    if (cnt[i] === 0) continue;
    res += Math.min(cnt[i], c);
  }
  return res;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 100;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

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

    for (let test = 0; test < N; test++) {
        let [n, c] = readline().split(' ').map(Number);
        let arr = readline().split(' ').map(Number);
        let freq = {};
        let res = 0;

        for (let i = 0; i < n; i++) {
            if (freq[arr[i]] === undefined) {
                freq[arr[i]] = 1;
            } else {
                freq[arr[i]]++;
            }
        }

        Object.keys(freq).forEach(orbit => {
            if (freq[orbit] < c) {
                res += freq[orbit];
            } else {
                res += c;
            }
        });

        output(res);
    }
}

function solve(a, b) {
  var arr = a
    .split(" ")
    .map((i) => +i);

  var c = arr[1];
  var p = b.split(" ").map((i) => +i);

  var cc = {};

  for (var i = 0; i < p.length; i++) {
    if (!cc[p[i]]) {
      cc[p[i]] = 0;
    }

    cc[p[i]]++;
  }

  var k = 0, keys = Object.keys(cc)

  for (var i = 0; i < keys.length; i++) {
    if (cc[keys[i]] <= c) {
      k += cc[keys[i]];
    } else {
      k += c;
    }
  }

  return k
}

var t = +readline()

while (t--) {
  solve(readline(), readline())
}

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

const getResult = (n, c, planets) => {
	if ( n === 1 ) return 1

    let frequency = new Array(100).fill(0)

    planets.forEach( p => {
    	frequency[p]++
    })

    frequency = frequency.filter( f => f !== 0 ).sort( (a,b) => b - a )

    if( c === 1 ) return frequency.length

    let min = 0

    frequency.forEach( f => {
    	min += Math.min(f, c)

    })

    return min
}

function main() {
    let testcases = parseInt(readline())
    while (testcases--) {
        let inputs = readline().split(' ').map(Number)
        let n = inputs[0]
        let c = inputs[1]
        let planets = readline().split(' ').map(Number)

        let res = getResult(n, c, planets)
        console.log(res)
    }
}

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

const getResult = (n, c, planets) => {
	if ( n === 1 ) return 1

    let frequency = new Array(100).fill(0)

    planets.forEach( p => {
    	frequency[p]++
    })

    frequency = frequency.filter( f => f !== 0 ).sort( (a,b) => b - a )

    if( c === 1 ) return frequency.length

    let min = 0
    let max = n

    frequency.forEach( f => {
    	if( f >= c ) min += c
    	else min++
    })

    return Math.min(min, max)
}

function main() {
    let testcases = parseInt(readline())
    while (testcases--) {
        let inputs = readline().split(' ').map(Number)
        let n = inputs[0]
        let c = inputs[1]
        let planets = readline().split(' ').map(Number)

        let res = getResult(n, c, planets)
        console.log(res)
    }
}

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

const getResult = (n, c, planets) => {
	if ( n === 1 ) return 1

    let maxOrbit = Math.max.apply(null, planets)
    let frequency = new Array(maxOrbit + 1).fill(0)

    planets.forEach( (p,i) => {
    	frequency[p]++
    })

    frequency = frequency.filter( f => f !== 0 ).sort( (a,b) => b - a )

    if( c === 1 ) return frequency.length

    let min = 0
    let max = n

    for( let f of frequency )
    {
    	if(f <= c) min++
	}

    return Math.min(min, max)
}

function main() {
    let testcases = parseInt(readline())
    while (testcases--) {
        let inputs = readline().split(' ').map(Number)
        let n = inputs[0]
        let c = inputs[1]
        let planets = readline().split(' ').map(Number)

        let res = getResult(n, c, planets)
        console.log(res)
    }
}

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

const getResult = (n, c, planets) => {
	if ( n === 1 ) return 1

    let maxOrbit = Math.max.apply(null, planets)
    let frequency = new Array(maxOrbit + 1).fill(0)

    planets.forEach( (p,i) => {
    	frequency[p]++
    })

    frequency = frequency.filter( f => f !== 0 ).sort( (a,b) => b - a )

    if( c === 1 ) return frequency.length

    let min = 0
    let max = n

    for( let f of frequency )
    {
    	if(f > 1) min += c
    	else min += 1

	}

    return Math.min(min, max)
}

function main() {
    let testcases = parseInt(readline())
    while (testcases--) {
        let inputs = readline().split(' ').map(Number)
        let n = inputs[0]
        let c = inputs[1]
        let planets = readline().split(' ').map(Number)

        let res = getResult(n, c, planets)
        console.log(res)
    }
}

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

const getResult = (n, c, orbits) => {
    let min = 0
    let max = Math.max.apply(null, orbits)
    let temp = new Array(max + 1).fill(0)

    for (let i = 0; i < n; i++) {
        temp[orbits[i]]++
    }

    for (let i = 0; i < max + 1; i++) {
        if (temp[i] > 1)
            min = min + c
        if (temp[i] === 0)
            min = min + 1

    }

    return min
}

function main() {
    let testcases = parseInt(readline())
    while (testcases--) {
        let inputs = readline().split(' ').map(Number)
        let n = inputs[0]
        let c = inputs[1]
        let orbits = readline().split(' ').map(Number)

        let res = getResult(n, c, orbits)
        console.log(res)
    }
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0, k = 0;
    for(i = 1; i <= t * 2; i++){
        var a = lines[i].split(' ').map(Number);
        if(i % 2 == 1){
            n = a[0], c = a[1];
        }else{
            var ans = 0;
            var m = new Array(100);
            for(j = 0; j < 100; j++){
                m[j] = 0;
            }
            for(j = 0; j < n; j++){
                m[a[j]]++;
                if(m[a[j]] <= c){
                    ans++;
                }
            }
            console.log(ans);
        }
    }
});