This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.You are given a binary table of size $$$n \times m$$$. This table consists of symbols $$$0$$$ and $$$1$$$.You can make such operation: select $$$3$$$ different cells that belong to one $$$2 \times 2$$$ square and change the symbols in these cells (change $$$0$$$ to $$$1$$$ and $$$1$$$ to $$$0$$$).Your task is to make all symbols in the table equal to $$$0$$$. You are allowed to make at most $$$nm$$$ operations. You don't need to minimize the number of operations.It can be proved, that it is always possible.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 5000$$$) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n, m \leq 100$$$). Each of the next $$$n$$$ lines contains a binary string of length $$$m$$$, describing the symbols of the next row of the table. It is guaranteed, that the sum of $$$nm$$$ for all test cases does not exceed $$$20000$$$.

For each test case print the integer $$$k$$$ ($$$0 \leq k \leq nm$$$) — the number of operations. In the each of the next $$$k$$$ lines print $$$6$$$ integers $$$x_1, y_1, x_2, y_2, x_3, y_3$$$ ($$$1 \leq x_1, x_2, x_3 \leq n, 1 \leq y_1, y_2, y_3 \leq m$$$) describing the next operation. This operation will be made with three cells $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$. These three cells should be different. These three cells should belong to some $$$2 \times 2$$$ square.

NoteIn the first test case, it is possible to make only one operation with cells $$$(1, 1)$$$, $$$(2, 1)$$$, $$$(2, 2)$$$. After that, all symbols will be equal to $$$0$$$.In the second test case:  operation with cells $$$(2, 1)$$$, $$$(3, 1)$$$, $$$(3, 2)$$$. After it the table will be: 011001000  operation with cells $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$. After it the table will be: 000000000 In the fifth test case:  operation with cells $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$. After it the table will be: 010110  operation with cells $$$(1, 2)$$$, $$$(2, 1)$$$, $$$(2, 2)$$$. After it the table will be: 000000

(()=>{"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)


Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 10 000, n ≥ 2m) — the number of participants of the qualifying contest and the number of regions in Berland. Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive). It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.

Print m lines. On the i-th line print the team of the i-th region — the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region.

5 2
Ivanov 1 763
Andreev 2 800
Petrov 1 595
Sidorov 1 790
Semenov 2 503

5 2
Ivanov 1 800
Andreev 2 763
Petrov 1 800
Sidorov 1 800
Semenov 2 503

NoteIn the first sample region teams are uniquely determined.In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.

var input = readline().split(' ')
  , n = +input[0]
  , m = +input[1]
  , teams = [];

for (var i = 0, info = null; i < n; i++) {
  info = readline().split(' ');
  if (teams[info[1]] === undefined) {
    teams[info[1]]= [];
  }
  if (teams[info[1]][info[2]] === undefined ) {
    teams[info[1]][info[2]] = [];
  }
  teams[info[1]][info[2]].push(info[0]);
}

for (var i = 1, keys = []; i < teams.length; i++) {
  keys = Object.keys(teams[i]).reverse();
  if (teams[i][keys[0]].length > 2) {
    print('?');
    continue;
  } else if (teams[i][keys[0]].length === 2) {
      print(teams[i][keys[0]].join(' '));
      continue;
  } else if (teams[i][keys[1]].length > 1) {
    print('?');
    continue;
  } else {
    print(teams[i][keys[0]] + ' ' + teams[i][keys[1]]);
    continue;
  }
}

var arr = readline().split(" ", 2).map(Number);
var n = arr[0], m = arr[1];

var array = new Array(m);
for (var i = 0; i < m; ++i) {
    array[i] = [];
}
for (var i = 0; i < n; ++i) {
    arr = readline().split(" ", 3);
    array[Number(arr[1]) - 1].push({
        name: arr[0],
        score: Number(arr[2])
    });
}

function getMaxIndex(array, l, r) {
    var value = array[l].score, index = l;
    for (var i = l + 1; i < r; ++i) {
        if (array[i].score > value) {
            value = array[i].score;
            index = i;
        }
    }
    return index;
}
function swap(array, x, y) {
    if (x !== y && x >= 0 && x < array.length &&
        y >= 0 && y < array.length) {
            var temp = array[x];
            array[x] = array[y];
            array[y] = temp;
        }
}
function firstThree(array) {
    for (var i = 0; i < 3; ++i) {
        swap(array, i, getMaxIndex(array, i, array.length));
    }
}
for (var i = 0; i < m; ++i) {
    if (array[i].length === 2) {
        print(array[i][0].name + " " + array[i][1].name);
    } else {
        firstThree(array[i]);
        if (array[i][1].score === array[i][2].score) {
            print("?");
        } else {
            print(array[i][0].name + " " + array[i][1].name);
        }
    }
}

var isCodeForces = true;
var line, lines, echo;
if(!isCodeForces){
	lines = '';
	process.stdin.resume();
	process.stdin.on('data', function(buffer){lines += buffer.toString();});
	process.stdin.on('end', function(){
		lines = lines.trim().split('\n');
		echo = console.log;
		wrapper();
	});
}else{
	lines = [];
	while(line = readline()){
		lines.push(line);
	}
	echo = print;
	wrapper();
}

function wrapper(){
	init();
	var res = main();
	if(res != undefined){
		echo(res);
	}
}

function main(){
	var line = lines[0].split(' ');
	var n = parseInt(line[0]), m = parseInt(line[1]), res = new Array(m + 1).join(' ').split('').map(function(){
		return [];
	});
	for(var i = 1; i <= n; i++){
		line = lines[i].split(' ');
		var name = line[0], region = parseInt(line[1]) - 1, score = parseInt(line[2]);
		res[region].push([score, name]);
	}
	for(i = 0; i < m; i++){
		var row = res[i].sort(function(a, b){
			return b[0] - a[0];
		});
		if(row.length >= 3 && row[1][0] == row[2][0])
			res[i] = '?';
		else {
			res[i] = `${row[0][1]} ${row[1][1]}`;
		}
	}
	return res.join('\n');
}

function init(){
}


