(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let o=0;o<t;++o){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const o=n(r(747));let s="",i=[],u=0,l="";const p="local"===process.argv[2],f=t=>{if(p){if(i=o.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),o.default.writeFileSync("output.txt",l),console.log(l),o.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{s+=t})),process.stdin.on("end",(e=>{i=s.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function h(){return i[u++]}function a(){return h().split(" ").map((t=>parseFloat(t)))}function c(){return h().split("")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=a();for(;e>0;)t(),e--}))},readline:h,nextNumbers:a,nextBigNumbers:function(){return h().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(a());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=a();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){p&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const o=n(r(312));o.default.runEachTest((function(){let[t,e]=o.default.nextNumbers(),r=o.default.nextCharacterMatrix(t),n=[],s=(t,e,o,s,i,u)=>{n.push(`${t+1} ${e+1} ${o+1} ${s+1} ${i+1} ${u+1}`),"0"==r[t][e]?r[t][e]="1":r[t][e]="0","0"==r[o][s]?r[o][s]="1":r[o][s]="0","0"==r[i][u]?r[i][u]="1":r[i][u]="0"};if(t%2==1)for(let t=0;t<e-1;t++)"1"==r[0][t]&&"1"==r[0][t+1]?s(0,t,0,t+1,1,t):"1"==r[0][t]?s(0,t,1,t+1,1,t):"1"==r[0][t+1]&&s(0,t+1,1,t+1,1,t);if(e%2==1)for(let e=t%2==0?0:1;e<t-1;++e)"1"==r[e][0]&&"1"==r[e+1][0]?s(e,0,e+1,0,e,1):"1"==r[e][0]?s(e,0,e+1,1,e,1):"1"==r[e+1][0]&&s(e,1,e+1,0,e+1,1);let i=(t,e)=>{"0"!=r[t][e]?"0"!=r[t+1][e]?"0"!=r[t][e+1]?"0"==r[t+1][e+1]&&s(t+1,e,t,e+1,t,e):s(t,e,t+1,e,t+1,e+1):s(t,e,t,e+1,t+1,e+1):s(t+1,e,t,e+1,t+1,e+1)},u=(t,e)=>{let n=[],o=[];for(let s=0;s<2;++s)for(let i=0;i<2;++i)"0"==r[t+s][e+i]?n.push({x1:t+s,x2:e+i}):o.push({x1:t+s,x2:e+i});s(n[0].x1,n[0].x2,n[1].x1,n[1].x2,o[0].x1,o[0].x2)},l=(t,e)=>{let n=[],o=[];for(let s=0;s<2;++s)for(let i=0;i<2;++i)"0"==r[t+s][e+i]?n.push({x1:t+s,x2:e+i}):o.push({x1:t+s,x2:e+i});s(n[0].x1,n[0].x2,n[1].x1,n[1].x2,o[0].x1,o[0].x2)};for(let n=t%2==0?0:1;n<t;n+=2)for(let t=e%2==0?0:1;t<e;t+=2){let e=0,o=0;"1"==r[n][t]?o++:e++,"1"==r[n+1][t]?o++:e++,"1"==r[n][t+1]?o++:e++,"1"==r[n+1][t+1]?o++:e++,0!=o&&(3!=o?2!=o?1!=o?4!=o||(s(n,t,n+1,t,n+1,t+1),u(n,t),l(n,t),i(n,t)):(u(n,t),l(n,t),i(n,t)):(l(n,t),i(n,t)):i(n,t))}o.default.puts(n.length),o.default.puts(n.join(" "))}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n, m] = io.nextNumbers()
//   let a = io.nextCharacterMatrix(n)
//
//   let flips = []
//
//   let flip = (x1: number, y1: number, x2: number, y2: number, x3: number, y3: number) => {
//     flips.push(`${x1 + 1} ${y1 + 1} ${x2 + 1} ${y2 + 1} ${x3 + 1} ${y3 + 1}`)
//
//     if (a[x1][y1] == "0") {
//       a[x1][y1] = "1"
//     } else {
//       a[x1][y1] = "0"
//     }
//
//     if (a[x2][y2] == "0") {
//       a[x2][y2] = "1"
//     } else {
//       a[x2][y2] = "0"
//     }
//
//     if (a[x3][y3] == "0") {
//       a[x3][y3] = "1"
//     } else {
//       a[x3][y3] = "0"
//     }
//   }
//
//   if (n % 2 == 1) {
//     for (let i = 0; i < m - 1; i++) {
//       if (a[0][i] == "1" && a[0][i + 1] == "1") {
//         flip(0, i, 0, i + 1, 1, i)
//       } else if (a[0][i] == "1") {
//         flip(0, i, 1, i + 1, 1, i)
//       } else if (a[0][i + 1] == "1") {
//         flip(0, i + 1, 1, i + 1, 1, i)
//       }
//     }
//   }
//
//   if (m % 2 == 1) {
//     for (let i = n % 2 == 0 ? 0 : 1; i < n - 1; ++i) {
//       if (a[i][0] == "1" && a[i + 1][0] == "1") {
//         flip(i, 0, i + 1, 0, i, 1)
//       } else if (a[i][0] == "1") {
//         flip(i, 0, i + 1, 1, i, 1)
//       } else if (a[i + 1][0] == "1") {
//         flip(i, 1, i + 1, 0, i + 1, 1)
//       }
//     }
//   }
//
//   let proc3 = (x1: number, x2: number) => {
//     if (a[x1][x2] == "0") {
//       flip(x1 + 1, x2, x1, x2 + 1, x1 + 1, x2 + 1)
//       return
//     }
//
//     if (a[x1 + 1][x2] == "0") {
//       flip(x1, x2, x1, x2 + 1, x1 + 1, x2 + 1)
//       return
//     }
//
//     if (a[x1][x2 + 1] == "0") {
//       flip(x1, x2, x1 + 1, x2, x1 + 1, x2 + 1)
//       return
//     }
//
//     if (a[x1 + 1][x2 + 1] == "0") {
//       flip(x1 + 1, x2, x1, x2 + 1, x1, x2)
//     }
//   }
//
//   let proc1 = (x1: number, x2: number) => {
//     let zeroCoord = []
//     let oneCoord = []
//
//     for (let i = 0; i < 2; ++i) {
//       for (let j = 0; j < 2; ++j) {
//         if (a[x1 + i][x2 + j] == "0") {
//           zeroCoord.push({ x1: x1 + i, x2: x2 + j })
//         } else {
//           oneCoord.push({ x1: x1 + i, x2: x2 + j })
//         }
//       }
//     }
//
//     flip(
//       zeroCoord[0].x1,
//       zeroCoord[0].x2,
//       zeroCoord[1].x1,
//       zeroCoord[1].x2,
//       oneCoord[0].x1,
//       oneCoord[0].x2
//     )
//   }
//
//   let proc2 = (x1: number, x2: number) => {
//     let zeroCoord = []
//     let oneCoord = []
//
//     for (let i = 0; i < 2; ++i) {
//       for (let j = 0; j < 2; ++j) {
//         if (a[x1 + i][x2 + j] == "0") {
//           zeroCoord.push({ x1: x1 + i, x2: x2 + j })
//         } else {
//           oneCoord.push({ x1: x1 + i, x2: x2 + j })
//         }
//       }
//     }
//
//     flip(
//       zeroCoord[0].x1,
//       zeroCoord[0].x2,
//       zeroCoord[1].x1,
//       zeroCoord[1].x2,
//       oneCoord[0].x1,
//       oneCoord[0].x2
//     )
//   }
//
//   for (let i = n % 2 == 0 ? 0 : 1; i < n; i += 2) {
//     for (let j = m % 2 == 0 ? 0 : 1; j < m; j += 2) {
//       let nr0 = 0
//       let nr1 = 0
//
//       if (a[i][j] == "1") {
//         nr1++
//       } else {
//         nr0++
//       }
//
//       if (a[i + 1][j] == "1") {
//         nr1++
//       } else {
//         nr0++
//       }
//
//       if (a[i][j + 1] == "1") {
//         nr1++
//       } else {
//         nr0++
//       }
//
//       if (a[i + 1][j + 1] == "1") {
//         nr1++
//       } else {
//         nr0++
//       }
//
//       if (nr1 == 0) {
//         continue
//       }
//
//       if (nr1 == 3) {
//         proc3(i, j)
//         continue
//       }
//
//       if (nr1 == 2) {
//         proc2(i, j)
//         proc3(i, j)
//         continue
//       }
//
//       if (nr1 == 1) {
//         proc1(i, j)
//         proc2(i, j)
//         proc3(i, j)
//         continue
//       }
//
//       if (nr1 == 4) {
//         flip(i, j, i + 1, j, i + 1, j + 1)
//         proc1(i, j)
//         proc2(i, j)
//         proc3(i, j)
//         continue
//       }
//     }
//   }
//
//   io.puts(flips.length)
//   io.puts(flips.join(" "))
// }
//
// io.runEachTest(main)
// // io.runMain(main)

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
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';}}
	};
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//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();
	var output2 = new Array();
	for(var i = 0; i < t; i++){
		var one = nextIntArray();
		var N = one[0];
		var M = one[1];
		var list = new Array(N);
		var count = 0;
		var output = [];
		for(var j = 0; j < N; j++){
			list[j] = new Array(M);
			var tmp = next();
			for(var k = 0; k < M; k++){
				list[j][k] = myconv(tmp[k], 1);
			}
		}
		if(list[N - 1][M - 1] == 1 && list[N - 2][M - 1] == 1 && list[N - 1][M - 2] == 1 && list[N - 2][M - 2] == 1){
			var s = (N - 1) + " " + M + " " + N + " " + (M - 1) + " " + N + " " + M;
			output.push(s);
			count++;
			list[N - 1][M - 1] = 0;
			list[N - 2][M - 1] = 0;
			list[N - 1][M - 2] = 0;
		}
		for(var x = 0; x < N - 1; x++){
			for(var y = 0; y < M - 1; y++){
				var hidariue = {
					v : list[x][y],
					s : (x + 1) + " " + (y + 1),
				};
				var hidarishita = {
					v : list[x + 1][y],
					s : (x + 2) + " " + (y + 1),
				};
				var migiue = {
					v : list[x][y + 1],
					s : (x + 1) + " " + (y + 2),
				};
				var migishita = {
					v : list[x + 1][y + 1],
					s : (x + 2) + " " + (y + 2),
				};

				var check = hidariue.v + hidarishita.v + migiue.v + migishita.v;
				if(check == 4){
					var s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
					output.push(s);
					count++;
					list[x][y] = 0;
					list[x + 1][y] = 0;
					list[x][y + 1] = 0;
				}else if(check == 3){
					if(hidariue.v == 0){
						var s = migiue.s + " " + migishita.s + " " + hidarishita.s;
						output.push(s);
						count++;
						list[x + 1][y + 1] = 0;
						list[x + 1][y] = 0;
						list[x][y + 1] = 0;
					}else if(hidarishita.v == 0){
						var s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						count++;
						list[x][y] = 0;
						list[x + 1][y + 1] = 0;
						list[x][y + 1] = 0;
					}else if(migiue.v == 0){
						var s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						count++;
						list[x][y] = 0;
						list[x + 1][y] = 0;
						list[x + 1][y + 1] = 0;
					}else{
						var s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
						output.push(s);
						count++;
						list[x][y] = 0;
						list[x + 1][y] = 0;
						list[x][y + 1] = 0;
					}
				}else if(check == 2){
					if(hidariue.v == 1 && migishita.v == 1){
						var s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
						count += 2;
						output.push(s);
						s = migiue.s + " " + migishita.s + " " + hidarishita.s;
						output.push(s);
						list[x][y] = 0;
						list[x + 1][y + 1] = 0;
					}else if(migiue.v == 1 && hidarishita.v == 1){
						var s = hidariue.s + " " + migishita.s + " " + hidarishita.s;
						count += 2;
						output.push(s);
						s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x][y + 1] = 0;
						list[x + 1][y] = 0;
					}else if(hidariue.v == 1 && migiue.v == 1){
						var s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						count += 2;
						output.push(s);
						s = migiue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						list[x][y] = 0;
						list[x][y + 1] = 0;
					}else if(migiue.v == 1 && migishita.v == 1){
						var s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						count += 2;
						output.push(s);
						s = migiue.s + " " + hidarishita.s + " " + hidariue.s;
						output.push(s);
						list[x][y + 1] = 0;
						list[x + 1][y + 1] = 0;
					}else if(hidarishita.v == 1 && migishita.v == 1){
						var s = hidariue.s + " " + migiue.s + " " + migishita.s;
						count += 2;
						output.push(s);
						s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
						output.push(s);
						list[x + 1][y] = 0;
						list[x + 1][y + 1] = 0;
					}else if(hidariue.v == 1 && hidarishita.v == 1){
						var s = hidariue.s + " " + migiue.s + " " + migishita.s;
						count += 2;
						output.push(s);
						s = hidarishita.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x][y] = 0;
						list[x + 1][y] = 0;
					}
				}else if(check == 1){
					if(hidariue.v == 1){
						count += 3;
						var s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
						output.push(s);
						s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x][y] = 0;
					}else if(migiue.v == 1){
						count += 3;
						var s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						s = hidariue.s + " " + hidarishita.s + " " + migiue.s;
						output.push(s);
						s = hidarishita.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x][y + 1] = 0;
					}else if(hidarishita.v == 1){
						count += 3;
						var s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						s = hidariue.s + " " + hidarishita.s + " " + migiue.s;
						output.push(s);
						s = hidarishita.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x + 1][y] = 0;
					}else if(migishita.v == 1){
						count += 3;
						var s = hidarishita.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						s = hidariue.s + " " + migishita.s + " " + migiue.s;
						output.push(s);
						s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						list[x + 1][y + 1] = 0;
					}
				}
			}
		}
		output.unshift(count);
		output2.push(myconv(output, 9));

	}
	myout(myconv(output2, 9));
}

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

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const [rowLen, colLen] = readLine().split(" ").map(Number);
    const arr = [];
    for (let i = 0; i < rowLen; i++) {
      const _r = readLine().split("").map(Number);
      arr.push(_r);
    }
    let count = 0;
    const ans = [];

    for (let row = 1; row <= rowLen; row++) {
      for (let col = 1; col <= colLen; col++) {
        let [dx, dy] = [1, 1];
        if (row === rowLen) dx = -1;
        if (col === colLen) dy = -1;

        if (arr[row - 1][col - 1] === 1) {
          count += 3;
          ans.push([row, col, row, col + dy, row + dx, col]);
          ans.push([row, col, row, col + dy, row + dx, col + dy]);
          ans.push([row, col, row + dx, col, row + dx, col + dy]);
        }
      }
    }
    console.log(count);
    for (let result of ans) console.log(result.join(" "));
  }
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
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';}}
	};
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//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();
	var output2 = new Array();
	for(var i = 0; i < t; i++){
		var one = nextIntArray();
		var N = one[0];
		var M = one[1];
		var list = new Array(N);
		var count = 0;
		var output = [];
		for(var j = 0; j < N; j++){
			list[j] = new Array(M);
			var tmp = next();
			for(var k = 0; k < M; k++){
				list[j][k] = myconv(tmp[k], 1);
			}
		}
		if(list[N - 1][M - 1] == 1 && list[N - 2][M - 1] == 1 && list[N - 1][M - 2] == 1 && list[N - 2][M - 2] == 1){
			var s = (N - 1) + " " + M + " " + N + " " + (M - 1) + " " + N + " " + M;
			output.push(s);
			count++;
			list[N - 1][M - 1] = 0;
			list[N - 2][M - 1] = 0;
			list[N - 1][M - 2] = 0;
		}
		for(var x = 0; x < N - 1; x++){
			for(var y = 0; y < M - 1; y++){
				var hidariue = {
					v : list[x][y],
					s : (x + 1) + " " + (y + 1),
				};
				var hidarishita = {
					v : list[x + 1][y],
					s : (x + 2) + " " + (y + 1),
				};
				var migiue = {
					v : list[x][y + 1],
					s : (x + 1) + " " + (y + 2),
				};
				var migishita = {
					v : list[x + 1][y + 1],
					s : (x + 2) + " " + (y + 2),
				};

				var check = hidariue.v + hidarishita.v + migiue.v + migishita.v;
				if(check == 4){
					var s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
					output.push(s);
					count++;
					list[x][y] = 0;
					list[x + 1][y] = 0;
					list[x][y + 1] = 0;
				}else if(check == 3){
					if(hidariue.v == 0){
						var s = migiue.s + " " + migishita.s + " " + hidarishita.s;
						output.push(s);
						count++;
						list[x + 1][y + 1] = 0;
						list[x + 1][y] = 0;
						list[x][y + 1] = 0;
					}else if(hidarishita.v == 0){
						var s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						count++;
						list[x][y] = 0;
						list[x + 1][x] = 0;
						list[x][y + 1] = 0;
					}else if(migiue.v == 0){
						var s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						count++;
						list[x][y] = 0;
						list[x + 1][y] = 0;
						list[x + 1][y + 1] = 0;
					}else{
						var s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
						output.push(s);
						count++;
						list[x][y] = 0;
						list[x + 1][y] = 0;
						list[x][y + 1] = 0;
					}
				}else if(check == 2){
					if(hidariue.v == 1 && migishita.v == 1){
						var s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
						count += 2;
						output.push(s);
						s = migiue.s + " " + migishita.s + " " + hidarishita.s;
						output.push(s);
						list[x][y] = 0;
						list[x + 1][y + 1] = 0;
					}else if(migiue.v == 1 && hidarishita.v == 1){
						var s = hidariue.s + " " + migishita.s + " " + hidarishita.s;
						count += 2;
						output.push(s);
						s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x][y + 1] = 0;
						list[x + 1][y] = 0;
					}else if(hidariue.v == 1 && migiue.v == 1){
						var s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						count += 2;
						output.push(s);
						s = migiue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						list[x][y] = 0;
						list[x][y + 1] = 0;
					}else if(migiue.v == 1 && migishita.v == 1){
						var s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						count += 2;
						output.push(s);
						s = migiue.s + " " + hidarishita.s + " " + hidariue.s;
						output.push(s);
						list[x][y + 1] = 0;
						list[x + 1][y + 1] = 0;
					}else if(hidarishita.v == 1 && migishita.v == 1){
						var s = hidariue.s + " " + migiue.s + " " + migishita.s;
						count += 2;
						output.push(s);
						s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
						output.push(s);
						list[x + 1][y] = 0;
						list[x + 1][y + 1] = 0;
					}else if(hidariue.v == 1 && hidarishita.v == 1){
						var s = hidariue.s + " " + migiue.s + " " + migishita.s;
						count += 2;
						output.push(s);
						s = hidarishita.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x][y] = 0;
						list[x + 1][y] = 0;
					}
				}else if(check == 1){
					if(hidariue.v == 1){
						count += 3;
						var s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
						output.push(s);
						s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x][y] = 0;
					}else if(migiue.v == 1){
						count += 3;
						var s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						s = hidariue.s + " " + hidarishita.s + " " + migiue.s;
						output.push(s);
						s = hidarishita.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x][y + 1] = 0;
					}else if(hidarishita.v == 1){
						count += 3;
						var s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						s = hidariue.s + " " + hidarishita.s + " " + migiue.s;
						output.push(s);
						s = hidarishita.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x + 1][y] = 0;
					}else if(migishita.v == 1){
						count += 3;
						var s = hidarishita.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						s = hidariue.s + " " + migishita.s + " " + migiue.s;
						output.push(s);
						s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x + 1][y + 1] = 0;
					}
				}
			}
		}
		output.unshift(count);
		output2.push(myconv(output, 9));

	}
	myout(myconv(output2, 9));
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
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';}}
	};
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//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();
	var output2 = new Array();
	for(var i = 0; i < t; i++){
		var one = nextIntArray();
		var N = one[0];
		var M = one[1];
		var list = new Array(N);
		var count = 0;
		var output = [];
		for(var j = 0; j < N; j++){
			list[j] = new Array(M);
			var tmp = next();
			for(var k = 0; k < M; k++){
				list[j][k] = myconv(tmp[k], 1);
			}
		}
		if(list[N - 1][M - 1] == 1 && list[N - 2][M - 1] == 1 && list[N - 1][M - 2] == 1 && list[N - 2][M - 2] == 1){
			var s = (N - 1) + " " + M + " " + N + " " + (M - 1) + " " + N + " " + M;
			output.push(s);
			count++;
			list[N - 1][M - 1] = 0;
			list[N - 2][M - 1] = 0;
			list[N - 1][M - 2] = 0;
		}
		for(var x = 0; x < N - 1; x++){
			for(var y = 0; y < M - 1; y++){
				var hidariue = {
					v : list[x][y],
					s : (x + 1) + " " + (y + 1),
				};
				var hidarishita = {
					v : list[x + 1][y],
					s : (x + 2) + " " + (y + 1),
				};
				var migiue = {
					v : list[x][y + 1],
					s : (x + 1) + " " + (y + 2),
				};
				var migishita = {
					v : list[x + 1][y + 1],
					s : (x + 2) + " " + (y + 2),
				};

				var check = hidariue.v + hidarishita.v + migiue.v + migishita.v;
				if(check == 4){
					var s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
					output.push(s);
					count++;
					list[x][y] = 0;
					list[x + 1][y] = 0;
					list[x][y + 1] = 0;
				}else if(check == 3){
					if(hidariue.v == 0){
						var s = migiue.s + " " + migishita.s + " " + hidarishita.s;
						output.push(s);
						count++;
						list[x + 1][y + 1] = 0;
						list[x + 1][y] = 0;
						list[x][y + 1] = 0;
					}else if(hidarishita.v == 0){
						var s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						count++;
						list[x][y] = 0;
						list[x + 1][y + 1] = 0;
						list[x][y + 1] = 0;
					}else if(migiue.v == 0){
						var s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						count++;
						list[x][y] = 0;
						list[x + 1][y] = 0;
						list[x + 1][y + 1] = 0;
					}else{
						var s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
						output.push(s);
						count++;
						list[x][y] = 0;
						list[x + 1][y] = 0;
						list[x][y + 1] = 0;
					}
				}else if(check == 2){
					if(hidariue.v == 1 && migishita.v == 1){
						var s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
						count += 2;
						output.push(s);
						s = migiue.s + " " + migishita.s + " " + hidarishita.s;
						output.push(s);
						list[x][y] = 0;
						list[x + 1][y + 1] = 0;
					}else if(migiue.v == 1 && hidarishita.v == 1){
						var s = hidariue.s + " " + migishita.s + " " + hidarishita.s;
						count += 2;
						output.push(s);
						s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x][y + 1] = 0;
						list[x + 1][y] = 0;
					}else if(hidariue.v == 1 && migiue.v == 1){
						var s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						count += 2;
						output.push(s);
						s = migiue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						list[x][y] = 0;
						list[x][y + 1] = 0;
					}else if(migiue.v == 1 && migishita.v == 1){
						var s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						count += 2;
						output.push(s);
						s = migiue.s + " " + hidarishita.s + " " + hidariue.s;
						output.push(s);
						list[x][y + 1] = 0;
						list[x + 1][y + 1] = 0;
					}else if(hidarishita.v == 1 && migishita.v == 1){
						var s = hidariue.s + " " + migiue.s + " " + migishita.s;
						count += 2;
						output.push(s);
						s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
						output.push(s);
						list[x + 1][y] = 0;
						list[x + 1][y + 1] = 0;
					}else if(hidariue.v == 1 && hidarishita.v == 1){
						var s = hidariue.s + " " + migiue.s + " " + migishita.s;
						count += 2;
						output.push(s);
						s = hidarishita.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x][y] = 0;
						list[x + 1][y] = 0;
					}
				}else if(check == 1){
					if(hidariue.v == 1){
						count += 3;
						var s = hidariue.s + " " + migiue.s + " " + hidarishita.s;
						output.push(s);
						s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x][y] = 0;
					}else if(migiue.v == 1){
						count += 3;
						var s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						s = hidariue.s + " " + hidarishita.s + " " + migiue.s;
						output.push(s);
						s = hidarishita.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x][y + 1] = 0;
					}else if(hidarishita.v == 1){
						count += 3;
						var s = hidariue.s + " " + hidarishita.s + " " + migishita.s;
						output.push(s);
						s = hidariue.s + " " + hidarishita.s + " " + migiue.s;
						output.push(s);
						s = hidarishita.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x + 1][y] = 0;
					}else if(migishita.v == 1){
						count += 3;
						var s = hidarishita.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						s = hidariue.s + " " + migishita.s + " " + migiue.s;
						output.push(s);
						s = hidariue.s + " " + migiue.s + " " + migishita.s;
						output.push(s);
						list[x + 1][y + 1] = 0;
					}
				}
			}
		}
		output.unshift(count);
		output2.push(myconv(output, 9));

	}
	myout(myconv(output2, 9));
}

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let o=0;o<t;++o){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const o=n(r(747));let s="",i=[],u=0,l="";const p="local"===process.argv[2],f=t=>{if(p){if(i=o.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),o.default.writeFileSync("output.txt",l),console.log(l),o.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{s+=t})),process.stdin.on("end",(e=>{i=s.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function h(){return i[u++]}function a(){return h().split(" ").map((t=>parseFloat(t)))}function c(){return h().split("")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=a();for(;e>0;)t(),e--}))},readline:h,nextNumbers:a,nextBigNumbers:function(){return h().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(a());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=a();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){p&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const o=n(r(312));o.default.runEachTest((function(){let[t,e]=o.default.nextNumbers(),r=o.default.nextCharacterMatrix(t),n=[],s=(t,e,o,s,i,u)=>{n.push(`${t+1} ${e+1} ${o+1} ${s+1} ${i+1} ${u+1}`),"0"==r[t][e]?r[t][e]="1":r[t][e]="0","0"==r[o][s]?r[o][s]="1":r[o][s]="0","0"==r[i][u]?r[i][u]="1":r[i][u]="0"};if(t%2==1)for(let t=0;t<e-1;t++)"1"==r[0][t]&&"1"==r[0][t+1]?s(0,t,0,t+1,1,t):"1"==r[0][t]?s(0,t,1,t+1,1,t):"1"==r[0][t+1]&&s(0,t+1,1,t+1,1,t);if(e%2==1)for(let e=t%2==0?0:1;e<t-1;++e)"1"==r[e][0]&&"1"==r[e+1][0]?s(e,0,e+1,0,e,1):"1"==r[e][0]?s(e,0,e+1,1,e,1):"1"==r[e+1][0]&&s(e,1,e+1,0,e,1);let i=(t,e)=>{"0"!=r[t][e]?"0"!=r[t+1][e]?"0"!=r[t][e+1]?"0"==r[t+1][e+1]&&s(t+1,e,t,e+1,t,e):s(t,e,t+1,e,t+1,e+1):s(t,e,t,e+1,t+1,e+1):s(t+1,e,t,e+1,t+1,e+1)},u=(t,e)=>{let n=[],o=[];for(let s=0;s<2;++s)for(let i=0;i<2;++i)"0"==r[t+s][e+i]?n.push({x1:t+s,x2:e+i}):o.push({x1:t+s,x2:e+i});s(n[0].x1,n[0].x2,n[1].x1,n[1].x2,o[0].x1,o[0].x2)},l=(t,e)=>{let n=[],o=[];for(let s=0;s<2;++s)for(let i=0;i<2;++i)"0"==r[t+s][e+i]?n.push({x1:t+s,x2:e+i}):o.push({x1:t+s,x2:e+i});s(n[0].x1,n[0].x2,n[1].x1,n[1].x2,o[0].x1,o[0].x2)};for(let n=t%2==0?0:1;n<t;n+=2)for(let t=e%2==0?0:1;t<e;t+=2){let e=0,o=0;"1"==r[n][t]?o++:e++,"1"==r[n+1][t]?o++:e++,"1"==r[n][t+1]?o++:e++,"1"==r[n+1][t+1]?o++:e++,0!=o&&(3!=o?2!=o?1!=o?4!=o||(s(n,t,n+1,t,n+1,t+1),u(n,t),l(n,t),i(n,t)):(u(n,t),l(n,t),i(n,t)):(l(n,t),i(n,t)):i(n,t))}o.default.puts(n.length),o.default.puts(n.join(" "))}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{}};return t[n].call(o.exports,o,o.exports,r),o.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n, m] = io.nextNumbers()
//   let a = io.nextCharacterMatrix(n)
//
//   let flips = []
//
//   let flip = (x1: number, y1: number, x2: number, y2: number, x3: number, y3: number) => {
//     flips.push(`${x1 + 1} ${y1 + 1} ${x2 + 1} ${y2 + 1} ${x3 + 1} ${y3 + 1}`)
//
//     if (a[x1][y1] == "0") {
//       a[x1][y1] = "1"
//     } else {
//       a[x1][y1] = "0"
//     }
//
//     if (a[x2][y2] == "0") {
//       a[x2][y2] = "1"
//     } else {
//       a[x2][y2] = "0"
//     }
//
//     if (a[x3][y3] == "0") {
//       a[x3][y3] = "1"
//     } else {
//       a[x3][y3] = "0"
//     }
//   }
//
//   if (n % 2 == 1) {
//     for (let i = 0; i < m - 1; i++) {
//       if (a[0][i] == "1" && a[0][i + 1] == "1") {
//         flip(0, i, 0, i + 1, 1, i)
//       } else if (a[0][i] == "1") {
//         flip(0, i, 1, i + 1, 1, i)
//       } else if (a[0][i + 1] == "1") {
//         flip(0, i + 1, 1, i + 1, 1, i)
//       }
//     }
//   }
//
//   if (m % 2 == 1) {
//     for (let i = n % 2 == 0 ? 0 : 1; i < n - 1; ++i) {
//       if (a[i][0] == "1" && a[i + 1][0] == "1") {
//         flip(i, 0, i + 1, 0, i, 1)
//       } else if (a[i][0] == "1") {
//         flip(i, 0, i + 1, 1, i, 1)
//       } else if (a[i + 1][0] == "1") {
//         flip(i, 1, i + 1, 0, i, 1)
//       }
//     }
//   }
//
//   let proc3 = (x1: number, x2: number) => {
//     if (a[x1][x2] == "0") {
//       flip(x1 + 1, x2, x1, x2 + 1, x1 + 1, x2 + 1)
//       return
//     }
//
//     if (a[x1 + 1][x2] == "0") {
//       flip(x1, x2, x1, x2 + 1, x1 + 1, x2 + 1)
//       return
//     }
//
//     if (a[x1][x2 + 1] == "0") {
//       flip(x1, x2, x1 + 1, x2, x1 + 1, x2 + 1)
//       return
//     }
//
//     if (a[x1 + 1][x2 + 1] == "0") {
//       flip(x1 + 1, x2, x1, x2 + 1, x1, x2)
//     }
//   }
//
//   let proc1 = (x1: number, x2: number) => {
//     let zeroCoord = []
//     let oneCoord = []
//
//     for (let i = 0; i < 2; ++i) {
//       for (let j = 0; j < 2; ++j) {
//         if (a[x1 + i][x2 + j] == "0") {
//           zeroCoord.push({ x1: x1 + i, x2: x2 + j })
//         } else {
//           oneCoord.push({ x1: x1 + i, x2: x2 + j })
//         }
//       }
//     }
//
//     flip(
//       zeroCoord[0].x1,
//       zeroCoord[0].x2,
//       zeroCoord[1].x1,
//       zeroCoord[1].x2,
//       oneCoord[0].x1,
//       oneCoord[0].x2
//     )
//   }
//
//   let proc2 = (x1: number, x2: number) => {
//     let zeroCoord = []
//     let oneCoord = []
//
//     for (let i = 0; i < 2; ++i) {
//       for (let j = 0; j < 2; ++j) {
//         if (a[x1 + i][x2 + j] == "0") {
//           zeroCoord.push({ x1: x1 + i, x2: x2 + j })
//         } else {
//           oneCoord.push({ x1: x1 + i, x2: x2 + j })
//         }
//       }
//     }
//
//     flip(
//       zeroCoord[0].x1,
//       zeroCoord[0].x2,
//       zeroCoord[1].x1,
//       zeroCoord[1].x2,
//       oneCoord[0].x1,
//       oneCoord[0].x2
//     )
//   }
//
//   for (let i = n % 2 == 0 ? 0 : 1; i < n; i += 2) {
//     for (let j = m % 2 == 0 ? 0 : 1; j < m; j += 2) {
//       let nr0 = 0
//       let nr1 = 0
//
//       if (a[i][j] == "1") {
//         nr1++
//       } else {
//         nr0++
//       }
//
//       if (a[i + 1][j] == "1") {
//         nr1++
//       } else {
//         nr0++
//       }
//
//       if (a[i][j + 1] == "1") {
//         nr1++
//       } else {
//         nr0++
//       }
//
//       if (a[i + 1][j + 1] == "1") {
//         nr1++
//       } else {
//         nr0++
//       }
//
//       if (nr1 == 0) {
//         continue
//       }
//
//       if (nr1 == 3) {
//         proc3(i, j)
//         continue
//       }
//
//       if (nr1 == 2) {
//         proc2(i, j)
//         proc3(i, j)
//         continue
//       }
//
//       if (nr1 == 1) {
//         proc1(i, j)
//         proc2(i, j)
//         proc3(i, j)
//         continue
//       }
//
//       if (nr1 == 4) {
//         flip(i, j, i + 1, j, i + 1, j + 1)
//         proc1(i, j)
//         proc2(i, j)
//         proc3(i, j)
//         continue
//       }
//     }
//   }
//
//   io.puts(flips.length)
//   io.puts(flips.join(" "))
// }
//
// io.runEachTest(main)
// // io.runMain(main)


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

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

const mxN = 2e5+1;

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

		const frq = []; //Array(mxN).fill(0);
		for (const x of a) {
			if (!frq[x]) {
				frq[x] = 0;
			}
			frq[x]++;
		}

		a = [...new Set(a)];
		a.sort((x, y) => x - y);

		const ans = [];
		let cost = 0, extras = [], i = 0;
		for (let x = 0; x <= n; x++) {
			if (a[i] == x) {
				ans[x] = cost + frq[x];
				extras.push(...Array(frq[x]-1).fill(x));
				i++;
			} else { // a[i] > x
				ans[x] = cost;
				if (extras.length) {
					cost += x - extras.pop();
				} else {
					break;
				}
			}
		}

		while (ans.length < n+1) {
			ans.push(-1);
		}

		console.log(ans.join(' '));
	}
}

