var t = parseInt(readline());
for (var tc = 0; tc < t; tc++) {
  var input = readline()
    .split(" ")
    .map((val) => parseInt(val));
  var n = input[0],
    m = input[1],
    x = input[2],
    y = input[3];
  var cost = 0;
  var min = Math.min(2 * x, y);

  for (var i = 0; i < n; i++) {
    var squares = readline().split("");
    for (var j = 0; j < squares.length; j++) {
      if (squares[j] == ".") {
        if (squares[j + 1] == ".") {
          if (2 * x > y) {
            cost += y;
            j++;
            continue;
          } else cost += x;
        } else cost += x;
      }
    }
  }
  print(cost);
}

//↓見なくていいよ！ここから--------------------------------------------------
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);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
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){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
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;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var one = nextIntArray();
		var n = one[0];
		var m = one[1];
		var x = one[2];
		var y = one[3];
		var list = new Array(n);
		for(var j = 0; j < n; j++){
			list[j] = nextCharArray();
		}
		var cost = 0;
		if(x * 2 > y){
			for(var j = 0; j < n; j++){
				list[j].push("*");
				for(var k = 0; k < m; k++){
					if(list[j][k] == "." && list[j][k + 1] == "."){
						cost += y;
						k++;
					}else if(list[j][k] == "." && list[j][k + 1] == "*"){
						cost += x;
					}
				}
			}
		}else{
			for(var j = 0; j < n; j++){
				for(var k = 0; k < m; k++){
					if(list[j][k] == "."){
						cost += x;
					}
				}
			}
		}
		output[i] = cost;
	}
	myout(myconv(output,9));
}

var testCases = readline();
for(var i =0; i< testCases; i++) {
    var info =  readline().split(" ");
    var oneCost = info[2];
    var twoCost = info[3];
    var cost = 0;
    for(var j =0; j< info[0]; j++) {
        var row = readline();
        var dotGroups =  row.match(/\.+/g) || [];
          for(var k =0; k< dotGroups.length; k++) {
              var groupLength = dotGroups[k].length;
              var currCost = groupLength*oneCost;
              if(twoCost < (oneCost * 2)) {
                  var t = Math.floor(groupLength/2);
                  currCost = t*twoCost + (groupLength - t*2)*oneCost;
              }
              cost+= currCost;
           }
    }
    print(cost);
}

'use strict';

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

let inputString = [];
let currentLine = 0;

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

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

    //withTiming(main);
    main();
});

const readline = () => inputString[currentLine++];

const withTiming = callback => {
    const start = new Date();
    callback();
    console.log(`Took ${new Date() - start} ms`);
}

const main = () => {
    const t = parseInt(readline());

    for (let k = 0; k < t; k++) {
        const [n, m, x, y] = readline().split(' ').map(x => parseInt(x));
        const tiles = [];
        let i = 0, j = 0, cost = 0;

        for (let j = 0; j < n; j++) {
            tiles.push(readline());
        }

        while (i < n) {
            while (j < m) {
                if (tiles[i][j] === '.') {
                    if (y < x * 2 && j !== m - 1 && tiles[i][j + 1] === '.') {
                        cost += y;
                        j += 2;
                    } else {
                        cost += x;
                        j++;
                    }
                } else {
                    j++;
                }
            }

            j = 0;
            i++;
        }

        console.log(cost);
    }
}

const processData = (lines) => {
  let acc = 0
  const n = lines[acc]
  acc++
  for (let i=0; i<n; i++) {
    const [n, m, o, t] = lines[acc].split(' ').map(x => +x)
    acc++
    let sum = 0
    for (let j=0; j<n; j++) {
      let tSum = 0
      let oSum = 0
      for (const s of lines[acc].split('*')) {
        oSum += s.length * o
        tSum += Math.floor(s.length / 2) * t + (s.length % 2) * o
      }
      sum += Math.min(tSum, oSum)
      acc++
    }
    console.log(sum)
  }
}

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

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

const calculateLine = (line, oneCellCost, twoCellsCost) => {
  let ret = 0;
  for(let i = 0; i < line.length; i++) {
    if (line[i] == '.') {
      if (line[i+1] == '.') {
        if (twoCellsCost < oneCellCost * 2) {
          ret += twoCellsCost;
          i++;
        } else {
          ret += oneCellCost;
        }
      } else {
        ret += oneCellCost;
      }
    }
  }
  return ret;
}

let tests = true;
let index = 0, ret = 0;
let rows, cols, oneCellCost, twoCellsCost;
readline.on('line', line => {
  if (tests) { tests = false; return; }
  const l = line.split(' ');
  if (l.length > 1) {
    rows = parseInt(l[0]); cols = parseInt(l[1]);
    oneCellCost = parseInt(l[2]); twoCellsCost = parseInt(l[3]);
    index = 0; ret = 0;
  } else if (index++ < rows) {
    ret += calculateLine(line, oneCellCost, twoCellsCost);
    if (index === rows) {
      console.log(ret);
    }
  }
});

/**
4
1 1 10 1
.
1 2 10 1
..
2 1 10 1
.
.
3 3 3 7
..*
*..
.*.

*/

'use strict';

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

let inputString = [];
let currentLine = 0;

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

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

    //withTiming(main);
    main();
});

const readline = () => inputString[currentLine++];

const withTiming = callback => {
    const start = new Date();
    callback();
    console.log(`Took ${new Date() - start} ms`);
}

const main = () => {
    const t = parseInt(readline());

    for (let k = 0; k < t; k++) {
        const [n, m, x, y] = readline().split(' ').map(x => parseInt(x));
        const tiles = [];
        let i = 0, j = 0, cost = 0;

        for (let j = 0; j < n; j++) {
            tiles.push(readline());
        }

        while (i < n) {
            while (j < m) {
                if (tiles[i][j] === '.') {
                    if (y < x * 2 && j !== m - 1) {
                        cost += y;
                        j += 2;
                    } else {
                        cost += x;
                        j++;
                    }
                } else {
                    j++;
                }
            }

            j = 0;
            i++;
        }

        console.log(cost);
    }
}

const processData = (lines) => {
  let acc = 0
  const n = lines[acc]
  acc++
  for (let i=0; i<n; i++) {
    const [n, m, o, t] = lines[acc].split(' ').map(x => +x)
    acc++
    let sum = 0
    for (let j=0; j<n; j++) {
      let tSum = 0
      let oSum = 0
      for (const s of lines[acc].split('*')) {
        oSum += s.length * o
        tSum += Math.ceil(s.length / 2) * t + (s.length % 2) * o
      }
      sum += Math.min(tSum, oSum)
      acc++
    }
    console.log(sum)
  }
}

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


function mlt() { return readline().split(' ').map(x => parseInt(x)) }

function solv() {

    var inp = mlt()
    var x = inp[0]
    var y = inp[1]
    var vis = 0;
    for (var n = 0; n < x - 1; n++) {
        var px = mlt();

        if (px[0] == y || px[1] == y) vis++;
    }
    if (vis == 1 || x == 1) {
        print('Ayush')
        return;
    }
    else {
        x--;
        var st = ['Ashish', 'Ayush']
        print(st[x % 2])
    }
}

var tc = 1;
tc = parseInt(readline());
while (tc--) solv()

"use strict";
var T = parseInt(readline())
for(let t = 0 ; t < T ; t++){
    let n_x = readline().split(' ')
    let n = parseInt(n_x[0])
    let x = parseInt(n_x[1])
    let cnt = 0;
    for(let i = 0 ; i < n -1 ; i++){
        let u_v = readline().split(' ')
        let u = parseInt(u_v[0]);
        let v = parseInt(u_v[1]);
        if (u == x || v == x) cnt++
    }
    if (cnt <= 1)
        print('Ayush')
    else if (n % 2 == 0)
        print('Ayush')
    else
        print('Ashish')
}

function mlt() { return readline().split(' ').map(x => parseInt(x)) }

function solv() {

    var inp = mlt()
    var x = inp[0]
    var y = inp[1]
    var vis = 0;
    for (var n = 0; n < x - 1; n++) {
        var px = mlt();

        if (px[0] == y || px[1] == y) vis++;
    }
    if (vis == 1) {
        print('Ayush')
        return;
    }
    else {
        x--;
        var st = ['Ashish', 'Ayush']
        print(st[x % 2])
    }
}

var tc = 1;
tc = parseInt(readline());
while (tc--) solv()


'use strict';
 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  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 L = process.env.DEBUG ? console.log : ()=>{};

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

const calc = (n, P)=>{
  let i;
  for (i=0; P[i]==i+1 && i<n; i++);
  if (i==n){
    return P;
  }
  let l = i;
  let minI = i;
  for (let j=i; j<n; j++){
    if (P[j]<P[minI])
      minI = j;
  }
  let r = minI;
  for (i=l; i<(l+r)/2; i++){
    let j = r-(i-l);
    let tmp = P[i];
    P[i] = P[j]
    P[j] = tmp
  }
  L({l, r, P})
  return P
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let A = ra();
      L('ans')
      print(calc(n, A).join(' '));
    }
}