You are given a permutation of length $$$n$$$. Recall that the permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2, 3, 1, 5, 4]$$$ is a permutation, but $$$[1, 2, 2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1, 3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).You can perform at most $$$n-1$$$ operations with the given permutation (it is possible that you don't perform any operations at all). The $$$i$$$-th operation allows you to swap elements of the given permutation on positions $$$i$$$ and $$$i+1$$$. Each operation can be performed at most once. The operations can be performed in arbitrary order.Your task is to find the lexicographically minimum possible permutation obtained by performing some of the given operations in some order.You can see the definition of the lexicographical order in the notes section.You have to answer $$$q$$$ independent test cases.For example, let's consider the permutation $$$[5, 4, 1, 3, 2]$$$. The minimum possible permutation we can obtain is $$$[1, 5, 2, 4, 3]$$$ and we can do it in the following way:  perform the second operation (swap the second and the third elements) and obtain the permutation $$$[5, 1, 4, 3, 2]$$$;  perform the fourth operation (swap the fourth and the fifth elements) and obtain the permutation $$$[5, 1, 4, 2, 3]$$$;  perform the third operation (swap the third and the fourth elements) and obtain the permutation $$$[5, 1, 2, 4, 3]$$$.  perform the first operation (swap the first and the second elements) and obtain the permutation $$$[1, 5, 2, 4, 3]$$$; Another example is $$$[1, 2, 4, 3]$$$. The minimum possible permutation we can obtain is $$$[1, 2, 3, 4]$$$ by performing the third operation (swap the third and the fourth elements).

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of test cases. Then $$$q$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation.

For each test case, print the answer on it — the lexicograhically minimum possible permutation obtained by performing some of the given operations in some order.

NoteRecall that the permutation $$$p$$$ of length $$$n$$$ is lexicographically less than the permutation $$$q$$$ of length $$$n$$$ if there is such index $$$i \le n$$$ that for all $$$j$$$ from $$$1$$$ to $$$i - 1$$$ the condition $$$p_j = q_j$$$ is satisfied, and $$$p_i < q_i$$$. For example:  $$$p = [1, 3, 5, 2, 4]$$$ is less than $$$q = [1, 3, 5, 4, 2]$$$ (such $$$i=4$$$ exists, that $$$p_i < q_i$$$ and for each $$$j < i$$$ holds $$$p_j = q_j$$$),  $$$p = [1, 2]$$$ is less than $$$q = [2, 1]$$$ (such $$$i=1$$$ exists, that $$$p_i < q_i$$$ and for each $$$j < i$$$ holds $$$p_j = q_j$$$).

//DONE:
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')
  const q = parseInt(arr.shift())

  for(let i = 0; i < q; i++) {
    const n = parseInt(arr[2 * i])
    const no = arr[2 * i + 1].split(' ').map(a => parseInt(a))
    var a = min(no)
    console.log(a.join(' '))
  }
})

function min(no) {
  const n = no.length
  const i = no.indexOf(Math.min.apply(null, no))
  // console.log(i, no)
  if(i == n - 1) {
    const s  = no.pop()
    no.unshift(s)
    return no
  }
  else if(i == 0) {
    return [no[0]].concat(min(no.slice(1, n)))
  }

  else {
    // console.log(no)
    var a = no.slice(0, i + 1)
    a.unshift(a.pop())
    no = a.concat(no.slice(i + 1, n))
    // console.log(a, no)
    b = min(no.slice(i, n))
    // console.log(b)
    return a.slice(0, a.length - 1).concat(b)
  }
}

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

let lineNumber = 0;
process.stdin.on('data', input => {
    input.split('\r\n').forEach(line => {
        // console.log('on line', lineNumber, input);
        if (++lineNumber >= 3 && lineNumber % 2 === 1) { resolve(line) }
    });
});

function resolve(input) {
    let permutation = input.split(' ').map(v => parseInt(v, 10));
    let index = 0;
    while (index < permutation.length - 1) {
        const value = Math.min(...permutation.slice(index));
        const valueIndex = permutation.indexOf(value);
        if (valueIndex > index) {
            for (let i = valueIndex - 1; i >= index; i--) {
                permutation[i + 1] = permutation[i];
            }
            permutation[index] = value;
            index = valueIndex - 1;
        }
        index++;
    }
    console.log(permutation.join(' '));
}

process.stdin.setEncoding('utf-8');
process.stdin.on('data', input => {
    input.split('\r\n')
        .filter((_, index) => index >= 2 && index % 2 === 0)
        .map(line => line.split(' ').map(v => parseInt(v, 10)))
        .forEach(permutation => {
            let index = 0;
            while (index < permutation.length - 1) {
                const value = Math.min(...permutation.slice(index));
                const valueIndex = permutation.indexOf(value);
                for (let i = valueIndex - 1; i >= index; i--) { permutation[i + 1] = permutation[i]; }
                permutation[index] = value;
                index = Math.max(valueIndex, index + 1);
            }
            console.log(permutation.join(' '));
        });
});

process.stdin.setEncoding('utf-8').on('data', input => {
    input.split('\r\n').filter((_, i) => i >= 2 && i % 2 === 0).map(l => l.split(' ').map(v => parseInt(v, 10)))
        .forEach(q => {
            for (let index = 0; index < q.length; index++) {
                const v = Math.min(...q.slice(index));
                const vIndex = q.indexOf(v);
                for (let i = vIndex - 1; i >= index; i--) { q[i + 1] = q[i]; }
                q[index] = v;
                index = Math.max(vIndex - 1, index);
            }
            console.log(q.join(' '));
        });
});

'use strict'

const problem = (n, p) => {
    let a = 0;
    for (let i = 1; i <= n; i++) {
        const b = p.indexOf(i);

        for (let j = b; j > a; j--) {
            const c = p[j]; p[j] = p[j - 1]; p[j - 1] = c;
        }
        if (a === b) a = b + 1;
        if (a < b) a = b;
    }
    return p.join(' ');
}

let q = +readline();
while (q--) print(problem(+readline(), readline().split(' ').map(Number)));

  var count = +readline();
  while (count--) {
    var n = +readline();
    var elements = readline()
      .split(" ")
      .map(Number);

    var a = 0;

    for (var i = 1; i < n + 1; i++) {
      var index = elements.indexOf(i);

      for (var j = index; j > a; j--) {
        var buf = elements[j - 1];
        elements[j - 1] = elements[j];
        elements[j] = buf;
      }

      if (a === index) a = index + 1;
      if (a < index) a = index;
    }
    print(elements.join(" "));
  }

//DONE:
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')
  const q = parseInt(arr.shift())

  for(let i = 0; i < q; i++) {
    const n = parseInt(arr[2 * i])
    const no = arr[2 * i + 1].split(' ').map(a => parseInt(a))
    // console.log(no)
    var a = min(no)
    console.log(a.join(' '))
  }
})

function min(no) {
  const n = no.length
  const i = no.indexOf(Math.min.apply(null, no))
  // console.log(i, Math.min.apply(null, no))
  if(i == n - 1) {
    const s  = no.pop()
    no.unshift(s)
    return no
  }
  else if(i == 0) {
    return [no[0]].concat(min(no.slice(1, n)))
  }

  else {
    var a = no.slice(0, i + 1)
    a.unshift(a.pop())
    var b = min(no.slice(i + 1, n))
    // console.log(a, no.slice(i + 1, n))
    no = a.concat(b)
    if(no[i] > no[i + 1]) {
      const temp = no[i]
      no[i] = no[i + 1]
      no[i + 1] = temp
    }
    return no
  }
}

//DONE:
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')
  const q = parseInt(arr.shift())

  for(let i = 0; i < q; i++) {
    const n = parseInt(arr[2 * i])
    const no = arr[2 * i + 1].split(' ').map(a => parseInt(a))
    // console.log(no)
    var a = min(no)
    console.log(a.join(' '))
  }
})

