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

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


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')
  }
})

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

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

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')
            }
        }
    }

});


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

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


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

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


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(" ") : ""));

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

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


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

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

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');
// ########################################################## //

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

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


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

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

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


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();
  });
  solve();
});
function readline() {
  return inputString[currentLine++];
}

function solve() {
  var t = readline();
  for (var k = 0; k < t; k++) {
    var n = readline();
    var digits = 10 - readline().split(' ').length;
    console.log(digits * (digits - 1) * 3);
  }
}

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    let k = 10 - n;
    k = (k * (k - 1)) / 2;
    console.log(k * 6);
  }
};
solve();

var testCasesCount = parseInt(readline());
var i = 0;
for (i = 0; i < testCasesCount; i++) {
  var exclusionLength = parseInt(readline());
  var excludedNums = readline().split(' ');
  var includedCount = 10 - excludedNums.length;
  print(((includedCount) * (includedCount - 1) / 2) * 6);
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var totalExcluded = parseInt(readline());
    readline();
    var value = 10 - totalExcluded
    var result = 6 * (value * (value-1) / 2);
    print(result);
}

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;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
            if(n == 1){
                console.log(216);
            }
            if(n == 2){
                console.log(168);
            }
            if(n == 3){
                console.log(126);
            }
            if(n == 4){
                console.log(90);
            }
            if(n == 5){
                console.log(60);
            }
            if(n == 6){
                console.log(36);
            }
            if(n == 7){
                console.log(18);
            }
            if(n == 8){
                console.log(6);
            }
        }
    }
});

/*
** Template
*/

// Common Template Starts //
//*
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++];
}
// Common Template Ends //

// Driver Function Starts //
const main = () => {
    console.clear()
    let t = parseInt(readline())
    // let primes = sivOfAtkin(1000)
    while (t--) {
        let n = parseInt(readline())
        let arr = readline().split(' ').map(Number)
        console.log( 3 * ( 10 - n ) * ( 9 - n ) )
    }
}
// Driver Function Ends //

/*
* auther yeling
*
*
*/
'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 print(str) {
    console.log(str);
}

// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();
// testOutput();

function begin(n, nums) {
    let left = 10 - n;
    let sum = left * (left - 1) / 2 * 6;
    print(sum);
}

function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = parseInt(readline(), 10);
        var x = readline()
            .trim()
            .split(' ')
            .map((y) => parseInt(y, 10));
        begin(n, x);
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {

    let t = parseInt(readLine());

    while(t--)
    {
        const n = parseInt(readLine());

        const arr_a = readLine().split(" ").map(x=>parseInt(x));

        let done = new Set()

        //console.log("arr_a " +arr_a)

        let nums = [0,1,2,3,4,5,6,7,8,9]
        let second_arr = nums.filter(n => !arr_a.includes(n))
        //console.log("second_arr" + second_arr)
        for(const a of second_arr)
        {
            //console.log("a " +a)
            for(const b of second_arr.slice())
            {
                if(a==b)
                    continue;
                //console.log("b " +b)
                 done.add(a.toString()+a.toString()+b.toString()+b.toString())
                 done.add(a.toString()+b.toString()+a.toString()+b.toString())
                 done.add(a.toString()+b.toString()+b.toString()+a.toString())
            }
        }
        //console.log(Array(...done).join(' '))
        console.log(done.size)

    }
}

'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);
  rn();
        const a = rns();
  const set = new Set(a.map(String));
  let res = 0;
  for (let i = 0; i < 10000; i++) {
    const s = i.toString().padStart(4, '0').split('');
    const cnt = new Map();
    for (let i = 0; i < s.length; i++) {
      var _cnt$get;
      cnt.set(s[i], ((_cnt$get = cnt.get(s[i])) !== null && _cnt$get !== void 0 ? _cnt$get : 0) + 1);
    }
    if (cnt.size !== 2) continue;
    const [a, b] = [...cnt.keys()];
    if (set.has(a) || set.has(b)) continue;
    if (cnt.get(a) !== 2 || cnt.get(b) !== 2) continue;
    res++;
  }
  return res;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    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(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

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;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
            if(n == 1){
                console.log(216);
            }
            if(n == 8){
                console.log(6)
            }
        }
    }
});