'use strict';

function solve(n, a) {
  let map = new Map();
  const res = [];
  const heap = [];
  for (let num of a) {
    var _map$get;
    map.set(num, ((_map$get = map.get(num)) !== null && _map$get !== void 0 ? _map$get : 0) + 1);
  }
  let cur = 0,
      op = 0;
  for (let i = 0; i <= n; i++) {
    if (cur === i) {
      if (map.has(i)) {
        res[i] = op + map.get(i);
        if (map.get(i) > 1) {
          heap.push([i, map.get(i) - 1]);
        }
        cur++;
      } else {
        res[i] = op;
        if (heap.length) {
          const top = heap[heap.length - 1];
          op += i - top[0];
          top[1]--;
          while (heap.length && heap[heap.length - 1][1] === 0) heap.pop();
          cur++;
        }
      }
    } else {
      res[i] = -1;
    }
  }
  return res.join(' ');
}

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

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

'use strict';

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(n, a) {
  let map = new Map();
  const res = [];
  const heap = new Heap((a, b) => b[0] - a[0]);
  for (let num of a) {
    var _map$get;
    map.set(num, ((_map$get = map.get(num)) !== null && _map$get !== void 0 ? _map$get : 0) + 1);
  }
  let cur = 0,
      op = 0;
  for (let i = 0; i <= n; i++) {
    if (cur === i) {
      if (map.has(i)) {
        res[i] = op + map.get(i);
        if (map.get(i) > 1) {
          heap.push([i, map.get(i) - 1]);
        }
        cur++;
      } else {
        res[i] = op;
        if (heap.size()) {
          const top = heap.top();
          op += i - top[0];
          top[1]--;
          if (top[1] === 0) heap.pop();
          cur++;
        }
      }
    } else {
      res[i] = -1;
    }
  }
  return res.join(' ');
}
class Heap {
  constructor(_comparator, arr) {
    _defineProperty(this, "_heap", []);
    this._comparator = _comparator;
    if (arr) {
      this._heap = [...arr];
      for (let i = arr.length >> 1; i; i--) this.down(i);
    }
  }
  swap(i, j) {
    [this._heap[i], this._heap[j]] = [this._heap[j], this._heap[i]];
  }
  _has(i) {
    return Object.prototype.hasOwnProperty.call(this._heap, i);
  }
  comparator(i, j) {
    return this._comparator(this._heap[i], this._heap[j]) < 0;
  }
  parent(i) {
    return i - 1 >> 1;
  }
  children(i) {
    return [2 * i + 1, 2 * i + 2];
  }
  up(i) {
    let parent = this.parent(i);
    while (i > 0 && this.comparator(i, parent)) {
      this.swap(i, parent);
      [i, parent] = [parent, parent - 1 >> 1];
    }
  }
  down(i) {
    let [left, right] = this.children(i);
    while (left < this._heap.length) {
      if (!this._has(right)) right = left;
      if (this.comparator(right, left)) [left, right] = [right, left];
      if (this.comparator(i, left)) break;
      this.swap(i, left);
      i = left;
      [left, right] = [2 * i + 1, 2 * i + 2];
    }
  }
  push(node) {
    this._heap.push(node);
    this.up(this._heap.length - 1);
  }
  pop() {
    if (this.size() === 0) return null;
    let res = this._heap[0];
    this.swap(0, this._heap.length - 1);
    this._heap.pop();
    this.down(0);
    return res;
  }
  remove(i) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this.swap(i, this._heap.length - 1);
    this._heap.pop();
    this.down(i);
    this.up(i);
    return res;
  }
  modify(i, val) {
    if (i >= this.size()) return;
    let res = this._heap[i];
    this._heap[i] = val;
    this.down(i);
    this.up(i);
    return res;
  }
  top() {
    if (this.size() === 0) return null;
    return this._heap[0];
  }
  size() {
    return this._heap.length;
  }
}

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

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

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

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

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let [n] = ra();
  let A = ra();
  LT({n, A});
  // PROCESSING:
  let cnt = {};
  for (let i=0; i<n; i++)
    cnt[i] = 0;
  for (let i=0; i<n; i++){
    cnt[A[i]]++;
  }
  let ans = [];
  let stack = [];
  let fix_zeros_price = 0;
  for (let i=0; i<=n; i++){
    ans.push(fix_zeros_price+(i<n ? cnt[i] : 0));
    while (cnt[i]>1){
      stack.push(i);
      cnt[i]--;
    }
    if (cnt[i]==0){
      if (stack.length){
        let top = stack.pop();
        fix_zeros_price += i-top;
      } else {
        ans.push(-1);
        break;
      }
    }
  }
  while (ans.length<=n) ans.push(-1)
  L(cnt)

  return ans;
};