function min(no) {
  const n = no.length
  const i = no.indexOf(Math.min.apply(null, no))
  // console.log(i, Math.min.apply(null, no))
  if(i == n - 1) {
    const s  = no.pop()
    no.unshift(s)
    return no
  }
  else if(i == 0) {
    return [no[0]].concat(min(no.slice(1, n)))
  }

  else {
    // console.log(no)
    var a = no.slice(0, i + 1)
    a.unshift(a.pop())
    no = a.concat(no.slice(i + 1, n))
    if(no[i] > no[i + 1]) {
      const temp = no[i]
      no[i] = no[i + 1]
      no[i + 1] = temp
      a = no.slice(0, i + 1)
    }
    // console.log(a, no)
    b = min(no.slice(i + 1, n))
    // console.log(b)
    return a.concat(b)
  }
}

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

let lineNumber = 0;
console.log('started');
process.stdin.on('data', input => {
    input.split('\r\n').forEach(line => {
        // console.log('on line', lineNumber, input);
        if (++lineNumber >= 3 && lineNumber % 2 === 1) { resolve(line) }
    });
});

function resolve(input) {
    let permutation = input.split(' ').map(v => parseInt(v, 10));
    let index = 0;
    while (index < permutation.length - 1) {
        const value = Math.min(...permutation.slice(index));
        const valueIndex = permutation.indexOf(value);
        if (valueIndex > index) {
            for (let i = valueIndex - 1; i >= index; i--) {
                permutation[i + 1] = permutation[i];
            }
            permutation[index] = value;
            index = valueIndex - 1;
        }
        index++;
    }
    console.log(permutation.join(' '));
}

'use strict'

const problem = (n, p) => {
    let a = 0, b, i = 0;
    while(i < n && a <= (b = p.indexOf(++i))) {
        for (let j = b; j > a; j--) {
            const c = p[j];
            p[j] = p[j - 1];
            p[j - 1] = c;
        }
        a = +(a === b) + b;
    }
    return p.join(' ');
}

let q = +readline();
while (q--) print(problem(+readline(), readline().split(' ').map(Number)));

'use strict'

const problem = (n, p) => {
    let a = 0;
    for (let i = 1; i < n; i++) {
        const b = p.indexOf(i);
        for (let j = b; j > a; j--) {
            const c = p[j];
            p[j] = p[j - 1];
            p[j - 1] = c;
        }
        a = +(a === b) + b;
    }
    return p.join(' ');
}

let q = +readline();
while (q--) {
    print(problem(+readline(), readline().split(' ').map(Number)));
}

  var sets = parseInt(readline());

  for (var i = 0; i < sets; i++) {
    var elementCount = parseInt(readline());
    var elements = readline()
      .split(" ")
      .map(function(value) {
        return parseInt(value);
      });
    var actions = Array(elementCount + 1).map(function(value) {
      return true;
    });

    for (var j = 0; j < actions.length; j++) {
      actions[j] = true;
    }
    var changed = true;

    for (var elem = 1; elem < elementCount + 1 && changed; elem++) {
      changed = false;

      if (elem === elements[elem - 1]) {
        elem++;
        changed = true;
        continue;
      }

      for (var j = 0; j < elementCount; j++) {
        if (elements[j + 1] === elem && elements[j] > elem && actions[j]) {
          var tmp = elements[j];
          elements[j] = elements[j + 1];
          elements[j + 1] = tmp;
          actions[j] = false;
          elem++;
          changed = true;
        }
      }
      elem = 0;
    }

    print(elements.join(' '));
  }

  var sets = parseInt(readline());

  for (var i = 0; i < sets; i++) {
    var elementCount = parseInt(readline());
    var elements = readline()
      .split(" ")
      .map(function(value) {
        return parseInt(value);
      });
    var actions = Array(elementCount + 1);

    for (var j = 0; j < actions.length; j++) {
      actions[j] = true;
    }
    var changed = true;

    for (var elem = 1; elem < elementCount + 1 && changed; elem++) {
      changed = false;

      if (elem === elements[elem - 1]) {
        changed = true;
        continue;
      }

      for (var j = 0; j < elementCount; j++) {
        if (elements[j + 1] === elem && elements[j] > elem && actions[j]) {
          var tmp = elements[j];
          elements[j] = elements[j + 1];
          elements[j + 1] = tmp;
          actions[j] = false;
          elem++;
          changed = true;
        }
      }
      elem = 0;
    }

    print(elements.join(" "));
  }

  var sets = parseInt(readline());

  for (var i = 0; i < sets; i++) {
    var elementCount = parseInt(readline());
    var elements = readline()
      .split(" ")
      .map(function(value) {
        return parseInt(value);
      });
    var actions = Array(elementCount + 1);

    for (var j = 0; j < actions.length; j++) {
      actions[j] = true;
    }
    var changed = true;

    for (var elem = 1; elem < elementCount + 1 && changed; elem++) {
      changed = false;

      if (elem === elements[elem - 1]) {
        elem++;
        changed = true;
        continue;
      }

      for (var j = 0; j < elementCount; j++) {
        if (elements[j + 1] === elem && elements[j] > elem && actions[j]) {
          var tmp = elements[j];
          elements[j] = elements[j + 1];
          elements[j + 1] = tmp;
          actions[j] = false;
          elem++;
          changed = true;
        }
      }
      elem = 0;
    }

    print(elements.join(" "));
  }


Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win.

The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one.

If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win.

NoteIn the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white.In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black.

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

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

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

function findCost(initial, chars) {
	var cost = 0,
		expected = initial, opposite = (initial+1)%2, temp;

	for (var position = 0; position < chars.length; ++position) {
		if (chars[position] != expected) {
			++cost;
		}
		temp = expected;
		expected = opposite;
		opposite = temp;
	}

	return cost;
}

function main() {
	var length = parseInt(readline(), 10);
	var input = readline().replace(/\s+/g, "");

	print(Math.min(findCost(0, input.split("")),
				findCost(1, input.split(""))));
}

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]);
	};
	return tokens;
}

function findCost(initial, chars) {
	var cost = 0,
		expected = initial, opposite = (initial+1)%2;

	for (var position = 0; position < chars.length; ++position) {
		if (chars[position] != expected) {
			++cost;
		}
		var temp = expected;
		expected = opposite;
		opposite = temp;
	}

	return cost;
}

function main() {
	var length = parseInt(readline(), 10);
	var input = readline().replace(/\s+/g, "");

	print(Math.min(findCost(0, input.split("")),
				findCost(1, input.split(""))));
}

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]);
	};
	return tokens;
}

function findCost(initial, chars) {
	var cost = 0,
		expected = (initial+1)%2, nextExpected = initial,
		position = 0;

	while (position != chars.length-1) {
		var temp = expected;
		expected = nextExpected;
		nextExpected = temp;

		if (chars[position] == chars[position+1]) {
			++cost;

			if (chars[position] == expected) {
				chars[position+1] = nextExpected;
				++position;
			}
			else {
				chars[position] = expected;
				if (position == 0) {
					position = 1;
				}
				else {
					--position;
				}
			}//end else
		}//end if

		else {
			++position;
		}
	}//end while

	return cost;
}//end findCost

function main() {
	var length = parseInt(readline(), 10);
	var input = readline().replace(/\s+/g, "");

	for (var position = 1; position < length; ++position) {
		if (input.charAt(position) == input.charAt(position-1)) {
			break;
		}
	}

	if (position == length) {
		print(0);
		return;
	}

	print(Math.min(findCost(0, input.split("")),
				findCost(1, input.split(""))));
}