E.calc = calc;

var t = parseInt(readline());
while (t--) {
    var n = parseInt(readline());
    var datas = readline().split(' ');
    reverse(datas, n);
}

function reverse(data, n) {
	var l = -1, r = 0;
	var i;
	for (i = 0; i < n; i++) {
	    data[i] = parseInt(data[i])
	    if (data[i] == l+1) {
	        r = i;
	        break;
	    }
	    if (data[i] != i+1 && l == -1) {
	        l = i;
	    }
	}
	var res = '';
	l = l == -1 ? 0 : l;
	for (i = 0; i < l; i++) {
		res = res + data[i] + ' ';
	}
	for (i = r; i>=l; i--) {
		res = res + data[i] + ' ';
	}
	for (i = r+1; i < n; i++) {
		res = res + data[i] + ' ';
	}
	print(res);
}

var t = parseInt(readline());
while (t--) {
    var n = parseInt(readline());
    var datas = readline().split(' ').map((x) => parseInt(x));
    reverse(datas, n);
}

function reverse(data, n) {
	var l = 0, r = 0, max = -1, min = 0;
	var i;
    if (data[0] != 1) max = 0;
	for (i = 1; i < n; i++) {
	    if ((min === 0 && data[i] < data[max]) || data[i] < data[min]){
			min = i;
			r = i;
		}
		if (max === -1 && data[i] > data[i - 1] + 1 && min === 0) {
			max = i;
			l = i;
		}
	}
	var res = '';
	for (i = 0; i < l; i++) {
		res = res + data[i] + ' ';
	}
	for (i = r; i>=l; i--) {
		res = res + data[i] + ' ';
	}
	for (i = r+1; i < n; i++) {
		res = res + data[i] + ' ';
	}
	print(res);
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = readline().split(" ");
    var caseMap = new Map();
    for (var j = 0; j < caseLength; j++)
    {
        caseMap[caseArray[j]] = j;
    }
    var start = 0;
    var flag = false;
    var result = "";
    for (var j = 0; j < caseLength; j++)
    {
        if (caseArray[j] !== `${j+1}`)
        {
            var startRevIndex = caseMap[`${j+1}`];
            if (startRevIndex !== null)
            {
                for (var k = startRevIndex; k >= j; k--)
                {
                    result += `${caseArray[k]} `;
                }
                start = startRevIndex + 1;
                flag = true;
                break;
            }
        }
        else result += `${caseArray[j]} `;
    }
    if (flag)
    {
        for (var j = start; j < caseLength; j++)
        {
            result += `${caseArray[j]} `;
        }
    }
    print(result);
}

var tests = parseInt(readline());

for (var i = 0; i < tests; i++) {
  var n = parseInt(readline());
  var arr = readline()
    .split(" ")
    .map((i) => parseInt(i));
  var l;
  var r;

  for (var j = 0; j < arr.length && arr[j] == j + 1; j++) {}
  if (j != arr.length) {
    l = j;
    for (var j = l; j < arr.length && arr[j] != l + 1; j++) {}
    r = j;
    for (var j = l; j < r; j++) {
      var tmp = arr[j];
      arr[j] = arr[r];
      arr[r--] = tmp;
    }
  }
  print(arr.join(" "));
}

// problems/contest1638/A/src/ts/solution.ts
var lines = [];
require("readline").createInterface({
  input: process.stdin
}).on("line", (line) => lines.push(line));
process.stdin.on("end", () => {
  main(lines);
});
function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]];
}
function reverse(arr, i, j) {
  while (i < j)
    swap(arr, i++, j--);
}
function solve(n, nums) {
  for (let i = 0; i < n; i++) {
    if (nums[i] !== i + 1) {
      let j = i + 1;
      while (j < n && nums[j] !== i + 1)
        j++;
      reverse(nums, i, j);
      break;
    }
  }
  return nums;
}
function main(lines2) {
  let ln = 0;
  let t = Number(lines2[ln++]);
  for (; t; t--) {
    const n = Number(lines2[ln++]);
    const nums = lines2[ln++].split(" ").map(Number);
    output(solve(n, nums));
  }
}
function output(res) {
  console.log(res.map((x) => `${x} `).join(""));
}

// problems/lib/js/array.js
function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]];
}
function reverse(arr, i, j) {
  while (i < j)
    swap(arr, i++, j--);
}

// problems/contest1638/A/src/js/solution.js
var lines = [];
require("readline").createInterface({
  input: process.stdin
}).on("line", (line) => lines.push(line));
process.stdin.on("end", () => {
  main(lines);
});
function solve(n, nums) {
  for (let i = 0; i < n; i++) {
    if (nums[i] !== i + 1) {
      let j = i + 1;
      while (j < n && nums[j] !== i + 1)
        j++;
      reverse(nums, i, j);
      break;
    }
  }
  return nums;
}
function main(lines2) {
  let ln = 0;
  let t = Number(lines2[ln++]);
  for (; t; t--) {
    const n = Number(lines2[ln++]);
    const nums = lines2[ln++].split(" ").map(Number);
    output(solve(n, nums));
  }
}
function output(res) {
  console.log(res.map((x) => `${x} `).join(""));
}

/*
A. Reverse
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given a permutation p1,p2,…,pn of length n. You have to choose two integers l,r (1≤l≤r≤n)
and reverse the subsegment [l,r] of the permutation. The permutation will become
p1,p2,…,pl−1,pr,pr−1,…,pl,pr+1,pr+2,…,pn.

Find the lexicographically smallest permutation that can be obtained by performing exactly one
reverse operation on the initial permutation.

Note that for two distinct permutations of equal length a and b, a is lexicographically smaller than
b if at the first position they differ, a has the smaller element.

A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For
example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the
array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).

Input

Each test contains multiple test cases. The first line contains a single integer t (1≤t≤500) — the
number of test cases. Description of the test cases follows.

The first line of each test case contains a single integer n (1≤n≤500) — the length of the
permutation.

The second line of each test case contains n integers p1,p2,…,pn (1≤pi≤n) — the elements of the
permutation.

Output

For each test case print the lexicographically smallest permutation you can obtain.

Example
Input
Copy

4
1
1
3
2 1 3
4
1 4 2 3
5
1 2 3 4 5

Output
Copy

1
1 2 3
1 2 4 3
1 2 3 4 5

Note

In the first test case, the permutation has length 1, so the only possible segment is [1,1]. The
resulting permutation is [1].

In the second test case, we can obtain the identity permutation by reversing the segment [1,2]. The
resulting permutation is [1,2,3].

In the third test case, the best possible segment is [2,3]. The resulting permutation is [1,2,4,3].

In the fourth test case, there is no lexicographically smaller permutation, so we can leave it
unchanged by choosing the segment [1,1]. The resulting permutation is [1,2,3,4,5].
*/

const lines = []

require('readline').createInterface({
  input: process.stdin
}).on('line', line => lines.push(line))

process.stdin.on('end', () => {
  main(lines)
})

function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]]
}

function reverse(arr, i, j) {
  while (i < j) swap(arr, i++, j--)
}

function solve(n, nums) {
  for (let i = 0; i < n; i++) {
    if (nums[i] !== i + 1) {
      let j = i + 1
      while (j < n && nums[j] !== i + 1) j++
      reverse(nums, i, j)
      break
    }
  }
  return nums
}

function main(lines) {
  let ln = 0
  let t = Number(lines[ln++])
  const res = []
  for (; t; t--) {
    const n = Number(lines[ln++])
    const nums = lines[ln++].split(' ').map(Number)
    output(solve(n, nums))
  }
}

function output(res) {
  console.log(res.map(x => `${x} `).join(''))
}

/*
A. Reverse
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given a permutation p1,p2,…,pn of length n. You have to choose two integers l,r (1≤l≤r≤n)
and reverse the subsegment [l,r] of the permutation. The permutation will become
p1,p2,…,pl−1,pr,pr−1,…,pl,pr+1,pr+2,…,pn.

Find the lexicographically smallest permutation that can be obtained by performing exactly one
reverse operation on the initial permutation.

Note that for two distinct permutations of equal length a and b, a is lexicographically smaller than
b if at the first position they differ, a has the smaller element.

A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For
example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the
array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).

Input

Each test contains multiple test cases. The first line contains a single integer t (1≤t≤500) — the
number of test cases. Description of the test cases follows.

The first line of each test case contains a single integer n (1≤n≤500) — the length of the
permutation.

The second line of each test case contains n integers p1,p2,…,pn (1≤pi≤n) — the elements of the
permutation.

Output

For each test case print the lexicographically smallest permutation you can obtain.

Example
Input
Copy

4
1
1
3
2 1 3
4
1 4 2 3
5
1 2 3 4 5

Output
Copy

1
1 2 3
1 2 4 3
1 2 3 4 5

Note

In the first test case, the permutation has length 1, so the only possible segment is [1,1]. The
resulting permutation is [1].

In the second test case, we can obtain the identity permutation by reversing the segment [1,2]. The
resulting permutation is [1,2,3].

In the third test case, the best possible segment is [2,3]. The resulting permutation is [1,2,4,3].

In the fourth test case, there is no lexicographically smaller permutation, so we can leave it
unchanged by choosing the segment [1,1]. The resulting permutation is [1,2,3,4,5].
*/