'use strict';
const readline = require('readline');
const util = require('util');
const rl = readline.createInterface({
    input: process.stdin,
});
let pos = 0;
const words = [];
rl.on('line', (line) => {
    words.push.apply(words, line.split(' ').filter(s => s != ''));
});
rl.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(words[pos++]));
}
function nextStr() {
    return words[pos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        let n = nextInt();
        let cnt = af(n + 1).fill(0);
        for (let i = 0; i < n; i++) {
            let x = nextInt();
            cnt[x]++;
        }
        let sum = 0; // sum to complete j < i
        let rem = []; // indices with extra
        let res = af(n + 1).fill(0);
        let i = 0;
        for (; i <= n; i++) {
            let ans = sum;
            if (cnt[i] > 0) {
                ans += cnt[i];
            }
            printf("%d ", ans);
            if (cnt[i] > 1) {
                rem.push(i);
                res[i] = cnt[i] - 1;
            }
            else if (cnt[i] == 0) {
                if (rem.length > 0) {
                    let last = rem[rem.length - 1];
                    sum += i - last;
                    res[last]--;
                    if (res[last] == 0) {
                        rem.pop();
                    }
                }
                else {
                    i++;
                    break;
                }
            }
        }
        for (; i <= n; i++) {
            printf("-1 ");
        }
        printf("\n");
    }
}