main();


You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.

The only line contains a string $$$s$$$ consisting of zeroes and ones ($$$1 \le |s| \le 1000$$$). Zero describes vertical tile, one describes horizontal tile.

Output $$$|s|$$$ lines — for each tile you should output two positive integers $$$r,c$$$, not exceeding $$$4$$$, representing numbers of smallest row and column intersecting with it. If there exist multiple solutions, print any of them.

NoteFollowing image illustrates the example after placing all three tiles:    Then the first row is deleted:

function main(str){

      var h = false;
      var v = false;
      for(var i = 0 ; i < str.length ; i++){
        if(str[i] === "0"){
          if(v){
            print("3 4");
          }
          else{
            print("1 4");
          }
          v = !v;
        }
        else{
          if(h){
            print("4 3");
          }
          else{
            print("4 1");
          }
          h = !h;
        }
      }
}

var str = readline();

main(str);

var str = '';
var readliner = require('readline');
var rl = readliner.createInterface(process.stdin, process.stdout, null);
rl.on('line', function (cmd) {
                  //console.log('You just typed: '+cmd);
                  str = cmd;
              }).on('close', main);

function recheck(s) {
	for (var x=0; x<4; x++) {
		var all_1 = 1;
		for (var y=0; y<4; y++)
			if (s[x][y] !== 1) {
				all_1 = 0;
				break;
			}
		if (all_1 === 1)
			for (var y=0; y<4; y++)
				s[x][y] = 0;
	}
	for (var x=0; x<4; x++) {
		var all_1 = 1;
		for (var y=0; y<4; y++)
			if (s[y][x] !== 1) {
				all_1 = 0;
				break;
			}
		if (all_1 === 1)
			for (var y=0; y<4; y++)
				s[y][x] = 0;
	}
}

function main() {
    //console.log('goodbye!');

/*    var mn = 1000000000;
    for (var code=0; code<(1<<9); code++) {
	var cnt_ones = 0;
	for (var j=0; j<9; j++) cnt_ones += (code>>j)&1;
        var x = N;

    }*/

    var s = [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]];

    for (var j=0; j<str.length; j++) {
    	if (str[j] === '0') {
    		var xx, yy, fnd = 0;
    		for (var x=0; x<3 && !fnd; x++)
    			for (var y=0; y<4; y++) if (y===0)
    				if (s[x][y] === 0 && s[x+1][y] === 0) {
    					xx = x;
    					yy = y;
    					fnd = 1;
    					break;
    				}
    		console.log((xx+1) + " " + (yy+1));
	   		s[xx][yy] = s[xx+1][yy] = 1;
    	}
    	else {
    		var xx, yy, fnd = 0;
    		for (var x=0; x<4 && !fnd; x++)
    			for (var y=0; y<3; y++) if (y===1)
    				if (s[x][y] === 0 && s[x][y+1] === 0) {
    					xx = x;
    					yy = y;
    					fnd = 1;
    					break;
    				}
    		console.log((xx+1) + " " + (yy+1));
    		s[xx][yy] = s[xx][yy+1] = 1;
    	}
    	recheck(s);
    }

    //console.log(ans);
    //console.log(Q);

    //var x = 1.2345678;
    //console.log('x = ',Number(x).toFixed(5));

    process.exit(0);
};

//var lines = data.split(/\r?\n/);

function main(str){

      var h = false;
      var v = false;
      for(var i = 0 ; i < str.length ; i++){
        if(str[i] === "0"){
          if(v){
            print("4 3");
          }
          else{
            print("4 1");
          }
          v = !v;
        }
        else{
          if(h){
            print("1 3");
          }
          else{
            print("1 1");
          }
          h = !h;
        }
      }
}

var str = readline();

main(str);

try {

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var array = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];

function clean() {
    for (var i = 0; i < 4; i++) {
        if (array[i][0] === 1 && array[i][1] === 1 && array[i][2] === 1 && array[i][3] === 1) {
            array[i][0] = array[i][1] = array[i][2] = array[i][3] = 0;
        } else if (array[0][i] === 1 && array[1][i] === 1 && array[2][i] === 1 && array[3][i] === 1) {
            array[0][i] = array[1][i] = array[2][i] = array[3][i] = 0;
        }
    }
}

function getFree() {
    var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            if (v && array[i][j] === 0 && array[i + 1][j] === 0) {
                return [i, j];
            } else if (!v && array[i][j] === 0 && array[i][j + 1] === 0) {
                return [i, j];
            }
        }
    }
}

var arr = String(readline());

arr = arr.split("").map(Number);
arr.forEach(function (i) {
    var _getFree = getFree(i === 0),
        _getFree2 = _slicedToArray(_getFree, 2),
        x = _getFree2[0],
        y = _getFree2[1];

    array[x][y] = 1;
    i === 1 ? array[x][y + 1] = 1 : array[x + 1][y] = 1;
    write(x + 1 + " " + (y + 1) + "\n");
    clean();
});
} catch(e){write(String(e.stack).replace(/ /g, "-"))}

try {

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var array = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];

function clean() {
    for (var i = 0; i < 4; i++) {
        if (array[i][0] === 1 && array[i][1] === 1 && array[i][2] === 1 && array[i][3] === 1) {
            array[i][0] = array[i][1] = array[i][2] = array[i][3] = 0;
        } else if (array[0][i] === 1 && array[1][i] === 1 && array[2][i] === 1 && array[3][i] === 1) {
            array[0][i] = array[1][i] = array[2][i] = array[3][i] = 0;
        }
    }
}

function getFree() {
    var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            if (v && array[i][j] === 0 && array[i + 1][j] === 0) {
                return [i, j];
            } else if (!v && array[i][j] === 0 && array[i][j + 1] === 0) {
                return [i, j];
            }
        }
    }
}

var xx = "";
var arr = String(xx = readline());

arr = arr.split("").map(Number);
arr.forEach(function (i) {
    var _getFree = getFree(i === 0),
        _getFree2 = _slicedToArray(_getFree, 2),
        x = _getFree2[0],
        y = _getFree2[1];

    array[x][y] = 1;
    i === 1 ? array[x][y + 1] = 1 : array[x + 1][y] = 1;
    write(x + 1 + " " + (y + 1) + "\n");
    clean();
});
} catch(e){write(xx)}

try {

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var array = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];

function clean() {
    for (var i = 0; i < 4; i++) {
        if (array[i][0] === 1 && array[i][1] === 1 && array[i][2] === 1 && array[i][3] === 1) {
            array[i][0] = array[i][1] = array[i][2] = array[i][3] = 0;
        } else if (array[0][i] === 1 && array[1][i] === 1 && array[2][i] === 1 && array[3][i] === 1) {
            array[0][i] = array[1][i] = array[2][i] = array[3][i] = 0;
        }
    }
}

function getFree() {
    var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            if (v && array[i][j] === 0 && array[i + 1][j] === 0) {
                return [i, j];
            } else if (!v && array[i][j] === 0 && array[i][j + 1] === 0) {
                return [i, j];
            }
        }
    }
}