const lines = []

require('readline').createInterface({
  input: process.stdin
}).on('line', line => lines.push(line))

process.stdin.on('end', () => {
  output(main(lines))
})

function output(res) {
  for (const r of res) {
    console.log(r.join(' '))
  }
}

function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]]
}

function reverse(arr, i, j) {
  while (i < j) swap(arr, i++, j--)
}

function solve(n, nums) {
  for (let i = 0; i < n; i++) {
    if (nums[i] !== i + 1) {
      let j = i + 1
      while (j < n && nums[j] !== i + 1) j++
      reverse(nums, i, j)
      break
    }
  }
  return nums
}

function main(lines) {
  let l = 0
  let t = Number(lines[l++])
  const res = []
  for (; t; t--) {
    const n = Number(lines[l++])
    const nums = lines[l++].split(' ').map(Number)
    res.push(solve(n, nums))
  }
  return res
}

/*
A. Reverse
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given a permutation p1,p2,…,pn of length n. You have to choose two integers l,r (1≤l≤r≤n)
and reverse the subsegment [l,r] of the permutation. The permutation will become
p1,p2,…,pl−1,pr,pr−1,…,pl,pr+1,pr+2,…,pn.

Find the lexicographically smallest permutation that can be obtained by performing exactly one
reverse operation on the initial permutation.

Note that for two distinct permutations of equal length a and b, a is lexicographically smaller than
b if at the first position they differ, a has the smaller element.

A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For
example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the
array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).

Input

Each test contains multiple test cases. The first line contains a single integer t (1≤t≤500) — the
number of test cases. Description of the test cases follows.

The first line of each test case contains a single integer n (1≤n≤500) — the length of the
permutation.

The second line of each test case contains n integers p1,p2,…,pn (1≤pi≤n) — the elements of the
permutation.

Output

For each test case print the lexicographically smallest permutation you can obtain.

Example
Input
Copy

4
1
1
3
2 1 3
4
1 4 2 3
5
1 2 3 4 5

Output
Copy

1
1 2 3
1 2 4 3
1 2 3 4 5

Note

In the first test case, the permutation has length 1, so the only possible segment is [1,1]. The
resulting permutation is [1].

In the second test case, we can obtain the identity permutation by reversing the segment [1,2]. The
resulting permutation is [1,2,3].

In the third test case, the best possible segment is [2,3]. The resulting permutation is [1,2,4,3].

In the fourth test case, there is no lexicographically smaller permutation, so we can leave it
unchanged by choosing the segment [1,1]. The resulting permutation is [1,2,3,4,5].
*/

const lines = []

require('readline').createInterface({
  input: process.stdin
}).on('line', line => lines.push(line))

process.stdin.on('end', () => {
  output(main(lines))
})

function output(res) {
  for (const r of res) {
    console.log(r.join(' '), '')
  }
}

function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]]
}

function reverse(arr, i, j) {
  while (i < j) swap(arr, i++, j--)
}

function solve(n, nums) {
  for (let i = 0; i < n; i++) {
    if (nums[i] !== i + 1) {
      let j = i + 1
      while (j < n && nums[j] !== i + 1) j++
      reverse(nums, i, j)
      break
    }
  }
  return nums
}

function main(lines) {
  let l = 0
  let t = Number(lines[l++])
  const res = []
  for (; t; t--) {
    const n = Number(lines[l++])
    const nums = lines[l++].split(' ').map(Number)
    res.push(solve(n, nums))
  }
  return res
}

"use strict";

//let startTime = Date.now();

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

let inputString = "";
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numOfTests = +(readline());

    for (let i=0; i<numOfTests; i++){
        const lengthOfArr = +(readline());
        const arr = readline().split(" ").map((string) => {
            return +(string);
        });

        let result = [...arr];

        let startRevIndex;
        let endRevIndex;
        let lowestNumToFind;

        for (let i=0; i<lengthOfArr; i++) {
            if (arr[i] === (i+1) && startRevIndex === undefined) {
                continue;
            }

            if (lowestNumToFind === undefined) {
                lowestNumToFind = i+1;
                startRevIndex = i;
                continue;
            }

            if (arr[i] === lowestNumToFind) {
                endRevIndex = i;

                for (let j=0; j<= endRevIndex - startRevIndex; j++) {
                    result[startRevIndex + j] = arr[endRevIndex-j];
                }

                break;
            }
        }

        console.log(result.join(" "));
    }

//    console.log(Date.now() - startTime + " ms");
}

"use strict";
var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};

// out/FinalCode/Input.js
var require_Input = __commonJS({
  "out/FinalCode/Input.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var Input = class {
      constructor(inputData) {
        this.inputWords = [];
        this.inputStream = "";
        this.inputWordsLength = 0;
        this.inputWordsCount = 0;
        this.set_stream = (chunk) => {
          this.inputStream += chunk;
        };
        this.settle_stream = () => {
          let re = /\s+/;
          this.inputWords = this.inputStream.split(re);
          this.inputWordsLength = this.inputWords.length;
        };
        this.getNextWord = () => {
          this.inputWordsCount++;
          if (this.inputWordsLength < this.inputWordsCount) {
            return "";
          }
          return this.inputWords[this.inputWordsCount - 1];
        };
        this.getLength = () => {
          return this.inputWordsLength;
        };
        this.getEveryWord = () => {
          return this.inputWords;
        };
        this.getNextString = () => {
          return this.getNextWord();
        };
        this.getNextBigInt = () => {
          return BigInt(this.getNextWord());
        };
        this.getNextNumber = () => {
          return Number(this.getNextWord());
        };
        this.getNextInt = () => {
          return parseInt(this.getNextWord(), 10);
        };
        this.getNextFloat = () => {
          return parseFloat(this.getNextWord());
        };
        this.inputStream = inputData;
      }
    };
    exports2.default = Input;
  }
});

// out/typescript_competitive_programming.js
var __importDefault = exports && exports.__importDefault || function(mod) {
  return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var Input_1 = __importDefault(require_Input());
var rw = new Input_1.default("");
var write = (output_element) => {
  process.stdout.write(output_element);
};
var writeLine = (output_element) => {
  write(String(output_element) + "\n");
};
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", (chunk) => {
  rw.set_stream(chunk);
});
process.stdin.on("end", () => {
  rw.settle_stream();
  main_func();
});
var main_func = () => {
  let test = rw.getNextInt();
  for (let index = 0; index < test; index++) {
    let n = rw.getNextInt();
    let arr = new Array(n);
    let id = -1;
    let min = 1e4;
    let start = -1;
    for (let idx = 0; idx < n; idx++) {
      arr[idx] = rw.getNextInt();
      if (arr[idx] !== idx + 1) {
        if (start === -1) {
          start = idx;
        }
        if (arr[idx] < min) {
          id = idx;
          min = arr[idx];
        }
      }
    }
    if (start !== -1) {
      for (let idx = 0; idx < (id - start) / 2; idx++) {
        [arr[start + idx], arr[id - idx]] = [arr[id - idx], arr[start + idx]];
      }
    }
    for (let idx = 0; idx < n; idx++) {
      write(`${arr[idx]} `);
    }
    writeLine(" ");
  }
};

"use strict";
var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};

// out/FinalCode/Input.js
var require_Input = __commonJS({
  "out/FinalCode/Input.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var Input = function() {
      function Input2(inputData) {
        var _this = this;
        this.inputWords = [];
        this.inputStream = "";
        this.inputWordsLength = 0;
        this.inputWordsCount = 0;
        this.set_stream = function(chunk) {
          _this.inputStream += chunk;
        };
        this.settle_stream = function() {
          var re = /\s+/;
          _this.inputWords = _this.inputStream.split(re);
          _this.inputWordsLength = _this.inputWords.length;
        };
        this.getNextWord = function() {
          _this.inputWordsCount++;
          if (_this.inputWordsLength < _this.inputWordsCount) {
            return "";
          }
          return _this.inputWords[_this.inputWordsCount - 1];
        };
        this.getLength = function() {
          return _this.inputWordsLength;
        };
        this.getEveryWord = function() {
          return _this.inputWords;
        };
        this.getNextString = function() {
          return _this.getNextWord();
        };
        this.getNextBigInt = function() {
          return BigInt(_this.getNextWord());
        };
        this.getNextNumber = function() {
          return Number(_this.getNextWord());
        };
        this.getNextInt = function() {
          return parseInt(_this.getNextWord(), 10);
        };
        this.getNextFloat = function() {
          return parseFloat(_this.getNextWord());
        };
        this.inputStream = inputData;
      }
      return Input2;
    }();
    exports2.default = Input;
  }
});