// Generated by CoffeeScript 1.8.0
;(function() {
  var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;

  floor = Math.floor, min = Math.min;

  /*
  Default comparison function to be used
   */

  defaultCmp = function(x, y) {
    if (x < y) {
      return -1;
    }
    if (x > y) {
      return 1;
    }
    return 0;
  };

  /*
  Insert item x in list a, and keep it sorted assuming a is sorted.

  If x is already in a, insert it to the right of the rightmost x.

  Optional args lo (default 0) and hi (default a.length) bound the slice
  of a to be searched.
   */

  insort = function(a, x, lo, hi, cmp) {
    var mid;
    if (lo == null) {
      lo = 0;
    }
    if (cmp == null) {
      cmp = defaultCmp;
    }
    if (lo < 0) {
      throw new Error('lo must be non-negative');
    }
    if (hi == null) {
      hi = a.length;
    }
    while (lo < hi) {
      mid = floor((lo + hi) / 2);
      if (cmp(x, a[mid]) < 0) {
        hi = mid;
      } else {
        lo = mid + 1;
      }
    }
    return ([].splice.apply(a, [lo, lo - lo].concat(x)), x);
  };

  /*
  Push item onto heap, maintaining the heap invariant.
   */

  heappush = function(array, item, cmp) {
    if (cmp == null) {
      cmp = defaultCmp;
    }
    array.push(item);
    return _siftdown(array, 0, array.length - 1, cmp);
  };

  /*
  Pop the smallest item off the heap, maintaining the heap invariant.
   */

  heappop = function(array, cmp) {
    var lastelt, returnitem;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    lastelt = array.pop();
    if (array.length) {
      returnitem = array[0];
      array[0] = lastelt;
      _siftup(array, 0, cmp);
    } else {
      returnitem = lastelt;
    }
    return returnitem;
  };

  /*
  Pop and return the current smallest value, and add the new item.

  This is more efficient than heappop() followed by heappush(), and can be
  more appropriate when using a fixed size heap. Note that the value
  returned may be larger than item! That constrains reasonable use of
  this routine unless written as part of a conditional replacement:
      if item > array[0]
        item = heapreplace(array, item)
   */

  heapreplace = function(array, item, cmp) {
    var returnitem;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    returnitem = array[0];
    array[0] = item;
    _siftup(array, 0, cmp);
    return returnitem;
  };

  /*
  Fast version of a heappush followed by a heappop.
   */

  heappushpop = function(array, item, cmp) {
    var _ref;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    if (array.length && cmp(array[0], item) < 0) {
      _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];
      _siftup(array, 0, cmp);
    }
    return item;
  };

  /*
  Transform list into a heap, in-place, in O(array.length) time.
   */

  heapify = function(array, cmp) {
    var i, _i, _j, _len, _ref, _ref1, _results, _results1;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    _ref1 = (function() {
      _results1 = [];
      for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); }
      return _results1;
    }).apply(this).reverse();
    _results = [];
    for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
      i = _ref1[_i];
      _results.push(_siftup(array, i, cmp));
    }
    return _results;
  };

  /*
  Update the position of the given item in the heap.
  This function should be called every time the item is being modified.
   */

  updateItem = function(array, item, cmp) {
    var pos;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    pos = array.indexOf(item);
    if (pos === -1) {
      return;
    }
    _siftdown(array, 0, pos, cmp);
    return _siftup(array, pos, cmp);
  };

  /*
  Find the n largest elements in a dataset.
   */

  nlargest = function(array, n, cmp) {
    var elem, result, _i, _len, _ref;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    result = array.slice(0, n);
    if (!result.length) {
      return result;
    }
    heapify(result, cmp);
    _ref = array.slice(n);
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      elem = _ref[_i];
      heappushpop(result, elem, cmp);
    }
    return result.sort(cmp).reverse();
  };

  /*
  Find the n smallest elements in a dataset.
   */

  nsmallest = function(array, n, cmp) {
    var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    if (n * 10 <= array.length) {
      result = array.slice(0, n).sort(cmp);
      if (!result.length) {
        return result;
      }
      los = result[result.length - 1];
      _ref = array.slice(n);
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        elem = _ref[_i];
        if (cmp(elem, los) < 0) {
          insort(result, elem, 0, null, cmp);
          result.pop();
          los = result[result.length - 1];
        }
      }
      return result;
    }
    heapify(array, cmp);
    _results = [];
    for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) {
      _results.push(heappop(array, cmp));
    }
    return _results;
  };

  _siftdown = function(array, startpos, pos, cmp) {
    var newitem, parent, parentpos;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    newitem = array[pos];
    while (pos > startpos) {
      parentpos = (pos - 1) >> 1;
      parent = array[parentpos];
      if (cmp(newitem, parent) < 0) {
        array[pos] = parent;
        pos = parentpos;
        continue;
      }
      break;
    }
    return array[pos] = newitem;
  };

  _siftup = function(array, pos, cmp) {
    var childpos, endpos, newitem, rightpos, startpos;
    if (cmp == null) {
      cmp = defaultCmp;
    }
    endpos = array.length;
    startpos = pos;
    newitem = array[pos];
    childpos = 2 * pos + 1;
    while (childpos < endpos) {
      rightpos = childpos + 1;
      if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {
        childpos = rightpos;
      }
      array[pos] = array[childpos];
      pos = childpos;
      childpos = 2 * pos + 1;
    }
    array[pos] = newitem;
    return _siftdown(array, startpos, pos, cmp);
  };

  Heap = (function() {
    Heap.push = heappush;

    Heap.pop = heappop;

    Heap.replace = heapreplace;

    Heap.pushpop = heappushpop;

    Heap.heapify = heapify;

    Heap.updateItem = updateItem;

    Heap.nlargest = nlargest;

    Heap.nsmallest = nsmallest;

    function Heap(cmp) {
      this.cmp = cmp != null ? cmp : defaultCmp;
      this.nodes = [];
    }

    Heap.prototype.push = function(x) {
      return heappush(this.nodes, x, this.cmp);
    };

    Heap.prototype.pop = function() {
      return heappop(this.nodes, this.cmp);
    };

    Heap.prototype.peek = function() {
      return this.nodes[0];
    };

    Heap.prototype.contains = function(x) {
      return this.nodes.indexOf(x) !== -1;
    };

    Heap.prototype.replace = function(x) {
      return heapreplace(this.nodes, x, this.cmp);
    };

    Heap.prototype.pushpop = function(x) {
      return heappushpop(this.nodes, x, this.cmp);
    };

    Heap.prototype.heapify = function() {
      return heapify(this.nodes, this.cmp);
    };

    Heap.prototype.updateItem = function(x) {
      return updateItem(this.nodes, x, this.cmp);
    };

    Heap.prototype.clear = function() {
      return this.nodes = [];
    };

    Heap.prototype.empty = function() {
      return this.nodes.length === 0;
    };

    Heap.prototype.size = function() {
      return this.nodes.length;
    };

    Heap.prototype.clone = function() {
      var heap;
      heap = new Heap();
      heap.nodes = this.nodes.slice(0);
      return heap;
    };

    Heap.prototype.toArray = function() {
      return this.nodes.slice(0);
    };

    Heap.prototype.insert = Heap.prototype.push;

    Heap.prototype.top = Heap.prototype.peek;

    Heap.prototype.front = Heap.prototype.peek;

    Heap.prototype.has = Heap.prototype.contains;

    Heap.prototype.copy = Heap.prototype.clone;

    return Heap;

  })();

  (function(root, factory) {
    // if (typeof define === 'function' && define.amd) {
    //   return define([], factory);
    // } else if (typeof exports === 'object') {
    //   return module.exports = factory();
    // } else {
      return root.Heap = factory();
    // }
  })(this, function() {
    return Heap;
  });

}).call(this);
const Heap = this.Heap