var arr = String(readline());

arr = arr.split("").map(Number);
arr.forEach(function (i) {
    var _getFree = getFree(i === 0),
        _getFree2 = _slicedToArray(_getFree, 2),
        x = _getFree2[0],
        y = _getFree2[1];

    array[x][y] = 1;
    i === 1 ? array[x][y + 1] = 1 : array[x + 1][y] = 1;
    write(x + 1 + " " + (y + 1) + "\n");
    clean();
});
} catch(e){write(e.stack)}

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var array = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];

function clean() {
    for (var i = 0; i < 4; i++) {
        if (array[i][0] === 1 && array[i][1] === 1 && array[i][2] === 1 && array[i][3] === 1) {
            array[i][0] = array[i][1] = array[i][2] = array[i][3] = 0;
        } else if (array[0][i] === 1 && array[1][i] === 1 && array[2][i] === 1 && array[3][i] === 1) {
            array[0][i] = array[1][i] = array[2][i] = array[3][i] = 0;
        }
    }
}

function getFree() {
    var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            if (v && array[i][j] === 0 && array[i][j + 1] === 0) {
                return [i, j];
            } else if (!v && array[i][j] === 0 && array[i + 1][j] === 0) {
                return [i, j];
            }
        }
    }
}

var arr = String(readline());
arr = arr.split("").map(Number);
arr.forEach(function (i) {
    var _getFree = getFree(i === 0),
        _getFree2 = _slicedToArray(_getFree, 2),
        x = _getFree2[0],
        y = _getFree2[1];

    array[x][y] = 1;
    i === 0 ? array[x][y + 1] = 1 : array[x + 1][y] = 1;
    write(x + 1 + " " + (y + 1) + "\n");
    clean();
});

try {

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var array = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];

function clean() {
    for (var i = 0; i < 4; i++) {
        if (array[i][0] === 1 && array[i][1] === 1 && array[i][2] === 1 && array[i][3] === 1) {
            array[i][0] = array[i][1] = array[i][2] = array[i][3] = 0;
        } else if (array[0][i] === 1 && array[1][i] === 1 && array[2][i] === 1 && array[3][i] === 1) {
            array[0][i] = array[1][i] = array[2][i] = array[3][i] = 0;
        }
    }
}

function getFree() {
    var v = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            if (v && array[i][j] === 0 && array[i + 1][j] === 0) {
                return [i, j];
            } else if (!v && array[i][j] === 0 && array[i][j + 1] === 0) {
                return [i, j];
            }
        }
    }
}

var arr = String(readline());

arr = arr.split("").map(Number);
arr.forEach(function (i) {
    var _getFree = getFree(i === 0),
        _getFree2 = _slicedToArray(_getFree, 2),
        x = _getFree2[0],
        y = _getFree2[1];

    array[x][y] = 1;
    i === 1 ? array[x][y + 1] = 1 : array[x + 1][y] = 1;
    write(x + 1 + " " + (y + 1) + "\n");
    clean();
});
} catch(e){}

var str = '';
var readliner = require('readline');
var rl = readliner.createInterface(process.stdin, process.stdout, null);
rl.on('line', function (cmd) {
                  //console.log('You just typed: '+cmd);
                  str = cmd;
              }).on('close', main);

function recheck(s) {
	for (var x=0; x<4; x++) {
		var all_1 = 1;
		for (var y=0; y<4; y++)
			if (s[x][y] !== 1) {
				all_1 = 0;
				break;
			}
		if (all_1 === 1)
			for (var y=0; y<4; y++)
				s[x][y] = 0;
	}
	for (var x=0; x<4; x++) {
		var all_1 = 1;
		for (var y=0; y<4; y++)
			if (s[y][x] !== 1) {
				all_1 = 0;
				break;
			}
		if (all_1 === 1)
			for (var y=0; y<4; y++)
				s[y][x] = 0;
	}
}

function main() {
    //console.log('goodbye!');

/*    var mn = 1000000000;
    for (var code=0; code<(1<<9); code++) {
	var cnt_ones = 0;
	for (var j=0; j<9; j++) cnt_ones += (code>>j)&1;
        var x = N;

    }*/

    var s = [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]];

    for (var j=0; j<str.length; j++) {
    	if (str[j] === '0') {
    		var xx, yy, fnd = 0;
    		for (var x=0; x<3 && !fnd; x++)
    			for (var y=0; y<4; y++)
    				if (s[x][y] === 0 && s[x+1][y] === 0 && Math.random() < 0.5) {
    					xx = x;
    					yy = y;
    					fnd = 1;
    					break;
    				}
    		console.log((xx+1) + " " + (yy+1));
	   		s[xx][yy] = s[xx+1][yy] = 1;
    	}
    	else {
    		var xx, yy, fnd = 0;
    		for (var x=0; x<4 && !fnd; x++)
    			for (var y=0; y<3; y++)
    				if (s[x][y] === 0 && s[x][y+1] === 0 && Math.random() < 0.5) {
    					xx = x;
    					yy = y;
    					fnd = 1;
    					break;
    				}
    		console.log((xx+1) + " " + (yy+1));
    		s[xx][yy] = s[xx][yy+1] = 1;
    	}
    	recheck(s);
    }

    //console.log(ans);
    //console.log(Q);

    //var x = 1.2345678;
    //console.log('x = ',Number(x).toFixed(5));

    process.exit(0);
};

//var lines = data.split(/\r?\n/);

var str = '';
var readliner = require('readline');
var rl = readliner.createInterface(process.stdin, process.stdout, null);
rl.on('line', function (cmd) {
                  //console.log('You just typed: '+cmd);
                  str = cmd;
              }).on('close', main);

function recheck(s) {
	for (var x=0; x<4; x++) {
		var all_1 = 1;
		for (var y=0; y<4; y++)
			if (s[x][y] !== 1) {
				all_1 = 0;
				break;
			}
		if (all_1 === 1)
			for (var y=0; y<4; y++)
				s[x][y] = 0;
	}
	for (var x=0; x<4; x++) {
		var all_1 = 1;
		for (var y=0; y<4; y++)
			if (s[y][x] !== 1) {
				all_1 = 0;
				break;
			}
		if (all_1 === 1)
			for (var y=0; y<4; y++)
				s[y][x] = 0;
	}
}

function main() {
    //console.log('goodbye!');

/*    var mn = 1000000000;
    for (var code=0; code<(1<<9); code++) {
	var cnt_ones = 0;
	for (var j=0; j<9; j++) cnt_ones += (code>>j)&1;
        var x = N;

    }*/

    var s = [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]];

    for (var j=0; j<str.length; j++) {
    	if (str[j] === '0') {
    		var xx, yy, fnd = 0;
    		for (var x=0; x<3 && !fnd; x++)
    			for (var y=0; y<4; y++)
    				if (s[x][y] === 0 && s[x+1][y] === 0 && Math.random() < 0.2) {
    					xx = x;
    					yy = y;
    					fnd = 1;
    					break;
    				}
    		console.log((xx+1) + " " + (yy+1));
	   		s[xx][yy] = s[xx+1][yy] = 1;
    	}
    	else {
    		var xx, yy, fnd = 0;
    		for (var x=0; x<4 && !fnd; x++)
    			for (var y=0; y<3; y++)
    				if (s[x][y] === 0 && s[x][y+1] === 0 && Math.random() < 0.2) {
    					xx = x;
    					yy = y;
    					fnd = 1;
    					break;
    				}
    		console.log((xx+1) + " " + (yy+1));
    		s[xx][yy] = s[xx][yy+1] = 1;
    	}
    	recheck(s);
    }

    //console.log(ans);
    //console.log(Q);

    //var x = 1.2345678;
    //console.log('x = ',Number(x).toFixed(5));

    process.exit(0);
};