// out/typescript_competitive_programming.js
var __importDefault = exports && exports.__importDefault || function(mod) {
  return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var Input_1 = __importDefault(require_Input());
var rw = new Input_1.default("");
var write = function(output_element) {
  process.stdout.write(output_element);
};
var writeLine = function(output_element) {
  write(String(output_element) + "\n");
};
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", function(chunk) {
  rw.set_stream(chunk);
});
process.stdin.on("end", function() {
  rw.settle_stream();
  main_func();
});
var main_func = function() {
  var _a;
  var test = rw.getNextInt();
  for (var index = 0; index < test; index++) {
    var n = rw.getNextInt();
    var arr = new Array(n);
    var id = -1;
    var min = 1e4;
    var start = -1;
    for (var idx = 0; idx < n; idx++) {
      arr[idx] = rw.getNextInt();
      if (arr[idx] !== idx + 1) {
        if (start === -1) {
          start = idx;
        }
        if (arr[idx] < min) {
          id = idx;
          min = arr[idx];
        }
      }
    }
    if (start !== -1) {
      for (var idx = 0; idx < (id - start) / 2; idx++) {
        _a = [arr[id - idx], arr[start + idx]], arr[start + idx] = _a[0], arr[id - idx] = _a[1];
      }
    }
    for (var idx = 0; idx < n; idx++) {
      write(arr[idx] + " ");
    }
    writeLine(" ");
  }
};

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

const reverse = (perm, l, r) => {
	return [
		...perm.slice(0, l),
		...perm.slice(l, r + 1).reverse(),
		...perm.slice(r + 1),
	];
};

function main() {
	const testCount = +readline();

	for (let i = 0; i < testCount; i++) {
		let permLength = +readline();
		let perm = readline().split(" ");

		let startIndex = 0;

		const sorted = perm.slice().sort((a, b) => a - b);

		while (
			sorted[startIndex] === perm[startIndex] &&
			startIndex < perm.length
		) {
			startIndex++;
		}

		if (startIndex === perm.length) {
			console.log(perm.join(" "));
		} else {
			const swapIndex = perm.indexOf(sorted[startIndex]);

			console.log(reverse(perm, startIndex, swapIndex).join(" "));
		}
	}
}

let text = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', str => {
    if (str === '\r\n' || str === '\n') {
        process.stdin.emit('end');
    } else {
        text += str;
    }
});

process.stdin.on('end', () => {
    const input = text.trim().replace(/\r/g, '').split('\n');
    const total = +input[0];
    for (let i = 1; i <= total; i++) {
        console.log(solve(input[i * 2]));
    }

    process.exit();
});

function solve(str) {
    const numbers = str.split(' ').map(ele => + ele);
    for (let i = 0; i < numbers.length; i++) {
        if (numbers[i] !== i + 1) {
            for (var j = i + 1; j < numbers.length; j++) {
                if (numbers[j] === i + 1) {
                    break;
                }
            }
            while(i < j) {
                [numbers[i], numbers[j]] = [numbers[j], numbers[i]];
                i++;
                j--;
            }
            break;
        }
    }
    return numbers.join(' ');
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

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

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);

        let left = 0;
        let right = 0;
        while (arr[left] === left + 1) left++;
        if (left === arr.length - 1) output(arr.join(' '));
        right = left + 1;
        while (!isNaN(arr[right]) && arr[right] !== left + 1) right++;
        let rev = arr.slice(left, right + 1).reverse();
        let res = [...arr.slice(0, left), ...rev, ...arr.slice(right + 1)];
        output(res.join(' '));
    }
}

'use strict';

function solve(n, a) {
  let l = -1,
      r = -1,
      min = -1;
  for (let i = n - 1; i >= 0; i--) {
    if (a[i] > a[min]) {
      l = i;
      r = min;
    }
    if (min === -1 || a[min] > a[i]) min = i;
  }
  for (let i = l, j = r; i < j; i++, j--) {
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a.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';

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++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  const tests_count = parseInt(readline());
  for (var test = 0; test < tests_count; test++) {
    const n = parseInt(readline());
    const permutation = readline().split(" ").filter(s => s.trim().length !== 0).map(s => parseInt(s.trim()));
    console.log(bestPermutation(permutation).join(" "));
  }
}

function bestPermutation(p) {
  let pivot_min_idx = findNextMin(p, 1);
  if (pivot_min_idx >= p.length)
    // Array is sorted
    return p;
  else {
    // Find biggest number after pivot
    let right_min_idx = findNextBestMin(p, pivot_min_idx);
    // Find smaller number before pivot
    let left_min_idx = pivot_min_idx - 1;
    while (left_min_idx >= 0 && p[left_min_idx] > p[right_min_idx])
      left_min_idx--;
    return permutate(p, left_min_idx + 1, right_min_idx)
  }
}
function findNextMin(p, ix) {
  while (ix < p.length && p[ix] > p[ix - 1]) ix++;
  return ix;
}
function findNextBestMin(p, ix) {
  let best = ix++;
  for (; ix < p.length; ix++)
    if (p[ix] < p[best]) best = ix;
  return best;
}
function permutate(p, ini, end) {
  const iTop = Math.floor((1 + end - ini) / 2);
  for (let i = 0; i < iTop; i++) swap(p, ini + i, end - i);
  return p;
}
function swap(p, i, j) {
  if (i !== j) {
    let aux = p[i];
    p[i] = p[j];
    p[j] = aux;
  }
}

const readline = require('readline');

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

const it = rl[Symbol.asyncIterator]();

const main = async () => {
    const use_cases = await it.next();
    let t = use_cases.value;
    while(t--)
    {
        const n = Number((await it.next()).value);
        let arr = (await it.next()).value.split(' ').map( x => Number(x));
        let left_index = -1;
        let required_elm = -1;
        let right_index = -1;
        let flag = false;
        for(let i=0; i< n; i++)
        {
            if( arr[i] > i+1 && !flag)
            {
                left_index = i;
                required_elm = i+1;
                flag = true;
            }
            if( arr[i] === required_elm)
            {
                right_index = i;
                break;
            }
        }
        if(right_index !== -1)
        {
            let j = right_index;
            for(let i=left_index; i<= left_index + (((right_index - left_index)/2) | 0); i++)
            {
                let temp = arr[i]
                arr[i] = arr[j];
                arr[j] = temp;
                j--;
            }
        }
        console.log(arr.join(' '));
    }

}
main();

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;
function readline(){
    return input[currentline++];
}

var T = readline();
for(var q=1;q<=T;q++) {
            var n = readline();
            var a = readline().split(" ").map(w => parseInt(w))
            var s = []
            for(var i=0;i<n;i++) s[i]=a[i]
            s.sort(function(ar,br){ return ar-br })
            var i=0;
            var j=0;
            while(s[i]==a[j] && (j<n && i<n)) {
            	i++;
            	j++;
            }
            for(var p=j;p<n;p++) {
            	if(a[p]==s[i]) break;
            }

            while(j<=p) {
            	var cache = a[j]
            	a[j] = a[p]
            	a[p] = cache;
            	j++;
            	p--;
            }
            console.log(a.join(' '));
}

var t = parseInt(readline());
while (t--) {
    var n = parseInt(readline());
    var datas = readline().split(' ');
    reverse(datas, n);
}

function reverse(data, n) {
	var l = -1, r = 0;
	var i;
	for (i = 0; i < n; i++) {
	    data[i] = parseInt(data[i]);
	    if (data[i] == l+1) {
	        r = i;
	        break;
	    }
	    if (data[i] != i+1 && l == -1) {
	        l = i;
	    }
	}
	var res = '';
	l = -1 ? 0 : l;
	for (i = 0; i < l; i++) {
		res = res + data[i] + ' ';
	}
	for (i = r; i>=l; i--) {
		res = res + data[i] + ' ';
	}
	for (i = r+1; i < n; i++) {
		res = res + data[i] + ' ';
	}
	print(res);
}

var t = parseInt(readline());
while (t--) {
    var n = parseInt(readline());
    var datas = readline().split(' ').map((x) => parseInt(x));
    reverse(datas, n);
}

function reverse(data, n) {
	var l = 0, r = 0, max = 0, min = 0;
	var i;

	for (i = 1; i < n; i++) {
	    if ((min === 0 && data[i] < data[max]) || data[i] < data[min]){
			min = i;
			r = i;
		}
		if (max === 0 && data[i] > data[i - 1] + 1 && min === 0) {
			max = i;
			l = i;
		}
	}
	var res = '';
	for (i = 0; i < l; i++) {
		res = res + data[i] + ' ';
	}
	for (i = r; i>=l; i--) {
		res = res + data[i] + ' ';
	}
	for (i = r+1; i < n; i++) {
		res = res + data[i] + ' ';
	}
	print(res);
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = readline().split(" ");
    var caseMap = new Map();
    for (var j = 0; j < caseLength; j++)
    {
        caseMap[caseArray[j]] = j;
    }
    var start = 0;
    var flag = false;
    var result = "";
    for (var j = 0; j < caseLength; j++)
    {
        if (caseArray[j] !== `${j+1}`)
        {
            var startRevIndex = caseMap[`${j+1}`];
            if (startRevIndex !== null)
            {
                for (var k = startRevIndex; k >= j; k--)
                {
                    result += `${caseArray[k]} `;
                }
                start = startRevIndex;
                flag = true;
                break;
            }
        }
        else result += `${caseArray[j]} `;
    }
    if (flag)
    {
        for (var j = start; j < caseLength; j++)
        {
            result += `${caseArray[j]} `;
        }
    }
    print(result);
}

"use strict";

//let startTime = Date.now();

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

let inputString = "";
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numOfTests = +(readline());

    for (let i=0; i<numOfTests; i++){
        const lengthOfArr = +(readline());
        let arr = readline().split(" ").map((string) => {
            return +(string);
        });

        let result = arr;

        for (let i=0; i<lengthOfArr-1; i++) {
            const a = arr[i];
            const b = arr[i+1];

            if (b < a) {
                result[i+1] = a;
                result[i] = b;
                break;
            }
        }

        console.log(result.toString().replace(/,/g, " "));
    }

//    console.log(Date.now() - startTime + " ms");
}