const readline = require('readline')

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

function solve(n, arr) {
    const map = arr.reduce((o, x) => {
        o[x] = (o[x] || 0) + 1
        return o
    }, {})
    let mex = -1
    for (let i = 0; i <= n; i++) {
        if (!map[i]) {
            mex = i
            break
        }
    }
    const ans = Array(n + 1)
    let agg = 0
    const h = new Heap((a, b) => b - a)
    let fail = 0
    for (let i = 0; i <= n; i++) {
        if (i < mex) {
            // i -> i + 1
            ans[i] = map[i]
        } else if (i > mex) {
            if (fail) {
                ans[i] = -1
                continue
            }
            let now = agg
            // i -> i + 1
            if (map[i]) now += map[i]
            ans[i] = now
        } else {
            ans[i] = 0
        }
        //
        if (!map[i]) {
            if (h.empty()) {
                fail = 1
                continue
            }
            const p = h.peek()
            if (--map[p] <= 1) h.pop()
            agg += i - p
        } else if (map[i] > 1) {
            h.push(i)
        }
    }
    return ans.join(' ')
}


function getLine(){
    return readline().split(' ').map(function(x){
       return parseInt(x);
    });
}

function getInt(){
    return parseInt(readline());
}

var L = getLine();
var n = L[0];
var m = L[1];
var P = [];