//var lines = data.split(/\r?\n/);

var str = '';
var readliner = require('readline');
var rl = readliner.createInterface(process.stdin, process.stdout, null);
rl.on('line', function (cmd) {
                  //console.log('You just typed: '+cmd);
                  str = cmd;
              }).on('close', main);

function recheck(s) {
	for (var x=0; x<4; x++) {
		var all_1 = 1;
		for (var y=0; y<4; y++)
			if (s[x][y] !== 1) {
				all_1 = 0;
				break;
			}
		if (all_1 === 1)
			for (var y=0; y<4; y++)
				s[x][y] = 0;
	}
	for (var x=0; x<4; x++) {
		var all_1 = 1;
		for (var y=0; y<4; y++)
			if (s[y][x] !== 1) {
				all_1 = 0;
				break;
			}
		if (all_1 === 1)
			for (var y=0; y<4; y++)
				s[y][x] = 0;
	}
}

function main() {
    //console.log('goodbye!');

/*    var mn = 1000000000;
    for (var code=0; code<(1<<9); code++) {
	var cnt_ones = 0;
	for (var j=0; j<9; j++) cnt_ones += (code>>j)&1;
        var x = N;

    }*/

    var s = [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]];

    for (var j=0; j<str.length; j++) {
    	if (str[j] === '0') {
    		var xx, yy, fnd = 0;
    		for (var x=0; x<3 && !fnd; x++)
    			for (var y=0; y<4; y++)
    				if (s[x][y] === 0 && s[x+1][y] === 0) {
    					xx = x;
    					yy = y;
    					fnd = 1;
    					break;
    				}
    		console.log((xx+1) + " " + (yy+1));
	   		s[xx][yy] = s[xx+1][yy] = 1;
    	}
    	else {
    		var xx, yy, fnd = 0;
    		for (var x=0; x<4 && !fnd; x++)
    			for (var y=0; y<3; y++)
    				if (s[x][y] === 0 && s[x][y+1] === 0) {
    					xx = x;
    					yy = y;
    					fnd = 1;
    					break;
    				}
    		console.log((xx+1) + " " + (yy+1));
    		s[xx][yy] = s[xx][yy+1] = 1;
    	}
    	recheck(s);
    }

    //console.log(ans);
    //console.log(Q);

    //var x = 1.2345678;
    //console.log('x = ',Number(x).toFixed(5));

    process.exit(0);
};

//var lines = data.split(/\r?\n/);

var str = '';
var readliner = require('readline');
var rl = readliner.createInterface(process.stdin, process.stdout, null);
rl.on('line', function (cmd) {
                  //console.log('You just typed: '+cmd);
                  str = cmd;
              }).on('close', main);

function recheck(s) {
	for (var x=0; x<4; x++) {
		var all_1 = 1;
		for (var y=0; y<4; y++)
			if (s[x][y] !== 1) {
				all_1 = 0;
				break;
			}
		if (all_1 === 1)
			for (var y=0; y<4; y++)
				s[x][y] = 0;
	}
	for (var x=0; x<4; x++) {
		var all_1 = 1;
		for (var y=0; y<4; y++)
			if (s[y][x] !== 1) {
				all_1 = 0;
				break;
			}
		if (all_1 === 1)
			for (var y=0; y<4; y++)
				s[y][x] = 0;
	}
}

function main() {
    //console.log('goodbye!');

/*    var mn = 1000000000;
    for (var code=0; code<(1<<9); code++) {
	var cnt_ones = 0;
	for (var j=0; j<9; j++) cnt_ones += (code>>j)&1;
        var x = N;

    }*/

    var s = [[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]];

    for (var j=0; j<str.length; j++) {
    	if (str[j] === '0') {
    		var xx, yy, fnd = 0;
    		for (var x=0; x<3 && !fnd; x++)
    			for (var y=0; y<4; y++) if (y===0 || y===3)
    				if (s[x][y] === 0 && s[x+1][y] === 0) {
    					xx = x;
    					yy = y;
    					fnd = 1;
    					break;
    				}
    		console.log((xx+1) + " " + (yy+1));
	   		s[xx][yy] = s[xx+1][yy] = 1;
    	}
    	else {
    		var xx, yy, fnd = 0;
    		for (var x=0; x<4 && !fnd; x++)
    			for (var y=0; y<3; y++) if (y===1)
    				if (s[x][y] === 0 && s[x][y+1] === 0) {
    					xx = x;
    					yy = y;
    					fnd = 1;
    					break;
    				}
    		console.log((xx+1) + " " + (yy+1));
    		s[xx][yy] = s[xx][yy+1] = 1;
    	}
    	recheck(s);
    }

    //console.log(ans);
    //console.log(Q);

    //var x = 1.2345678;
    //console.log('x = ',Number(x).toFixed(5));

    process.exit(0);
};

//var lines = data.split(/\r?\n/);


Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself.

Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number.

NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs.

var n=readline();
var a=readline().split(' ');
a=a.slice(0,n);
var cnt= [];
cnt.length=2;
for(var k=0; k<2; k++){
    cnt[k] = [];
    cnt[k].length=(1<<20)+3;
    cnt[k].fill(0);
}

cnt[1][0]=1;
var res=0;
var x=0;
for(var i=0; i<n; ++i){
    x^=a[i];
    res+=cnt[i%2][x];
    ++cnt[i%2][x];
}

print(res);

// problem name: Sasha and a Bit of Relax
// problem link: https://codeforces.com/problemset/problem/1109/A
// contest link: https://codeforces.com/contest/1109
// author: reyad
// time: (?)

'use strict';

function main() {
	let m = 1<<20;
	let n = nextInt();

	let count_odd = [];
	let count_even = [];
	for(let i=0; i<=m; i++) {
		count_odd.push(0);
		count_even.push(0);
	}

	let ans = 0;

	let xor = 0;
	count_even[xor]++;

	for(let i=1; i<=n; i++) {
		xor = nextInt() ^ xor;
		if((i&1) == 1) {
			ans = ans + count_odd[xor];
			count_odd[xor]++;
		}
		else {
			ans = ans + count_even[xor];
			count_even[xor]++;
		}
	}
	console.log(ans);
}

// reader and main caller

let readline = require('readline');

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

let inputBuf = [];
let inputBufCnt = 0;
let tk = []
let tkCnt = 0;

function nextLine() {
	return inputBuf[inputBufCnt++];
}
function next() {
	if(tkCnt == tk.length) {
		tk = inputBuf[inputBufCnt++].split(' ');
		tkCnt = 0;
	}
	return tk[tkCnt++];
}
function nextInt() {
	return parseInt(next());
}
function nextDouble() {
	return parseFloat(next());
}