'use strict';
 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  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 l = process.env.DEBUG ? console.log : ()=>{};

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

const calc = (n, P)=>{
  let i;
  for (i=0; P[i]==i+1 && i<n; i++);
  if (i==n){
    return P;
  }
  let l = i;
  let minI = i;
  for (let j=i; j<n; j++){
    if (P[j]<P[minI])
      minI = j;
  }
  let r = minI;
  for (i=l; i<(l+r)/2; i++){
    let j = r-(l-i);
    let tmp = P[i];
    P[i] = P[j]
    P[j] = tmp
  }
  return P
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let A = ra();
      l('ans')
      print(calc(n, A).join(' '));
    }
}

E.calc = calc;

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

const reverse = (perm, l, r) => {
	return [
		...perm.slice(0, l),
		...perm.slice(l, r + 1).reverse(),
		...perm.slice(r + 1),
	];
};

function main() {
	const testCount = +readline();

	for (let i = 0; i < testCount; i++) {
		let permLength = +readline();
		let perm = readline().split(" ");

		let startIndex = 0;

		const sorted = perm.slice().sort();

		while (
			sorted[startIndex] === perm[startIndex] &&
			startIndex < perm.length
		) {
			startIndex++;
		}

		if (startIndex === perm.length) {
			console.log(perm.join(" "));
		} else {
			const swapIndex = perm.indexOf(sorted[startIndex]);

			console.log(reverse(perm, startIndex, swapIndex).join(" "));
		}
	}
}


'use strict';

function solve(n, s) {
  const len0 = s.split('').filter(char => char === '0').length;
  if (s[0] === '0' || s[s.length - 1] === '0' || len0 & 1) return 'NO';
  let res1 = [],
      res2 = [],
      pre = 0;
  for (let i = 0; i < n; i++) {
    if (s[i] === '0') {
      if (pre === 0) {
        res1[i] = '(';
        res2[i] = ')';
      } else {
        res1[i] = ')';
        res2[i] = '(';
      }
      pre ^= 1;
    }
  }
  {
    let l = n / 2 - len0 / 2;
    for (let i = 0; i < n; i++) {
      if (s[i] === '0') continue;
      if (l) {
        res1[i] = '(';
        res2[i] = '(';
        l--;
      } else {
        res1[i] = ')';
        res2[i] = ')';
      }
    }
  }
  return `YES\n${res1.join('')}\n${res2.join('')}`;
}

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

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

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const s = rl();

		let cnt = [0, 0];
		for (let i = 0; i < n; i++) {
			cnt[s[i]]++;
		}

		if (s[0] == 0 || s[n-1] == 0 || cnt[0] & 1) {
			console.log('NO');
			continue;
		}

		const ans = [[], []];
		for (let i = 0, use, cntOpen = 0, last; i < n; i++) {
			if (s[i] == 1) {
				use = cntOpen < cnt[1]/2 ? '((' : '))';
				cntOpen++;
			} else {
				use = last ? "()" : ")(";
				last ^= 1;
			}
			ans[0][i] = use[0];
			ans[1][i] = use[1];
		}

		console.log('YES');
		console.log(ans[0].join(''));
		console.log(ans[1].join(''));
	}
}

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

//Don't have to see. end------------------------------------------

function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var b = next();
		if(b[0] == "0" || b[N - 1] == "0"){
			myout("NO");
			continue;
		}
		var one = 0;
		var zero = 0;
		for(var j = 0; j < N; j++){
			if(b[j] == "1"){
				one++;
			}else{
				zero++;
			}
		}
		if(one % 2 == 0 && zero % 2 == 0){
			myout("YES");
			var L = new Array(N);
			var R = new Array(N);
			var Ocount = 0;//max:N / 2
			var Zcount = 0;//max: N /2
			for(var j = 0; j < N; j++){
				if(b[j] == "1"){
					if(Ocount < one / 2){
						Ocount++;
						L[j] = "(";
						R[j] = "(";
					}else{
						L[j] = ")";
						R[j] = ")";
					}
				}else{
					if(Zcount % 2 == 0){
						L[j] = "(";
						R[j] = ")";
					}else{
						L[j] = ")";
						R[j] = "(";
					}
					Zcount++;
				}
			}
			myout(myconv(L, 0));
			myout(myconv(R, 0));
		}else{
			myout("NO");
		}
	}
	/*var N = nextInt();
	var ok = new Set();
	for(var i = 0; i < (1 << N); i++){
		var s = "";
		for(var j = 0; j < N; j++){
			s += ((i & (1 << j)) != 0) ? "1" : "0";
		}
		for(var j = 0; j < (1 << N); j++){
			var L = "";
			var R = "";
			for(var k = 0; k < N; k++){
				if((j & (1 << k)) != 0){
					if(s[k] == "0"){
						L += "(";
						R += ")";
					}else{
						L += "(";
						R += "(";
					}
				}else{
					if(s[k] == "0"){
						L += ")";
						R += "(";
					}else{
						L += ")";
						R += ")";
					}
				}
			}
			var Li = [];
			var Ri = [];
			for(var k = 0; k < N; k++){
				if(L[k] == "("){
					Li.push("(");
				}else if(Li[Li.length - 1] == "("){
					Li.pop();
				}else{
					Li.push(")");
				}
				if(R[k] == "("){
					Ri.push("(");
				}else if(Ri[Ri.length - 1] == "("){
					Ri.pop();
				}else{
					Ri.push(")");
				}
			}
			if(Li.length == 0 && Ri.length == 0){
				myerr({s, L, R});
				ok.add(s);
			}
		}
	}
	myerr(ok);*/
}


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

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

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

  l += x;
  r += y;

  c++;
});

rl.on('close', () => {
  const ans = Math.min(n - l, l) + Math.min(n - r, r);

  console.log(ans);
});

print(function(n) {

	var l = 0,
		r = 0;
	for (var i = 0; i < n; i++)
		readline().split(' ').map(Number).reduce(function(ll, rr) {
			l += ll;
			r += rr;
		});

	return Math.min(n - l, l) + Math.min(n - r, r);

}(+readline()));

"use strict";

//readline().split(' ').map(Number);

function sec(){
    print("F")
}

function main(){
    var t = readline();
    var a = 0,b = 0;
    for (var i = 0;i<t;i++){
        var arr = readline().split(' ').map(Number);
        a += arr[0];
        b += arr[1];
    }
    print(Math.min(a,t-a)+Math.min(b,t-b));
}

main();

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  let [l0, l1] = [0, 0];
  let [r0, r1] = [0, 0];
  while (t--) {
    const [left, right] = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    if (left === 0) l0++;
    else l1++;

    if (right === 0) r0++;
    else r1++;
  }
  console.log(`${Math.min(l0, l1) + Math.min(r0, r1)}`);
}

//Cupboards

const {EOL} = require('os');

let inp = '';

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

process.stdin.on('end', () => {
    let lines = inp.split(EOL);

	let cnt = [0, 0, 0, 0]; //c, l, o, r
	for(let i in lines)  {
		if(lines[i] == '0 0')  {
			cnt[0]++;
		}
		if(lines[i] == '1 0')  {
			cnt[1]++;
		}
		if(lines[i] == '1 1')  {
			cnt[2]++;
		}
		if(lines[i] == '0 1')  {
			cnt[3]++;
		}
	}

	let t = [];
	for(let i = 0; i < 4; i++)  {
		t.push(cnt[(i + 1) % 4] + cnt[(i + 3) % 4] + (2 * cnt[(i + 2) % 4]));
	}

	process.stdout.write(Math.min(...t) + '');

    return;
});

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

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

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

  if (x === 0) {
    c1++;
  }
  else {
    o1++;
  }

  if (y === 0) {
    c2++;
  }
  else {
    o2++;
  }

  c++;
});