for(var i = 0; i < n; i++){
    P[i] = getLine();
}
var T = [];
var G = [];
for(var i = 0; i < m; i++){
    T[i] = 0;
}
G[0] = 0;
for(var i = 1; i < n; i++){
    var min = n;
    for(var j = 0; j < m; j++){
        if(P[i - 1][j] > P[i][j]){
            T[j] = i;
        }
        min = Math.min(min, T[j]);
    }
    G[i] = min;
}
var k = getInt();
for(var i = 0; i < k; i++){
    var L = getLine();
    var l = L[0] - 1;
    var r = L[1] - 1;
    print(G[r] <= l ? "Yes" : "No");
}

var s = readline().split(" ");
var n = Number(s[0]);
var m = Number(s[1]);

var a = new Array(n);
for (var i = 0; i < n; ++i) {
    a[i] = readline().split(" ").map(function(each) {return Number(each)});
}

var track = new Array(n);
for (i = 0; i < n; ++i) {
    track[i] = new Array(m);
}

var track1 = new Array(n);
track1[0] = 1;

for (j = 0; j < m; ++j) {
    track[0][j] = 1;
}

for (i = 1; i < n; ++i) {
    var max = 0
    for (j = 0; j < m; ++j) {
        if (a[i][j] >= a[i - 1][j]) {
            track[i][j] = track[i - 1][j] + 1;
        } else {
            track[i][j] = 1;
        }

        if (track[i][j] > max)
            max = track[i][j];
    }

    track1[i] = max;
}

//for (i = 0; i < n; ++i) {
//    for (j = 0; j < m; ++j) {
//        write(track[i][j]);
//    }
//    print();
//}

function nonDesc(l, r) {
    if (track1[r - 1] >= r - l + 1) {
        return "Yes";
    }

    return "No";
}

var k = Number(readline());

for (i = 0; i < k; ++i) {
    var s = readline().split(" ");
    var l = Number(s[0]);
    var r = Number(s[1]);
    print(nonDesc(l, r));
}

function getLine(){
    return readline().split(' ').map(function(x){
       return parseInt(x);
    });
}

function getInt(){
    return parseInt(readline());
}

var L = getLine();
var n = L[0];
var m = L[1];
var P = [];

for(var i = 0; i < n; i++){
    P[i] = getLine();
}
var T = [];
var G = [];
for(var i = 0; i < m; i++){
    T[i] = 0;
}
G[0] = 0;
for(var i = 1; i < n; i++){
    var min = n;
    for(var j = 0; j < m; j++){
        if(P[i - 1][j] > P[i][j]){
            T[j] = i;
        }
        min = Math.min(min, T[j]);
    }
    G[i] = min;
}
var k = getInt();
for(var i = 0; i < k; i++){
    var L = getLine();
    var l = L[0] - 1;
    var r = L[1] - 1;
    print(G[r] <= l ? "YES" : "NO");
}

var s = readline().split(" ");
var n = Number(s[0]);
var m = Number(s[1]);

var a = new Array(n);
for (var i = 0; i < n; ++i) {
    a[i] = readline().split(" ").map(function(each) {return Number(each)});
}

var track = new Array(n);
for (i = 0; i < n; ++i) {
    track[i] = new Array(m);
}

for (j = 0; j < m; ++j) {
    track[0][j] = 1;
}

for (i = 1; i < n; ++i) {
    for (j = 0; j < m; ++j) {
        if (a[i][j] >= a[i - 1][j]) {
            track[i][j] = track[i - 1][j] + 1;
        } else {
            track[i][j] = 1;
        }
    }
}

//for (i = 0; i < n; ++i) {
//    for (j = 0; j < m; ++j) {
//        write(track[i][j]);
//    }
//    print();
//}