rl.on('line', (line) => {
	inputBuf.push(line);
}).on('close', () => {
	main();
});

var n=readline();
var a=readline().split(' ');
a=a.slice(0,n);
var cnt= [];
cnt.length=2;
for(var k=0; k<2; k++){
    cnt[k] = [];
    cnt[k].length=(1<<20)+3;
    cnt[k].fill(0);
}

cnt[1][0]=1;
var res=0;
var x=0;
for(var i=0; i<n; ++i){
    x^=a[i];
    res+=cnt[i%2][x];
    ++cnt[i%2][x];
    print(res);
}

print(res);


For his birthday, Kevin received the set of pairwise distinct numbers $$$1, 2, 3, \ldots, n$$$ as a gift.He is going to arrange these numbers in a way such that the minimum absolute difference between two consecutive numbers be maximum possible. More formally, if he arranges numbers in order $$$p_1, p_2, \ldots, p_n$$$, he wants to maximize the value $$$$$$\min \limits_{i=1}^{n - 1} \lvert p_{i + 1} - p_i \rvert,$$$$$$ where $$$|x|$$$ denotes the absolute value of $$$x$$$.Help Kevin to do that.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$2 \le n \leq 1\,000$$$) — the size of the set.

For each test case print a single line containing $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$) describing the arrangement that maximizes the minimum absolute difference of consecutive elements.  Formally, you have to print a permutation $$$p$$$ which maximizes the value $$$\min \limits_{i=1}^{n - 1} \lvert p_{i + 1} - p_i \rvert$$$. If there are multiple optimal solutions, print any of them.

NoteIn the first test case the minimum absolute difference of consecutive elements equals $$$\min \{\lvert 4 - 2 \rvert, \lvert 1 - 4 \rvert, \lvert 3 - 1 \rvert \} = \min \{2, 3, 2\} = 2$$$. It's easy to prove that this answer is optimal.In the second test case each permutation of numbers $$$1, 2, 3$$$ is an optimal answer. The minimum absolute difference of consecutive elements equals to $$$1$$$.

let ryan = '';//.map(saer).sort(function(a, a){return a - a})
process.stdin.on('data', c => ryan += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = ryan.split(EOL);
    var n = lines[0]
    for(i = 1; i <= n * 2; i++){
        var k = lines[i], a = Math.floor(k / 2) + 1, s = ''
        for(j = 0; j < Math.floor(k / 2); j++){
            s += (a + j) + ' ' + Number(j + 1) + ' '
        }
        if(k % 2 == 1){
            s += k;
        }
        console.log(s)
    }
});

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let i=1;i<=t;i++)
    {
        let n=parseInt(line[i]);
        let ans='';
        let a=new Array(n);
        let x;
        if(n&1) x=Math.floor((n+1)/2);
        else x=Math.floor((n+2)/2);
        let z=x;
        for(let i=0;i<n;i+=2) a[i]=z++;
        z=1;
        for(let i=1;i<n;i+=2) a[i]=z++;
        // for(let i=1;i<=n;i++) if(!(i&1)) ans+=i+' ';
        // for(let i=1;i<=n;i++) if(i&1) ans+=i+' ';
        for(let i=0;i<n;i++) ans+=a[i]+' ';
        console.log(ans);
    }
})

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];
    for(i = 1; i <= t * 2; i++){
        var n = lines[i];
        var a = Math.floor(n / 2) + 1;
        var ans = '';
        for(j = 0; j < Math.floor(n / 2); j++){
            ans += (a + j) + ' ' + (j + 1) + ' ';
        }
        if(n % 2 == 1){
            ans += n;
        }
        console.log(ans);
    }
});

'use strict';

function solve(max) {
    const perm = [];
    const next = Math.floor(max / 2 + 1);

    for (let i = 0; i < max; i++) {
        const numToInsert = i + 1;
        if (numToInsert < next) {
            perm[(i * 2) + 1] = numToInsert;
        } else {
            perm[(numToInsert-next) * 2] = numToInsert;
        }
    }

    cl(perm.join(' '));
}

function main() {
    const numOfCases = rlsn();

    for (let testCase = 0; testCase < numOfCases; testCase++) {
        const l1 = rlsn();

        solve(l1);
    }
}

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

let inStr = '';
let curLine = 0;
const cl = console.log;

process.stdin.on('data', function(inStdin) {inStr += inStdin;});
process.stdin.on('end', function() {inStr = inStr.split('\n');main();});

function readline() {return inStr[curLine++].replace(/\s+$/g, '');}
function rlsn() {return Number(readline());}
function rlarrstr() {return readline().split(' ');}
function rlarrn() {return rlarrstr().map(Number);}
function makeFreqMap(str) {const m={};for (let char of str) m[char]=m[char]+1||1;return m;}

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++]
        output[i] = solve(n)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n) {
    const r = []
    if (n & 1) {
        // for (let i = 0; i < (n - 1) / 2; i++) {
        for (let i = (n - 1) / 2 - 1; i >= 0; i--) {
            r.push(i + 1, i + (n + 1) / 2)
        }
        // r.push((n + 1) / 2)
        r.push(n)
    } else {
        // for (let i = 0; i < n / 2; i++) {
        for (let i = n / 2 - 1; i >= 0; i--) {
            r.push(i + 1, i + n / 2 + 1)
        }
    }
    return r.join(' ')
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function evaluateBoard(board)
{

}

function main() {

    let t = parseInt(readLine());

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

        //let qas = readLine().split("");
        let toprint=[]
        if(n%2==1)
        {
            let cur_number = 1
            let diff_low = Math.floor(n/2)
            let diff_up = Math.ceil(n/2)
            for(let i=1;i<n+1;i++)
            {
                toprint.push(cur_number)
                if(i%2==0)
                    cur_number = cur_number - diff_low
                else
                    cur_number = cur_number + diff_up

            }
        }
        else
        {
            let cur_number = n/2
            let diff_low = n/2+1
            let diff_up = n/2
            for(let i=1;i<n+1;i++)
            {
                toprint.push(cur_number)
                if(i%2==0)
                    cur_number = cur_number - diff_low
                else
                    cur_number = cur_number + diff_up

            }
        }
        console.log(...toprint)

    }
}

'use strict';

var fs = require('fs');

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

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

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

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

var numOfCases = Number(readline());

for (var testCase = 0; testCase < numOfCases; testCase++) {
    var l1 = Number(readline());

    var result = process(l1);
    print(result);
}

function process(max) {
    var perm = [];
    var next = Math.floor(max / 2 + 1);

    for (var i = 0; i < max; i++) {
        var numToInsert = i + 1;
        if (numToInsert < next) {
            perm[(i * 2) + 1] = numToInsert;
        } else {
            perm[(numToInsert-next) * 2] = numToInsert;
        }
    }

    return perm.join(' ');
}