rl.on('close', () => {
  let ans = n - Math.max(o1, c1) + n - Math.max(o2, c2);

  console.log(ans);
});

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function isPrime(x) {
	let s = Math.sqrt(x);
	let i = 2;
	while (i <= s) {
		if (x % i === 0) {
			return false;
		}
		i++;
	}
	return true;
}

function main() {
	let n = readLine() >> 0;
	let m = n;
	let cl = {},
		cr = {};
	while (n--) {
		let [l, r] = readLine()
			.split(' ')
			.map(x => x >> 0);

		cl[l] = (cl[l] || 0) + 1;
		cr[r] = (cr[r] || 0) + 1;
	}

	let res = 0;
	let lt = Math.min(...Object.values(cl));
	lt = lt === m ? 0 : lt;
	let rt = Math.min(...Object.values(cr));
	rt = rt === m ? 0 : rt;

	res = lt + rt;
	console.log(res);
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}

function main() {
    let cupBoards = parseInt(readLine());
    let leftDoors = [];
    let rightDoors = [];
    for (let i = 0; i < cupBoards; i++) {
        const doorsArray = readLine().split(' ').map(Number);
        let [left, right] = doorsArray;
        leftDoors.push(left);
        rightDoors.push(right);
    }

    function NumberInArray(array, number) {
        let count = 0;
        for (let i = 0; i < array.length; i++) {
            if (array[i] === number) {
                count++;
            }
        }
        return count;
    }
    let ZerosinLeftArray = NumberInArray(leftDoors, 0);
    let OnesinLeftArray = NumberInArray(leftDoors, 1);
    let ZerosinRightArray = NumberInArray(rightDoors, 0);
    let OnesinRightArray = NumberInArray(rightDoors, 1);
    if (ZerosinLeftArray === cupBoards && ZerosinRightArray === cupBoards) {
        console.log(0);
        return;
    }
    if (OnesinRightArray === cupBoards && OnesinLeftArray == cupBoards) {
        console.log(0);
        return;
    }
    let changesinLeftDoors;
    if (
        ZerosinLeftArray > OnesinLeftArray
        // ZerosinLeftArray > ZerosinRightArray
    ) {
        changesinLeftDoors = OnesinLeftArray;
        // let changesinRightDoors = ZerosinRightArray;
        // console.log(changesinLeftDoors + changesinRightDoors);
    } else if (ZerosinLeftArray < OnesinLeftArray) {
        changesinLeftDoors = ZerosinLeftArray;
        // let changesinRightDoors = OnesinRightArray;
        // console.log(changesinLeftDoors + changesinRightDoors);
    } else if (ZerosinLeftArray === OnesinLeftArray) {
        changesinLeftDoors = ZerosinLeftArray;
    }

    let changesinRightDoors;
    if (ZerosinRightArray > OnesinRightArray) {
        changesinRightDoors = OnesinRightArray;
    } else if (ZerosinRightArray < OnesinRightArray) {
        changesinRightDoors = ZerosinRightArray;
    } else if (ZerosinRightArray === OnesinRightArray) {
        changesinRightDoors = ZerosinRightArray;
    }

    console.log(changesinLeftDoors + changesinRightDoors);
}

let data = '';
process.stdin.on('data', c => data += c);
const solution = () => {
	let line = data.split('\n');
	let n = parseInt(line[0], 10);
	let r = 0;
	let l = 0;
	for(let i = 1; i <= n; i++){
		let [x, y] = line[i].split(' ').map(v => parseInt(v,10));
		l += x;
		r += y;
	}
	console.log(Math.min(l, n - l) + Math.min(r, n - r));

};

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

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

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

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

  if (x === 0) {
    c1++;
  }
  else {
    o1++;
  }

  if (y === 0) {
    c2++;
  }
  else {
    o2++;
  }

  c++;
});

rl.on('close', () => {
  let ans = Math.min(o1 + c2, c1 + o2);

  if (o1 === o2 && c1 === c2) {
    ans = 0;
  }

  console.log(ans);
});

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

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

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

  if (x === 0) {
    c1++;
  }
  else {
    o1++;
  }

  if (y === 0) {
    c2++;
  }
  else {
    o2++;
  }

  c++;
});

rl.on('close', () => {
  const ans = Math.min(o1 + c2, c1 + o2);
  console.log(ans);
});

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function isPrime(x) {
	let s = Math.sqrt(x);
	let i = 2;
	while (i <= s) {
		if (x % i === 0) {
			return false;
		}
		i++;
	}
	return true;
}

function main() {
	let n = readLine() >> 0;
	let cl = {},
		cr = {};
	while (n--) {
		let [l, r] = readLine()
			.split(' ')
			.map(x => x >> 0);

		cl[l] = (cl[l] || 0) + 1;
		cr[r] = (cr[r] || 0) + 1;
	}

	let res = 0;
	res = Math.min(...Object.values(cl)) + Math.min(...Object.values(cr));
	console.log(res);
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}

function main() {
    let cupBoards = parseInt(readLine());
    let leftDoors = [];
    let rightDoors = [];
    for (let i = 0; i < cupBoards; i++) {
        const doorsArray = readLine().split(' ').map(Number);
        let [left, right] = doorsArray;
        leftDoors.push(left);
        rightDoors.push(right);
    }

    function NumberInArray(array, number) {
        let count = 0;
        for (let i = 0; i < array.length; i++) {
            if (array[i] === number) {
                count++;
            }
        }
        return count;
    }
    let ZerosinLeftArray = NumberInArray(leftDoors, 0);
    let OnesinLeftArray = NumberInArray(leftDoors, 1);
    let ZerosinRightArray = NumberInArray(rightDoors, 0);
    let OnesinRightArray = NumberInArray(rightDoors, 1);

    if (
        ZerosinLeftArray > OnesinLeftArray &&
        ZerosinLeftArray > ZerosinRightArray
    ) {
        let changesinLeftDoors = OnesinLeftArray;
        let changesinRightDoors = ZerosinRightArray;
        console.log(changesinLeftDoors + changesinRightDoors);
    } else {
        let changesinLeftDoors = ZerosinLeftArray;
        let changesinRightDoors = OnesinRightArray;
        console.log(changesinLeftDoors + changesinRightDoors);
    }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}

function main() {
    let cupBoards = parseInt(readLine());
    let leftDoors = [];
    let rightDoors = [];
    for (let i = 0; i < cupBoards; i++) {
        const doorsArray = readLine().split(' ').map(Number);
        let [left, right] = doorsArray;
        leftDoors.push(left);
        rightDoors.push(right);
    }

    function NumberInArray(array, number) {
        let count = 0;
        for (let i = 0; i < array.length; i++) {
            if (array[i] === number) {
                count++;
            }
        }
        return count;
    }
    let ZerosinLeftArray = NumberInArray(leftDoors, 0);
    let OnesinLeftArray = NumberInArray(leftDoors, 1);
    let ZerosinRightArray = NumberInArray(rightDoors, 0);
    let OnesinRightArray = NumberInArray(rightDoors, 1);
    if (ZerosinLeftArray === cupBoards && ZerosinRightArray === cupBoards) {
        console.log(0);
        return;
    }
    if (OnesinRightArray === cupBoards && OnesinLeftArray == cupBoards) {
        console.log(0);
        return;
    }
    let changesinLeftDoors;
    if (
        ZerosinLeftArray > OnesinLeftArray
        // ZerosinLeftArray > ZerosinRightArray
    ) {
        changesinLeftDoors = OnesinLeftArray;
        // let changesinRightDoors = ZerosinRightArray;
        // console.log(changesinLeftDoors + changesinRightDoors);
    } else if (ZerosinLeftArray < OnesinLeftArray) {
        changesinLeftDoors = ZerosinLeftArray;
        // let changesinRightDoors = OnesinRightArray;
        // console.log(changesinLeftDoors + changesinRightDoors);
    }

    let changesinRightDoors;
    if (ZerosinRightArray > OnesinRightArray) {
        changesinRightDoors = OnesinRightArray;
    } else if (ZerosinRightArray < OnesinRightArray) {
        changesinRightDoors = ZerosinRightArray;
    }

    console.log(changesinLeftDoors + changesinRightDoors);
}


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

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

var key = new Array(k);
for (var i = 0; i < k; ++i) {
	key[i] = readline().split(" ", 3).map(Number);
}

var rowu = new Array(n), rown = n;
var colu = new Array(m), coln = m;

var kk = k - 1;
while(rown !== 0 && coln !== 0 && kk >= 0) {
	var t = key[kk][1] - 1;
	if (key[kk][0] === 1) {
		if (!rowu[t]) {
			rowu[t] = true;
			--rown;
			for (var i = 0; i < m; ++i) {
				if (map[t][i] === 0) {
					map[t][i] = key[kk][2];
				}
			}
		}
	} else {
		if (!colu[t]) {
			colu[t] = true;
			--coln;
			for (var i = 0; i < n; ++i) {
				if (map[i][t] === 0) {
					map[i][t] = key[kk][2];
				}
			}
		}
	}
	--kk;
}