function nonDesc(l, r) {
    for (var i = 0; i < m; ++i) {
        if (track[r - 1][i] === r - l + 1) {
            return "Yes";
        }
    }

    return "No";
}

var k = Number(readline());

for (i = 0; i < k; ++i) {
    var s = readline().split(" ");
    var l = Number(s[0]);
    var r = Number(s[1]);
    print(nonDesc(l, r));
}

var s = readline().split(" ");
var n = Number(s[0]);
var m = Number(s[1]);

var a = new Array(n);
for (var i = 0; i < n; ++i) {
    a[i] = readline().split(" ").map(function(each) {return Number(each)});
}

var track = new Array(n);
for (i = 0; i < n; ++i) {
    track[i] = new Array(m);
}

for (j = 0; j < m; ++j) {
    track[0][j] = 1;
}

for (i = 1; i < n; ++i) {
    for (j = 0; j < m; ++j) {
        if (a[i][j] >= a[i - 1][j]) {
            track[i][j] = track[i - 1][j] + 1;
        } else {
            track[i][j] = 1;
        }
    }
}

//for (i = 0; i < n; ++i) {
//    for (j = 0; j < m; ++j) {
//        write(track[i][j]);
//    }
//    print();
//}

function nonDesc(l, r) {
    for (var i = 0; i < m; ++i) {
        if (track[r - 1][i] === r - l + 1) {
            return "YES";
        }
    }

    return "NO";
}

var k = Number(readline());

for (i = 0; i < k; ++i) {
    var s = readline().split(" ");
    var l = Number(s[0]);
    var r = Number(s[1]);
    print(nonDesc(l, r));
}


'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 m = rn(),
        a = rns(m);
  const n = Math.log2(m);
  let res = 0;
  const swap = (i, j) => [a[i], a[j]] = [a[j], a[i]];
  for (let i = 1; i <= n; i++) {
    const d = 2 ** i,
          d1 = d / 2;
    for (let j = d - 1; j < m; j += d) {
      const k = j - d1;
      if (a[j] + d1 === a[k]) {
        res++;
        swap(j, k);
      } else if (a[j] === a[k] + d1) {
        continue;
      } else {
        return -1;
      }
    }
  }
  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 = 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(/\s+/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

"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 ans = 0,
      op = 0;
    const trav = (n) => {
      const helper = (st, end, k) => {
        if (st === end) {
          return { min: arr[st], max: arr[st] };
        }
        let mid = Math.floor((st + end) / 2);
        let left = helper(st, mid, k / 2);
        let right = helper(mid + 1, end, k / 2);
        if (left.min > right.min) op++;
        let min = Math.min(left.min, left.max, right.min, right.max);
        let max = Math.max(left.min, left.max, right.min, right.max);
        let dif = Math.abs(min - max) + 1;
        if (dif !== k) ans = -1;
        return { min: min, max: max };
      };
      helper(0, n - 1, n);
    };
    trav(n);
    if (ans === -1) console.log(-1);
    else console.log(op);
  }
};
solve();

const readline = require('readline')

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

let ans
function solve(n, arr) {
    if (n === 1) return 0
    ans = 0
    helper(arr, 0, n - 1)
// console.log(arr.join(' '))
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] < arr[i - 1]) return -1
    }
    return ans
}
function helper(arr, l, r) {
    if (l + 1 === r) {
        if (arr[l] > arr[r]) {
            [arr[l], arr[r]] = [arr[r], arr[l]]
            ans++
        }
    } else {
        const h = (r - l + 1) / 2
        helper(arr, l, l + h - 1)
        helper(arr, l + h, r)
        if (arr[l] > arr[l + h]) {
            ans++
            for (let i = 0; i < h; i++) {
                [arr[l + i], arr[l + h + i]] = [arr[l + h + i], arr[l + i]]
            }
        }
    }
}


function main() {
    [n, m] = readInts()
    diff = []
    sm = 0
    for (i = 0; i<n; i++){
        [a,b] = readInts()
        sm += a
        diff.push(a-b)
    }
    sort(diff, false)
    if (sm<=m){
        print(0)
    } else {
        for (i=0; i<n; i++){
            sm -= diff[i]
            if (sm<=m){
                print(i+1)
                return
            }
        }
        print(-1)
    }
}

const TESTCASES = false
/* NodeJS Footer by @satyamcse and @shivam1420*/
var readline = require('readline');
process.stdin.setEncoding('utf-8');
var rl = readline.createInterface({input: process.stdin, output: process.stdout});
var inp = "";
rl.on('line' , v => inp += v+"\n");
rl.on('close', () => {
    inp = inp.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
    if (TESTCASES){
        const cnt = readInt()
        for (let i = 0; i<cnt; i++){
            main()
        }
    } else {main()}
});
function sort(a, inc = true) {
    if(inc) a.sort((a, b) => a - b)
    else a.sort((a, b) => b - a)
}
var ptr = 0
function print(...x) {console.log(...x)}
function readInt() {return +inp[ptr++]}
function readLine() {return inp[ptr++]}
function readInts() {return inp[ptr++].split(' ').map(a => +a)}

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum = 0,sumArc = 0;
    for(var i = 0; i < n ;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += +s[1];
        me.push(s[0] - s[1]);
    }
    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-m;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a > 0){
        res++;
        a -= me.pop();
    }

    print(res);
}

main();

function main() {
  const is = new Scanner();
  const [n, m] = is.nextArray(Number);
  let normal = 0, a, b;
  const diff = [];
  for (let i = 0; i < n; i += 1) {
    [a, b] = is.nextArray(Number);
    diff.push(a - b);
    normal += a;
  }

  diff.sort((u, v) => u - v);
  diff.reverse();
  let song = 0;
  for (let i = 0; normal > m && i < n; i += 1) {
    normal -= diff[i];
    song += 1;
  }
  console.log(normal > m ? -1 : song);
}

/*
 *  Api Scanner
 */
class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++].trim(); // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray(fn) {
    const array = this.nextLine().split(' ');
    return fn === String ? array : array.map(fn);
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let ptr = 0
  const [n, m] = readInts(input, ptr++)
  const as = new Array(n)
  const bs = new Array(n)
  for(let i = 0; i < n; i++) {
    let x = readInts(input, ptr++);
    as[i] = x[0]
    bs[i] = x[1]
  }
  // console.log(as, bs)
  let sumA = as.reduce((a, b) => a + b, 0)
  let sumB = bs.reduce((a, b) => a + b, 0)
  if(sumA <= m) wr(0)
  else if(sumB > m) wr(-1)
  else {
    let diff = new Array(n)
    for(let i = 0; i < n; i++) {
      diff[i] = as[i] - bs[i]
    }
    sort(diff, false)
    const d = sumA - m
    let x = 0
    let count = 0
    let i = 0
    while(x < d) {
      x += diff[i++]
      count++
    }
    wr(count)
  }
}

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum = 0,sumArc = 0;
    for(var i = 0; i<n ;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += +s[1];
        me.push(s[0] - s[1]);
    }

    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-m;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a <= 0){
        res++;
        a -= me.pop()
    }

    print(res);
}

main();

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum = 0,sumArc = 0;
    for(var i = 0; i<n ;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += +s[1];
        me.push(s[0] - s[1]);
    }

    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-sumArc;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a <= 0){
        res++;
        a -= me.pop()
    }

    print(res);
}

main();

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum,sumArc;
    for(var i = 0;i<n;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += +s[1];
        me.push(s[0] - s[1]);
    }

    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-sumArc;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a <= 0){
        res++;
        a -= me.pop()
    }

}

main();

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum = 0,sumArc = 0;
    for(var i = 0; i < n ;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += +s[1];
        me.push(s[0] - s[1]);
    }
    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-m;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a > 0){
        print('asd')
        res++;
        a -= me.pop();
        print(a);
    }

    print(res);
}

main();

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum,sumArc;
    for(var i = 0;i<n;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += +s[1];
        me.push(s[0] - s[1]);
    }

    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-sumArc;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a <= 0){
        res++;
        a -= me.pop()
    }

    print(res);
}

main();

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum,sumArc;
    for(var i = 0;i<n;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += s[1];
        me.push(s[0] - s[1]);
    }

    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-sumArc;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a <= 0){
        res++;
        a -= me.pop()
    }

}

main();


'use strict';

var readline = require('readline');

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

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

function solve(nums) {
  const [a, b, c] = nums
  return [a+b+c,b+c,c].join(' ')
}

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

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

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; i++){
        var k = lines[i].split(' ').map(Number);
        var a = k[0], b = k[1], c = k[2];
        console.log(a + b + c, b + c, c);
    }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

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

    for (let test = 0; test < N; test++) {
        let [a, b, c] = readline().split(' ').map(Number);
        output(`${a + b + c} ${b + c} ${c}`);
    }
}

'use strict';

var readline = require('readline');

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

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