var n = +readline();
for(var i = 0; i < n; i++) {
  var k = +readline();
  var ans = Math.floor(k / 2) + 1;
  var temp = [];
  for(var j = 0, jj = 1; j < k; j++) {
    if(j % 2 === 0) {
      temp.push(ans);
      ans++;
      continue;
    }
    temp.push(jj);
    jj++;
  }
  print(temp.join(' '));
}

let ryan = '';//.map(saer).sort(function(a, a){return a - a})
process.stdin.on('data', c => ryan += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = ryan.split(EOL);
    var n = lines[0]
    for(i = 1; i <= n * 2; i++){
        var k = lines[i], a = Math.floor(k / 2) + 1, s = ''
        for(j = 0; j < Math.floor(k / 2); j++){
            s += (a + j) + ' ' + Number(j + 1) + ' '
        }
        if(n % 2 == 1){
            s += k;
        }
        console.log(s)
    }
});

let ryan = '';//.map(saer).sort(function(a, a){return a - a})
process.stdin.on('data', c => ryan += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = ryan.split(EOL);
    var n = lines[0]
    for(i = 1; i <= n * 2; i++){
        var k = lines[i], a = Math.floor(k / 2) + 1, s = ''
        for(j = 0; j <= Math.floor(k / 2); j++){
            s += (a + j) + ' ' + Number(j + 1) + ' '
        }

        console.log(s)
    }
});

let ryan = '';//.map(saer).sort(function(a, a){return a - a})
process.stdin.on('data', c => ryan += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = ryan.split(EOL);
    var n = lines[0]
    for(i = 1; i <= n * 2; i++){
        var k = lines[i], a = Math.floor(k / 2) + 1, s = ''
        for(j = 0; j < Math.floor(k / 2); j++){
            s += (a + j) + ' ' + Number(j + 1) + ' '
        }

        console.log(s)
    }
});

let ryan = '';//.map(saer).sort(function(a, a){return a - a})
process.stdin.on('data', c => ryan += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = ryan.split(EOL);
    var n = lines[0]
    for(i = 1; i <= n * 2; i++){
        var k = lines[i], a = Math.floor(k / 2) + 1, s = ''
        for(j = 0; j < Math.floor(k / 2); j++){
            s += (a + j) + ' ' + j + 1 + ' '
        }

        console.log(s)
    }
});

let ryan = '';//.map(saer).sort(function(a, a){return a - a})
process.stdin.on('data', c => ryan += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = ryan.split(EOL);
    var n = lines[0]
    for(i = 1; i <= n * 2; i++){
        var k = lines[i], a = Math.floor(k / 2) + 1, s = ''
        for(j = 0; j < Math.floor(k / 2); j++){
            s += (a + j) + ' ' + j + ' '
        }

        console.log(s)
    }
});

//  var gcd = function(a, b) {
//   if (!b) {
//     return a;
//   }

//   return gcd(b, a % b);
// }
let ryan = '';//.map(Number).sort(function(a, b){return a - b})
process.stdin.on('data', c => ryan += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = ryan.split(EOL);
    var n = lines[0]
    for(j = 1; j <= n; j++){
        var k = lines[j]
        e = ''
        for(l = 1; l <= k; l++){
            e += l + ' '
        }
        console.log(e)
    }

});

//  var gcd = function(a, b) {
//   if (!b) {
//     return a;
//   }

//   return gcd(b, a % b);
// }
let ryan = '';//.map(Number).sort(function(a, b){return a - b})
process.stdin.on('data', c => ryan += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = ryan.split(EOL);
    var n = lines[0]
    for(j = 1; j <= n; j++){
        var k = lines[j], e = ''
        for(j = 1; j <= k; j++){
            e += j + ' '
        }
        console.log(e)
    }

});

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let i=1;i<=t;i++)
    {
        let n=parseInt(line[i]);
        let ans='';
        let a=new Array(n);
        let x=Math.floor((n+1)/2);
        let z=x;
        for(let i=0;i<n;i+=2) a[i]=z++;
        z=1;
        for(let i=1;i<n;i+=2) a[i]=z++;
        // for(let i=1;i<=n;i++) if(!(i&1)) ans+=i+' ';
        // for(let i=1;i<=n;i++) if(i&1) ans+=i+' ';
        for(let i=0;i<n;i++) ans+=a[i]+' ';
        console.log(ans);
    }
})

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let i=1;i<=t;i++)
    {
        let n=parseInt(line[i]);
        let ans='';
        for(let i=1;i<=n;i++) if(!(i&1)) ans+=i+' ';
        for(let i=1;i<=n;i++) if(i&1) ans+=i+' ';
        console.log(ans);
    }
})

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var a = lines[0].split(' ').map(Number);
    var months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var n = a[0], m = a[1];
    if(months[n] == 31){
        console.log(m > 5 ? 6 : 5);
    }else if(months[n] == 30){
        console.log(m == 7 ? 6 : 5);
    }else{
        console.log(m == 1  ? 4 : 5);
    }
});

var numOfCases = Number(readline());

for (var testCase = 0; testCase < numOfCases; testCase++) {
    var l1 = Number(readline());

    var result = process(l1);
    print(result);
}

function process(max) {
    var perm = [];
    var next = Math.ceil(max / 2 + 1);

    for (var i = 0; i < max; i++) {
        var numToInsert = i + 1;
        if (numToInsert < next) {
            perm[i * 2] = numToInsert;
        } else {
            perm[(numToInsert - next) * 2 + 1] = numToInsert;
        }
    }

    return perm.join(' ');
}

var numOfCases = Number(readline());

for (var testCase = 0; testCase < numOfCases; testCase++) {
    var l1 = Number(readline());

    var result = process(l1);
    print(result);
}

function process(max) {
    const perm = [];
    var l = 0, r = max - 1;

    var midIndex = Math.floor(max / 2);
    perm[midIndex] = 1;

    var ml = midIndex - 1,
        mr = midIndex + 1;

    for (var i = 2; i <= max; i++) {
        if ((i + 4) % 4 === 2) {
            perm[l] = i;
            l++;
        } else if ((i + 4) % 4 === 3) {
            perm[r] = i;
            r--;
        } else if ((i + 4) % 4 === 0) {
            perm[ml] = i;
            ml--;
        } else if ((i + 4) % 4 === 1) {
            perm[mr] = i;
            mr++;
        }
    }

    return perm.join(' ');
}

var numOfCases = Number(readline());

for (var testCase = 0; testCase < numOfCases; testCase++) {
    var l1 = Number(readline());

    var result = process(l1);
    print(result);
}

function process(max) {
    const perm = [];
    var l = 0, r = max - 1;

    var midIndex = Math.floor(max / 2);
    perm[midIndex] = 1;

    var ml = midIndex - 1,
        mr = midIndex + 1;

    for (var i = 2; i <= max; i++) {
        if ((i + 4) % 4 === 2) {
            perm[l] = i;
            l++;
        } else if ((i + 4) % 4 === 3) {
            perm[r] = i;
            r--;
        } else if ((i + 4) % 4 === 0) {
            perm[ml] = i;
            ml--;
        } else if ((i + 4) % 4 === 1) {
            perm[mr] = i;
            mr++;
        }
    }
    print(perm)

    return perm.join(' ');
}