for (var i = 0; i < n; ++i) {
	print(map[i].join(" "));
}

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

var rown = new Array(n), rowc = new Array(n);
var coln = new Array(m), colc = new Array(m);

for (var i = 0; i < k; ++i) {
	arr = readline().split(" ", 3).map(Number);
	--arr[1];
	if (arr[0] === 1) {
		rown[arr[1]] = i + 1;
		rowc[arr[1]] = arr[2];
	} else {
		coln[arr[1]] = i + 1;
		colc[arr[1]] = arr[2];
	}
}

for (var i = 0; i < n; ++i) {
	var ans = "";
	for (var j = 0; j < m; ++j) {
		if (rown[i]) {
			if (coln[j]) {
				ans += (rown[i] > coln[j] ? rowc[i] : colc[j]) + " ";
			} else {
				ans += rowc[i] + " ";
			}
		} else {
			if (coln[j]) {
				ans += colc[j] + " ";
			} else {
				ans += "0 ";
			}
		}
	}
	print(ans);
}

try {require('codef');} catch (e){global = this};
function readLineAsArray(separator){return readline().split(typeof separator == "undefined" ? ' ' : separator)}
function readLineAsIntegerArray(separator){return readLineAsArray(separator).map(function(v){return +v})}
Array.prototype.list = function() {var length = arguments.length; for(var i=0; i < length; i++){global[arguments[i]] = this[i]}};
String.prototype.repeat = function(n){return new Array(n + 1).join(this);}

var tmp = readLineAsIntegerArray(),
	n = tmp[0],
	m = tmp[1],
	k = tmp[2];

var arr = [],
	moves = [];

for(var i = 0; i < n; i++) {
	arr.push([]);
	for(var j = 0; j < m; j++) {
		arr[i].push(0);
	}
}

function markH(index, c){
	index--;
	for(var j = 0; j < m; j++) {
		arr[index][j] = c;
	}
}
function markV(index, c){
	index--;
	for(var j = 0; j < n; j++) {
		arr[j][index] = c;
	}
}

function printM(){
	for(var i = 0; i < n; i++) {
		write(arr[i].join(' ') + '\n')
	}
}

var map = {1: {}, 2: {}};
var moves = [];

for(var i = 0 ; i < k; i++) {
	var item;
	moves.push(item = readLineAsIntegerArray());
	if (map[item[0]][item[1]]) {
		moves[map[item[0]][item[1]]] = false;
	}
	map[item[0]][item[1]] = i;
}

for(var i = 0; i < moves.length; i++) {
	if (moves[i]) {
		(moves[i][0] == 1 ? markH : markV)(moves[i][1], moves[i][2]);
	}
}

printM();

try {require('codef');} catch (e){global = this};
function readLineAsArray(separator){return readline().split(typeof separator == "undefined" ? ' ' : separator)}
function readLineAsIntegerArray(separator){return readLineAsArray(separator).map(function(v){return +v})}
Array.prototype.list = function() {var length = arguments.length; for(var i=0; i < length; i++){global[arguments[i]] = this[i]}};
String.prototype.repeat = function(n){return new Array(n + 1).join(this);}

tmp = readLineAsIntegerArray();
var n = tmp[0],
	m = tmp[1],
	k = tmp[2];

var arr = [];
for(var i = 0; i < n; i++) {
	arr.push([]);
	for(var j = 0; j < m; j++) {
		arr[i].push(0);
	}
}

function markH(index, c){
	index--;
	for(var j = 0; j < m; j++) {
		arr[index][j] = c;
	}
}
function markV(index, c){
	index--;
	for(var j = 0; j < n; j++) {
		arr[j][index] = c;
	}
}

function printM(){
	for(var i = 0; i < n; i++) {
		write(arr[i].join(' '));
	}
}

for(var i = 0 ; i < k; i++) {
	var tmp = readLineAsIntegerArray();
	(tmp[0] == 1 ? markH : markV)(tmp[1], tmp[2]);
	//printM();
	//console.log('================');
}
printM();


var n = parseInt(readline());
var a = readline().split(" ").map(Number);

var s = "";
var cur = 'a';
for (var i = n - 1; i >= 0; i--) {
	while (a[i]) {
		for (var j = 0; j <= i; j++) {
			s += cur;
			a[j] -= (i - j + 1);
		}
		if (cur=="a") cur = "b"; else cur = "a";
	}
}
print(s);

var n = +readline();
var a = readline().split(' ').map(function(v) { return +v; });
var groups = [];
for (var i = n-1; i >= 0; i--) {
    var knt = a[i];
    for (var j = 0; j < knt; j++) {
        groups.push(i+1);
    }
    for (var j = 0; j <= i; j++) {
        a[i-j] -= knt * (j+1);
    }
}
var res = "";
var c = 'a';
for (var i = 0; i < groups.length; i++) {
    for (var j = 0; j < groups[i]; j++) {
        res += c;
    }
    c = (c == 'a') ? 'b' : 'a';
}
print(res);

var n = +readline();
var v = readline().split(' ').map(function(k){return +k;});
v.splice(0,0,0);
var ans = [];
for(var i = n; i > 0; i--){
    if(v[i] === 0)
        continue;
    for(var k = 0; k < v[i]; k++)
        ans.push(i);
    for(var j = i - 1; j > 0; j--)
        v[j] -= v[i] * (i - j + 1);
}
for(var i = 0; i < ans.length; i++){
    for(var j = 0; j < ans[i]; j++){
        if(i % 2 == 1) write("b");
        else write("a");
    }
}


t = readline()
for(var i = 0; i < t;i++)
{
    n = readline();
    print(n, ' ');
    for(var j = 1 ; j < n;j++)
    {
        print(j, ' ');
    }
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		if(N == 1){
			myout(1);
			continue;
		}
		var output = [N];
		for(var i = 1; i < N ; i++){
			output.push(i);
		}
		myout(myconv(output, 8));
	}
}

'use strict';

const fs = require('fs');

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 calc(n) {
    if (n == 1) {
        console.log(1)
        return
    } else if (n == 2) {
        console.log("2 1")
        return
    } else if (n == 3) {
        console.log("3 1 2")
        return
    }

    let s = "2 1"
    for (let i = 3; i <= n - 1; i++) {
        s += " " + (i + 1)
    }

    s += " 3"
    console.log(s)
}

function main() {
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
        const n = parseInt(readLine().trim(), 10);

        if (n >= 1 && n <= 100000) {
           // const val = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
            let output = calc(n);
            // console.log(output)
        }
        // ws.write(result + '\n');
    }

    // ws.end();
}

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

function print(x) {
    console.log(x);
}

let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});

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

function readNumbersLine() {
    return readline().split(" ").map(el => +el);
}

let arr = {};
let ans = [0, 0];

function main() {
    let k = +readline()
    for (let i = 0; i < k; i++) {
        let n = +readline()
        let res = ""
        for (let j = 2; j <= n; j++) {
            res += j +' ';
        }
        res += 1;
        console.log(res);
    }

}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main(){
    var tests = parseInt(readline());
    for (let t = 0;t < tests; ++t) {
        var n = parseInt(readline());
        let arr = [n];
        for (let i = 1;i < n;++i) {
            arr.push(i);
        }
        console.log(arr.join(' ').toString());
    }

}

"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 getValue() {
  return parseInt(readline());
}
let mod = BigInt(1e9 + 7);
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue(),
      res = [];
    if (n === 1) console.log(1);
    else {
      let arr = new Array(n).fill(0).map((cur, ind) => ind + 1);
      for (let i = 0; i + 1 < n; i += 2) {
        [arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
      }
      if (n % 2 === 0) console.log(arr.join(" "));
      else {
        [arr[0], arr[n - 1]] = [arr[n - 1], arr[0]];
        console.log(arr.join(" "));
      }
    }
  }
};
solve();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

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

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);

        let result = [];

        for (let i = 2; i <= n; i++) {
            result.push(i);
        }
        result.push(1);

        output(result.join(' '));
    }
}

var a = parseInt(readline());

for(var i = 0; i < a; i++){
	var n = parseInt(readline());

	var arr = [n];

	// arr.push(n);

	for(var j = 1; j < n; j++){
		arr.push(j);
	}

	// arr.push(1);

	// if(n === 1){
	// 	print(1);
	// }
	// else{
	// 	print(arr.join(' '));
	// }

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

var a = parseInt(readline());

for(var i = 0; i < a; i++){
	var n = parseInt(readline());

	var arr = [n];

	arr.push(1);

	for(var j = 2; j < n; j++){
		arr.push(j);
	}

	if(n === 1){
		print(1);
	}
	else{
		print(arr.join(' '));
	}
}

var t = parseInt(readline());

while (t--) {
    var n = parseInt(readline());
    var result = [];
    for (var i = 0; i < n - 1; i++) {
        result.push(i + 2);
    }
    result.push(1);
    print(result.join(" "));
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var value = parseInt(readline());
    var result = "";
    for (var j = 2; j <= value; j++)
    {
        result += `${j} `;
    }
    result += "1 ";
    print(result);
}

var tests = parseInt(readline());
    for (var t=0; t < tests; t++) {
        var n = parseInt(readline());
        var ans = [ n ];
        for (var i = 0; i < n-1; i++) {
            ans.push(i+1);
        }
        print(ans.join(' '));
    }

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    var a = 0
    for(j = 1; j <= n ;j ++){
    var k = lines[j]
        a = k + ' '
        for(l = 1; l < k; l++){
            a += l + ' '
        }
            console.log(a)

    }

});