function solve(nums) {
  const [a, b, c] = nums,
        max = Math.max(...nums);
  let x = 0,
      y = 0,
      z = 0;
  if (max === a) {
    x = a;
    z = x + c;
    y = z + b;
  } else if (max === b) {
    y = b;
    x = y + a;
    z = x + c;
  } else {
    z = c;
    y = z + b;
    x = y + a;
  }
  return [x, y, z].join(' ');
}

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

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

const solve = (a,b,c)=>{
     console.log(`${a+b+c} ${b+c} ${c}`);
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for (let i = 0; i < t; i++) {
       let n = readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(...n);
  }
}
main();

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

let lines = 0;
const compute = (x, y, a, c) => {
  if (x + a - (x % y) > c) {
    return x + a - (x % y);
  } else {
    return y * x + a;
  }
};

rl.on("line", function (line) {
  if (lines !== 0) {
    let [a, b, c] = line.split(" ").map(BigInt);
    let x = c + 1n,
      y = a + 1n,
      z = b + 1n;
    while (x % y !== a || y % z !== b || z % x !== c) {
      if (x % y !== a) {
        x = compute(x, y, a, c);
        continue;
      } else if (y % z !== b) {
        y = compute(y, z, b, a);
        continue;
      } else if (z % x !== c) {
        z = compute(z, x, c, b);
        continue;
      }
    }
    console.log([x, y, z].join(" "));
  }

  lines++;
});

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

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

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`\nTest #${testN}`, obj);

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

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

// SOLUTION:
IS_MULTITEST = true;

const calc = (testN)=>{
  // READING:
  let [a, b, c] = ra();
  LT({a, b, c});
  // PROCESSING:
  let x = BigInt(a)+BigInt(b)*BigInt(1e8);
  return [x.toString(), b, (x+BigInt(c)).toString()];
};

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

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

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const calc = ()=>{
    /* read */
    let [a, b, c] = ra();
    let result = [a + b + c, b + c, c];
    return result.join(' ');
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc());
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

var number_of_test = readline();

function get_numbers_with_solution(){
   var arr = readline().split(' ') ;
   var a = parseInt( arr[0] ),
       b = parseInt( arr[1] ),
       c = parseInt( arr[2] )
   var z = c,
       y = c + b,
       x = c + b + a;
   print(x + " " + y + " " + z ) ;
}

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

   get_numbers_with_solution();

}

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];
    console.log(1, 1, 1);
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

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

    for (let test = 0; test < N; test++) {
        let [a, b, c] = readline().split(' ').map(Number);
        output(`${a + b + c} ${a + b} ${c}`);
    }
}

var number_of_test = readline();

function get_numbers_with_solution(){
   var a = parseInt( readline() ),
       b = parseInt( readline() ),
       c = parseInt( readline() );

   var z = c,
       y = c + b,
       x = c + b + a;

   print(x + " " + y + " " + z + "\n") ;
}

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

   get_numbers_with_solution();

}

var number_of_test = readline();

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

   var a = parseInt( readline() ),
       b = parseInt( readline() ),
       c = parseInt( readline() );

   var z = c,
       y = c + b,
       x = c + b + a;

   print(x + " " + y + " " + z )

}

var number_of_test = readline();

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

   var a = parseInt( readline() ),
       b = parseInt( readline() ),
       c = parseInt( readline() );

   var z = c,
       y = c + b,
       x = c + b + a;

   print(x%y + " " + y%z + " " + z%x);
   print("----------")
   print(x + " " + y + " " + z )

}


print(function(n, x) {

	var ans = 0;
	var a = readline().split(' ').map(Number);
	var m = n;
	if (a.indexOf(x) === -1) {
		a.push(x);
		m++;
	}
	a.sort(function(a, b) {
		return a - b;
	});
	a.unshift(1e15);
	var y1 = a.indexOf(x);
	var y2 = a.lastIndexOf(x);
	var y = Math.floor((n + 1) / 2);
	if (a[y] === x) {
		return m - n;
	}

	if (y < y1) {
		while (Math.floor((m + 1) / 2) !== y1) {
			m++;
		}
		return m - n;
	}

	if (y > y2) {
		while (Math.floor((m + 1) / 2) !== y2) {
			m++;
			y2++;
		}
		return m - n;
	}

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

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

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

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

function printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], x = data[1],
    arr = tokenizeIntegers(readline());
  arr.sort(function (a, b) {
    return a - b;
  });
  var count = 0;
  if (arr.indexOf(x) == -1) {
    var left = 0;
    while (left < n && arr[left] < x) {
      ++left;
    }
    var right = n-left;
    count = 1;
  } else {
    var left = arr.indexOf(x),
      right = left;
    while (right+1 < n && arr[right+1] == x) {
      ++right;
    }
    var pos = Math.floor((n-1)/2);
    if (pos > right) {
      pos = right;
    } else if (pos < left) {
      pos = left;
    }
    left = pos;
    right = n-1-pos;
  }
  if (left >= right) {
    count += left-right;
  } else {
    count += right-left-1;
  }
  print(count);
}

main();

print(function(n, x) {

	var ans = 0;
	var a = readline().split(' ').map(Number);
	var m = n;
	if (a.indexOf(x) === -1) {
		a.push(x);
		m++;
	}
	a.sort(function(a, b) {
		return a - b;
	});
	var y1 = a.indexOf(x) + 1;
	var y2 = a.lastIndexOf(x) + 1;
	var y = Math.floor((n + 1) / 2);
	if (a[y] === x) {
		return m - n;
	}

	if (y < y1) {
		while (Math.floor((m + 1) / 2) !== y1) {
			m++;
		}
		return m - n;
	}

	if (y > y2) {
		while (Math.floor((m + 1) / 2) !== y2) {
			m++;
			y2++;
		}
		return m - n;
	}

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

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

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

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

function printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], x = data[1],
    arr = tokenizeIntegers(readline());
  arr.sort(function (a, b) {
    return a - b;
  });
  //print(arr.join(' '));
  if (arr.indexOf(x) == -1) {
    var left = 0;
    while (left < n && arr[left] < x) {
      ++left;
    }
    var right = n-left,
        count = 1;
    ++left;
    if (left > right) {
      count += left-right-1;
    } else {
      count += right-left;
    }
    print(count);
    return;
  } else {
    var left = arr.indexOf(x),
      right = left;
    while (right+1 < n && arr[right+1] == x) {
      ++right;
    }
    var median = Math.floor((n-1)/2);
    //print(left, right, median);
    if (median >= left && median <= right) {
      print(0);
    } else if (median < left) {
      print(left-median);
    } else {
      print(median-right);
    }
  }
}

main();

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

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

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

function printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], x = data[1],
    arr = tokenizeIntegers(readline());
  arr.sort(function (a, b) {
    return a - b;
  });
  //print(arr.join(' '));
  if (arr.indexOf(x) == -1) {
    var left = 0;
    while (left < n && arr[left] < x) {
      ++left;
    }
    var right = n-left,
        count = 1;
    ++left;
    if (left > right) {
      count += left-right-1;
    } else {
      count += right-left;
    }
    print(count);
    return;
  } else {
    var left = arr.indexOf(x),
      right = left;
    while (right+1 < n && arr[right+1] == x) {
      ++right;
    }
    var median = Math.floor(n/2);
    if (median >= left && median <= right) {
      print(0);
    } else if (median < left) {
      print(left-median);
    } else {
      print(median-right);
    }
  }
}

main();


const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')
const N = Number(inputs[0])
for (let _ = 0, __ = 1; _ < N; _++) {
  const n = Number(inputs[__++]),
    data = inputs[__++].split(' ').map(Number)
  main(n, data)
}

function main(n, data) {
  let count = new Array(n + 1).fill(0)
  for (let i = 0; i < n; i++) {
    if (data[i] > n || data[i] > data[(i - 1 + n) % n] + 1) {
      console.log('NO')
      return
    }
    count[data[i]]++
  }
  if (count[1] !== 1) {
    console.log('NO')
    return
  }
  console.log('YES')
}

const readline = require('readline')

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

function solve(n, arr) {
    // has 1
    // +1 or -x or 0
    let has1 = 0
    for (let i = 0; i < arr.length; i++) {
        const x = arr[i]
        if (x < 1 || x > n) return false
        if (x === 1) has1++
        if (x === n) {
            if (i + 1 < arr.length && arr[i + 1] !== 1) return false
        }
        // if (i) {
            const d = arr[i] - (i ? arr[i - 1] : arr[n - 1])
            if (d === 1 || d <= 0) {
                //
            } else {
                return false
            }
        // }
    }
    if (has1 !== 1) return false
    return true
}

const readline = require('readline')

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

function solve(n, arr) {
    // has 1
    // +1 or -x or 0
    let has1 = false
    for (let i = 0; i < arr.length; i++) {
        const x = arr[i]
        if (x < 1 || x > n) return false
        if (x === 1) has1 = true
        if (x === n) {
            if (i + 1 < arr.length && arr[i + 1] !== 1) return false
        }
        if (i) {
            const d = arr[i] - arr[i - 1]
            if (d === 1 || d <= 0) {
                //
            } else {
                return false
            }
        }
    }
    if (!has1) return false
    return true
}