t = readline()
for(var i = 0; i < t;i++ )
{
var start = readline(), end = readline();
var arr = [];

arr.push(end)
for (var i = start; i < end; i++) { arr.push(i) }

print(start)
print(arr.join(' '))
}

t = readline()
for(var i = 0; i < t;i++ )
{
    n = readline(), start = readline(), end = readline();
var arr = [];

arr.push(end)
for (var i = start; i < end; i++) { arr.push(i) }

print(start)
print(arr.join(' '))
}

var n = readline(), start = readline(), end = readline();
var arr = [];

arr.push(end)
for (var i = start; i < end; i++) { arr.push(i) }

print(start)
print(arr.join(' '))

for (var x = 2; x < parseInt(n); x++) {
	var end = readline();
	var arr = [];

	arr.push(end)
	for (var i = start; i < end; i++) { arr.push(i) }
	print(arr.join(' '))
}

var n = readline(), start = readline(), end = readline();
var arr = [];

arr.push(end)
for (var i = start; i < end; i++) { arr.push(i) }

print(start)
print(arr.join(' '))

for (var x = 2; x < parseInt(n); x++) {
	var end = readline();
	var arr = [];

	arr.push(end)
	for (var i = start; i < end; i++) { arr.push(i) }

	print(start)
	print(arr.join(' '))
}

var n = readline(), start = readline(), end = readline();
var arr = [];

arr.push(end)
for (var i = start; i < end; i++) { arr.push(i) }

print(start)
print(arr.join(' '))

for (var x = 2; x < parseInt(n); x++) {
	var start = end, end = readline();
	var arr = [];

	arr.push(end)
	for (var i = start; i < end; i++) { arr.push(i) }

	print(start)
	print(arr.join(' '))
}

var n = readline(), start = readline(), end = readline();
var arr = [];

arr.push(end)
for (var i = start; i < end; i++) { arr.push(i) }

print(start)
print(arr.join(' '))

for (var x = 1; x < parseInt(n); x++) {
	var start = end, end = readline();
	var arr = [];

	arr.push(end)
	for (var i = start; i < end; i++) { arr.push(i) }

	print(start)
	print(arr.join(' '))
}

var n = readline(), start = readline(), end = readline();
var arr = [];

arr.push(end)
for (var i = start; i < end; i++) { arr.push(i) }

print(start)
print(arr.join(' '))

for (var x = 1; x < n; x++) {
	var start = end, end = readline();
	var arr = [];

	arr.push(end)
	for (var i = start; i < end; i++) { arr.push(i) }

	print(start)
	print(arr.join(' '))
}

var n = readline(), start = readline(), end = readline();
var arr = [];

arr.push(end)
for (var i = start; i < end; i++) { arr.push(i) }

print(start)
print(arr.join(' '))

for (var i = 0; i < n - 1; i++) {
	var start = end, end = readline();
	var arr = [];

	arr.push(end)
	for (var i = start; i < end; i++) { arr.push(i) }

	print(start)
	print(arr.join(' '))
}

var n = readline(), start = readline(), end = readline();
var arr = [];

arr.push(end)
for (var i = start; i < end; i++) { arr.push(i) }

print(start)
print(arr.join(' '))

for (var i = 0; i < n; i++) {
	var start = end, end = readline();
	var arr = [];

	arr.push(end)
	for (var i = start; i < end; i++) { arr.push(i) }

	print(start)
	print(arr.join(' '))
}

var n = readline(), start = readline(), end = readline();
var arr = [];

arr.push(end)
for (var i = start; i < end; i++) { arr.push(i) }

print(start)
print(arr.join(' '))

for (var i = 0; i <= n; i++) {
	var start = end, end = readline();
	var arr = [];

	arr.push(end)
	for (var i = start; i < end; i++) { arr.push(i) }

	print(start)
	print(arr.join(' '))
}

var n = readline(), start = readline(), end = readline();
var arr = [];

arr.push(end)
for (var i = start; i < end; i++) { arr.push(i) }

print(1)
print(arr.join(' '))

var n = readline(), start = readline(), end = readline();
var arr = [];

arr.push(end)
for (var i = start; i < end; i++) { arr.push(i) }

print(arr.join(' '))

var n = readline(), start = readline(), end = readline();
var arr = [];

for (var i = start; i <= end; i++) { arr.push(i) }
arr.reverse()

print(arr.join(' '))

var n = readline(), start = readline(), end = readline();
var arr = [];

for (var i = start; i < end; i++) { arr.push(i) }

arr.reverse()

print(arr.join(' '))

var a = parseInt(readline());

for(var i = 0; i < a; i++){
	var n = parseInt(readline());

	var arr = [n];

	arr.push(n);

	for(var j = 1; j < n; j++){
		arr.push(j);
	}

	// arr.push(1);

	// if(n === 1){
	// 	print(1);
	// }
	// else{
	// 	print(arr.join(' '));
	// }

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

var a = parseInt(readline());

for(var i = 0; i < a; i++){
	var n = parseInt(readline());

	var arr = [n];

	arr.push(n);

	for(var j = 2; j < n; j++){
		arr.push(j);
	}

	// arr.push(1);

	// if(n === 1){
	// 	print(1);
	// }
	// else{
	// 	print(arr.join(' '));
	// }

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

var a = parseInt(readline());

for(var i = 0; i < a; i++){
	var n = parseInt(readline());

	var arr = [n];

	// arr.push(1);

	for(var j = 2; j < n; j++){
		arr.push(j);
	}

	arr.push(1);

	// if(n === 1){
	// 	print(1);
	// }
	// else{
	// 	print(arr.join(' '));
	// }

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

var a = parseInt(readline());

for(var i = 0; i < a; i++){
	var n = parseInt(readline());

	var arr = [n];

	arr.push(1);

	for(var j = 2; j < n; j++){
		arr.push(j);
	}

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

var a = parseInt(readline());

for(var i = 0; i < a; i++){
	var n = parseInt(readline());

	var arr = [n];

	arr.push(1);

	for(var j = 2; j <= n; j++){
		arr.push(j);
	}

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

var a = parseInt(readline());

for(var i = 0; i < a; i++){
	var n = parseInt(readline());

	var arr = [n];

	for(var j = 1; j <= n; j++){
		arr.push(j);
	}

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

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    var k = lines[1].split(' ').map(Number)
    var a = k[k.length - 1] + ' '
    for(j = 1; j < n ;j ++){
        a +k[j] + ' '
    }
    console.log(1)
    console.log(a)

});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    var k = lines[1].split(' ').map(Number)
    var a = k[k.length - 1] + ' '
    for(j = 1; j < n ;j ++){
        a +k[j] + ' '
    }

});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    for(j = 1; j <= n ;j +=2){

    }
    console.log(1)
    console.log(1 + ' ' + 2 + ' ' + 3 + ' ' + 4)

});

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0]
    for(j = 1; j <= n ;j +=2){

    }
    console.log(1)
    console.log(2 + ' ' + 1 + ' ' + 4 + ' ' + 3)

});

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		if(N == 1){
			myout(1);
			continue;
		}
		var output = [];
		for(var i = 0; i < N / 2; i++){
			output.push(i * 2 + 2);
			output.push(i * 2 + 1);
		}
		myout(myconv(output, 8));
	}
}

'use strict';

const fs = require('fs');

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 calc(n) {
    if (n == 1) {
        console.log(1)
        return
    }

    let s = "2 1"
    for (let i = 3; i <= n - 1; i++) {
        s += " " + (i + 1)
    }

    s += " 3"
    console.log(s)
}

function main() {
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
        const n = parseInt(readLine().trim(), 10);

        if (n >= 1 && n <= 100000) {
           // const val = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
            let output = calc(n);
            // console.log(output)
        }
        // ws.write(result + '\n');
    }

    // ws.end();
}

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

function print(x) {
    console.log(x);
}

let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main();
});

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

function readNumbersLine() {
    return readline().split(" ").map(el => +el);
}

let arr = {};
let ans = [0, 0];

function main() {
    let k = +readline()
    for (let i = 0; i < k; i++) {
        let n = +readline()
        let res = ""
        for (let j = 2; j <= n; j++) {
            res += j;
        }
        res += 1;
        console.log(res);
    }

}