;(function () {

	print(function (n) {

		var a = readline().split(' '),
			isEqual = true,
			max = 0, j = 0;

		for (var i = 0; i < n; i++) {
			a[i] = +a[i];

			if (isEqual && a[i] !== a[0]) isEqual = false;

			if (max < a[i]) {
				j = i;
				max = a[i];
			}
		}

		if (isEqual) {

			if (a[0] !== 1) a[0] = 1;
			else a[a.length - 1] = 2;

		} else a[j] = 1;

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

	}(+readline()));

}.call(this));

//Input
// var firstLine = "5" ; var secondLine = "1 2 3 4 5"      //R: 1 1 2 3 4
// var firstLine = "5" ; var secondLine = "2 3 4 5 6 "      //R: 1 2 3 4 5
// var firstLine = "3" ; var secondLine = "2 2 2"      //R: 1 2 2
// var firstLine = "4" ; var secondLine = "1 1 2 3"      //R: 1 1 1 2

// var firstLine = "3" ; var secondLine = "1 1 1"      //R: 1 1 2

// var firstLine = "10" ; var secondLine = "5 6 1 2 3 1 3 45 7 1000000000"      //R: 1 1 1 2 3 3 5 6 7 45
// var firstLine = "1" ; var secondLine = "1 "      //R: 1

var firstLine = readline(); var secondLine = readline();

retorno = eval(firstLine, secondLine);

//Solution
function eval(firstLine, secondLine){
    var n = parseInt(firstLine);
    var arr = secondLine.split(" ").map(function (x){ return parseInt(x)});

    write(replace(arr));
    // console.log(replace(arr));
    return "Hola";
};

function replace(arr){
    var len = arr.length;
    var newArr = ""; new Array(len+1).join("0").split("").map(parseInt); if(len > 1){newArr[1] = 0};

    arr.sort(function (a, b){return a-b});
    if(arr[len-1] != 1){
        arr[len-1] = 1;
    } else{
        arr[len-1] = 2
    };
    arr.sort(function(a, b){ return a-b});

    for(var i = 0 ; i < len ; i++){
        newArr += "" + arr[i];
        if(i < len -1){
            newArr += " ";
        };
    };

    return newArr;
};

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    let [_, ...arr] = i.split`\n`;
    arr = arr[0].split` `.map(Number);
    arr.sort((a, b) => a - b);
    arr.pop() === 1 ? arr.push(2) : arr.unshift(1);
    console.log(arr.join` `);
});

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

//135A, 2 attempts
var n = readline();
var arr = getNums();
var max = {val: 1, pos: -1};
for (var i = 0; i < n; i++) {
    if (arr[i] > max.val) {
        max = {val: arr[i], pos: i};
    }
}
if (max.pos === -1) {
    arr[0] = 2;
} else {
    arr[max.pos] = 1;
}
print(arr.sort(function(a, b){return a - b}).join(' '));

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    let [_, ...arr] = i.split`\n`;
    arr = arr[0].split` `.map(Number);
    arr.sort((a, b) => a - b);
    arr.pop() === 1 ? arr.push(2) : arr.unshift(1);
    console.log(arr);
});

//Input
// var firstLine = "5" ; var secondLine = "1 2 3 4 5"      //R: 1 1 2 3 4
// var firstLine = "5" ; var secondLine = "2 3 4 5 6 "      //R: 1 2 3 4 5
// var firstLine = "3" ; var secondLine = "2 2 2"      //R: 1 2 2
// var firstLine = "4" ; var secondLine = "1 1 2 3"      //R: 1 1 1 2

// var firstLine = "3" ; var secondLine = "1 1 1"      //R: 1 1 2

// var firstLine = "10" ; var secondLine = "5 6 1 2 3 1 3 45 7 1000000000"      //R: 1 1 1 2 3 3 5 6 7 45
// var firstLine = "1" ; var secondLine = "1 "      //R: 1

var firstLine = readline(); var secondLine = readline();

retorno = eval(firstLine, secondLine);

//Solution
function eval(firstLine, secondLine){
    var n = parseInt(firstLine);
    var arr = secondLine.split(" ").map(function (x){ return parseInt(x)});

    // console.log(replace(arr));
    write(replace(arr));
    return "Hola";
};

function replace(arr){
    var len = arr.length;
    var newArr = new Array(len+1).join("0").split("").map(parseInt); if(len > 1){newArr[1] = 0};

    //console.log("arr: " + arr);
    arr.sort(function (a, b){return a-b});
    //console.log("arr: " + arr);
    if(arr[len-1] != 1){
        arr[len-1] = 1;
    } else{
        arr[len-1] = 2
    };
    arr.sort(function(a, b){ return a-b});

    return arr;
};

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

//134B
var n = readline();
var arr = getNums();
var max = {val: arr[0], pos: 0};
for (var i = 1; i > n; i++) {
    if (arr[i] > max.val) {
        max = {val: arr[i], pos: i};
    }
}
arr[max.pos] = 1;
print(arr.sort(function(a, b){return a - b}).join(' '));

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

//134B
var n = readline();
var arr = getNums();
var max = {val: arr[0], pos: 0};
for (var i = 1; i < n; i++) {
    if (arr[i] > max.val) {
        max = {val: arr[i], pos: i};
    }
}
arr[max.pos] = 1;
print(arr.sort(function(a, b){return a - b}).join(' '));


"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

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

function main() {
  const testCases = readline();
  for (let i = 0; i < testCases; i++) {
    const length = readline();
    const arr = readline().split(" ");
    arr.sort((a, b) => a - b);
    const result =
      parseInt(arr[length - 1] - arr[0]) + parseInt(arr[length - 2] - arr[1]);
    console.log(result);
  }
}

/* why are we still here, just to suffer? */
let buf='';

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

process.stdin.on('end', ()=>{
    let lines=buf.split('\n');
    let lc=0;
    let t=parseInt(lines[lc++]);
    while(t--) {
        let n=parseInt(lines[lc++]);
        let _=lines[lc++].split(' ');
        let a=[];
        for(let i=0;i<n;i++) {
            a.push(parseInt(_[i]));
        }
        let max1=0,max2=0,min1=parseInt(1e9+7),min2=min1;
        for(let i=0;i<n;i++) {
            if(a[i]>=max1) {
                max2=max1; max1=a[i];
            } else if(a[i]>max2) max2=a[i];

            if(a[i]<=min1) {
                min2=min1; min1=a[i];
            } else if(a[i]<min2) min2=a[i];
        }

        console.log(max1+max2-min1-min2);
    }
});

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		list.sort(function(a,b){
			return a - b;
		});
		var output = list[N - 1] + list[N - 2] - list[1] - list[0];
		myout(output);
	}
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var k = lines[i].split(' ').map(Number).sort(function(a, b){return a - b});
            var a = k[k.length - 1] + k[k.length - 2];
            var b = k[0] + k[1];
            a -= b;
            console.log(a);
        }
    }
});

'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++) {
        readline();
        const arr = readline().split(' ').map(Number);

        let min1 = Infinity;
        let min2 = Infinity;
        let max1 = -1;
        let max2 = -1;

        for (let i = 0; i < arr.length; i++) {
            if (arr[i] < min1) {
                min2 = min1;
                min1 = arr[i];
            } else if (arr[i] < min2) {
                min2 = arr[i];
            }
            if (arr[i] > max1) {
                max2 = max1;
                max1 = arr[i];
            } else if (arr[i] > max2) {
                max2 = arr[i];
            }
        }
        output(max1 + max2 - min1 - min2);
    }
}

// max max min min
// min max min max
// max min min max
//
//
//

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

function main() {
    const t = +readLine();
    for(let i = 0; i < t; i++){
        const n = +readLine();
        const arr = readLine().split(' ').map(p => +p);
        let result = myFunc(arr);
        console.log(result);
    }
}

function myFunc(arr){

    const n = arr.length;
    arr.sort((a, b) => a - b);

    return arr[n-1] + arr[n-2] - arr[1] - arr[0];

}

var n, a;
    var tests = parseInt(readline());
    for (var t=0; t<tests;t++) {
        n = parseInt(readline());
        a = readline().split(' ').map(x=>parseInt(x));
        a.sort((x, y) => x-y);
        print(a[n-1] + a[n-2] - a[0] - a[1])
    }

const fs = require("fs");

const input = fs.readFileSync(0, "utf8").trim().split("\n");

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const n = parseInt(input[index]);
    index++;
    const a = input[index].split(" ").map((item) => parseInt(item));
    const testCase = {
      n,
      a,
    };
    testCases.push(testCase);
  }
}

const attempt = (a, n) => {
  let leftMin = Infinity;
  let leftMax = -Infinity;
  const leftMins = [];
  const leftMaxs = [];
  for (let i = 0; i < n; i++) {
    const v = a[i];
    if (v < leftMin) leftMin = v;
    if (v > leftMax) leftMax = v;
    leftMins.push(leftMin);
    leftMaxs.push(leftMax);
  }
  let rightMin = Infinity;
  let rightMax = -Infinity;
  const rightMins = [];
  const rightMaxs = [];
  for (let i = n - 1; i >= 0; i--) {
    const v = a[i];
    if (v < rightMin) rightMin = v;
    if (v > rightMax) rightMax = v;
    rightMins.unshift(rightMin);
    rightMaxs.unshift(rightMax);
  }

  const leftDiffs = leftMaxs.map((m, i) => m - leftMins[i]);
  const rightDiffs = rightMaxs.map((m, i) => m - rightMins[i]);
  // console.log(leftMins);
  // console.log(leftMaxs);
  // console.log(leftDiffs);
  // console.log(rightMins);
  // console.log(rightMaxs);
  // console.log(rightDiffs);

  let result = 0;
  for (let i = 0; i < n - 1; i++) {
    const v = leftDiffs[i] + rightDiffs[i + 1];
    if (v > result) result = v;
  }
  return result;
};

function solution(testCase) {
  let { n, a } = testCase;

  a.sort((b, c) => b - c);
  console.log(a[a.length - 1] + a[a.length - 2] - a[1] - a[0]);
}

parseInput();

testCases.forEach(solution);

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

function main() {
  const length = readline()
  const arr = readline().split(' ')
  arr.sort((a, b) => a - b)
  const result = parseInt(arr[length - 1] - arr[0]) + parseInt(arr[length - 2] - arr[1])
  console.log(result)
}

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

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

// Main Function, write code here

function main() {
    const length = readline()
  const arr = readline().split(' ')
  arr.sort((a, b) => a - b)
  const result = parseInt(arr[length - 1] - arr[0]) + parseInt(arr[length - 2] - arr[1])
  console.log(result)
}

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

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

function main() {
    const length = readline()
  const arr = readline().split(' ')
  arr.sort()
  const result = parseInt(arr[length - 1] - arr[0]) + parseInt(arr[length - 2] - arr[1])
  return result
}

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

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

// Main Function, write code here

function main() {
    const length = readline()
  const arr = readline().split(' ')
  arr.sort()
  const result = arr[length - 1] - arr[0] + arr[length - 2] - arr[1]
  return result
}

const fs = require("fs");

const input = fs.readFileSync(0, "utf8").trim().split("\n");

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const n = parseInt(input[index]);
    index++;
    const a = input[index].split(" ").map((item) => parseInt(item));
    const testCase = {
      n,
      a,
    };
    testCases.push(testCase);
  }
}

const attempt = (a, n) => {
  let leftMin = Infinity;
  let leftMax = -Infinity;
  const leftMins = [];
  const leftMaxs = [];
  for (let i = 0; i < n; i++) {
    const v = a[i];
    if (v < leftMin) leftMin = v;
    if (v > leftMax) leftMax = v;
    leftMins.push(leftMin);
    leftMaxs.push(leftMax);
  }
  let rightMin = Infinity;
  let rightMax = -Infinity;
  const rightMins = [];
  const rightMaxs = [];
  for (let i = n - 1; i >= 0; i--) {
    const v = a[i];
    if (v < rightMin) rightMin = v;
    if (v > rightMax) rightMax = v;
    rightMins.unshift(rightMin);
    rightMaxs.unshift(rightMax);
  }

  const leftDiffs = leftMaxs.map((m, i) => m - leftMins[i]);
  const rightDiffs = rightMaxs.map((m, i) => m - rightMins[i]);
  // console.log(leftMins);
  // console.log(leftMaxs);
  // console.log(leftDiffs);
  // console.log(rightMins);
  // console.log(rightMaxs);
  // console.log(rightDiffs);

  let result = 0;
  for (let i = 0; i < n - 1; i++) {
    const v = leftDiffs[i] + rightDiffs[i + 1];
    if (v > result) result = v;
  }
  return result;
};

function solution(testCase) {
  let { n, a } = testCase;
  // console.log(n, a);

  let maxi = -Infinity;
  let maxiIndex;
  let mini = Infinity;
  let miniIndex;
  a.forEach((v, i) => {
    if (v > maxi) {
      maxi = v;
      maxiIndex = i;
    }
    if (v < mini) {
      mini = v;
      miniIndex = i;
    }
  });

  let startWithMax = [...a];
  const toPushStartWithMax = startWithMax.splice(0, maxiIndex);
  startWithMax.push(...toPushStartWithMax);

  const resultStartWithMax = attempt(startWithMax, n);

  let endWithMax = [...a];
  const toPushEndWithMax = endWithMax.splice(maxiIndex + 1);
  endWithMax.push(...toPushEndWithMax);

  const resultEndWithMax = attempt(endWithMax, n);

  let startWithMin = [...a];
  const toPushStartWithMin = startWithMin.splice(0, miniIndex);
  startWithMin.push(...toPushStartWithMin);

  const resultStartWithMin = attempt(startWithMin, n);

  let endWithMin = [...a];
  const toPushEndWithMin = endWithMin.splice(miniIndex + 1);
  endWithMin.push(...toPushEndWithMin);

  const resultEndWithMin = attempt(endWithMin, n);

  // console.log(a);

  console.log(
    Math.max(
      resultStartWithMax,
      resultEndWithMax,
      resultStartWithMin,
      resultEndWithMin
    )
  );
  // console.log("--------");
}

parseInput();

testCases.forEach(solution);

const fs = require("fs");

const input = fs.readFileSync(0, "utf8").trim().split("\n");

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const n = parseInt(input[index]);
    index++;
    const a = input[index].split(" ").map((item) => parseInt(item));
    const testCase = {
      n,
      a,
    };
    testCases.push(testCase);
  }
}

const attempt = (a, n) => {
  let leftMin = Infinity;
  let leftMax = -Infinity;
  const leftMins = [];
  const leftMaxs = [];
  for (let i = 0; i < n; i++) {
    const v = a[i];
    if (v < leftMin) leftMin = v;
    if (v > leftMax) leftMax = v;
    leftMins.push(leftMin);
    leftMaxs.push(leftMax);
  }
  let rightMin = Infinity;
  let rightMax = -Infinity;
  const rightMins = [];
  const rightMaxs = [];
  for (let i = n - 1; i >= 0; i--) {
    const v = a[i];
    if (v < rightMin) rightMin = v;
    if (v > rightMax) rightMax = v;
    rightMins.unshift(rightMin);
    rightMaxs.unshift(rightMax);
  }

  const leftDiffs = leftMaxs.map((m, i) => m - leftMins[i]);
  const rightDiffs = rightMaxs.map((m, i) => m - rightMins[i]);
  // console.log(leftMins);
  // console.log(leftMaxs);
  // console.log(leftDiffs);
  // console.log(rightMins);
  // console.log(rightMaxs);
  // console.log(rightDiffs);

  let result = 0;
  for (let i = 0; i < n - 1; i++) {
    const v = leftDiffs[i] + rightDiffs[i + 1];
    if (v > result) result = v;
  }
  return result;
};

function solution(testCase) {
  let { n, a } = testCase;
  // console.log(n, a);

  let maxi = -Infinity;
  let maxiIndex;
  let mini = Infinity;
  let miniIndex;
  a.forEach((v, i) => {
    if (v > maxi) {
      maxi = v;
      maxiIndex = i;
    }
    if (v < mini) {
      mini = v;
      miniIndex = i;
    }
  });

  let startWithMax = [...a];
  const toPushStartWithMax = startWithMax.splice(0, maxiIndex);
  startWithMax.push(...toPushStartWithMax);

  const resultStartWithMax = attempt(startWithMax, n);

  let endWithMax = [...a];
  const toPushEndWithMax = endWithMax.splice(maxiIndex + 1);
  endWithMax.push(...toPushEndWithMax);

  const resultEndWithMax = attempt(endWithMax, n);

  // console.log(a);

  console.log(Math.max(resultStartWithMax, resultEndWithMax));
  // console.log("--------");
}

parseInput();

testCases.forEach(solution);

const fs = require("fs");

const input = fs.readFileSync(0, "utf8").trim().split("\n");

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const n = parseInt(input[index]);
    index++;
    const a = input[index].split(" ").map((item) => parseInt(item));
    const testCase = {
      n,
      a,
    };
    testCases.push(testCase);
  }
}

function solution(testCase) {
  let { n, a } = testCase;
  // console.log(n, a);

  let maxi = -Infinity;
  let maxiIndex;
  a.forEach((v, i) => {
    if (v > maxi) {
      maxi = v;
      maxiIndex = i;
    }
  });

  const toPush = a.splice(0, maxiIndex);
  a.push(...toPush);

  // console.log(a);

  let leftMin = Infinity;
  let leftMax = -Infinity;
  const leftMins = [];
  const leftMaxs = [];
  for (let i = 0; i < n; i++) {
    const v = a[i];
    if (v < leftMin) leftMin = v;
    if (v > leftMax) leftMax = v;
    leftMins.push(leftMin);
    leftMaxs.push(leftMax);
  }
  let rightMin = Infinity;
  let rightMax = -Infinity;
  const rightMins = [];
  const rightMaxs = [];
  for (let i = n - 1; i >= 0; i--) {
    const v = a[i];
    if (v < rightMin) rightMin = v;
    if (v > rightMax) rightMax = v;
    rightMins.unshift(rightMin);
    rightMaxs.unshift(rightMax);
  }

  const leftDiffs = leftMaxs.map((m, i) => m - leftMins[i]);
  const rightDiffs = rightMaxs.map((m, i) => m - rightMins[i]);
  // console.log(leftMins);
  // console.log(leftMaxs);
  // console.log(leftDiffs);
  // console.log(rightMins);
  // console.log(rightMaxs);
  // console.log(rightDiffs);

  let result = 0;
  for (let i = 0; i < n - 1; i++) {
    const v = leftDiffs[i] + rightDiffs[i + 1];
    if (v > result) result = v;
  }
  console.log(result);
  // console.log("--------");
}

parseInput();

testCases.forEach(solution);


;(function () {

	print(function () {
		var n = +readline(), m = {}, r = 0;
		readline().split(' ').forEach(function (e) { m[e] = m[e] ? m[e] + 1 : 1; });

		for (var k in m)
			if (m[k] > 1)
				r += Math.floor(m[k] / 2);

		return Math.floor(r / 2);
	}());

}).call(this);

print(function(n, a) {
	var i, sum = 0,
		cnt = new Int32Array(105);

	for (i = 0; i < n; i++)
		++cnt[a[i]];

	for (i = 0; i < 105; i++)
		sum += cnt[i] >> 1;

	return sum >> 1;

}(+readline(), readline().split(' ').map(Number)));


function input() {
  return [
    parseInt(readline().trim()),
    readline()
      .trim()
      .split(" ")
      .map(function(i) {
        return parseInt(i);
      })
  ];
}

function main() {
  // get input
  var read = input();
  var n = read[0];
  var values = read[1];

  var negative = Infinity;
  var positive = 0;

  values.forEach(function(v) {
    var _negative = negative,
      _positive = positive;
    positive = Math.min(
      _negative + Math.abs(v + 1),
      _positive + Math.abs(v - 1)
    );
    negative = Math.min(
      _negative + Math.abs(v - 1),
      _positive + Math.abs(v + 1)
    );
  });

  print(positive);
}

main();

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

let c = 0;

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

  let ans = 0;
  let minus = 0;
  let hasZero = false;
  const arr = d.split(" ").map(Number);
  arr.sort((a, b) => a - b);

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < 0) {
      ans += Math.abs(arr[i] + 1);
      minus++;
    } else {
      if (arr[i] === 0) {
        hasZero = true;
      }
      ans += Math.abs(arr[i] - 1);
    }
  }

  if (minus % 2 !== 0 && !hasZero) {
    ans += 2;
  }

  console.log(ans);
  c++;
});

function doStuff (data) {
    var x = data.split(' ');

    var solutionNrs = [];
    var coins = 0;
    var zeroPresent = false;
    for (var i = 0; i < numbers; i++) {
        var cur = x[i];
        if (cur == 0) {
            cur++;
            zeroPresent = true;
            solutionNrs.push(1);
        } else if (cur < 0) {
            cur *= -1;
            cur--;
            solutionNrs.push(-1);
        } else if (cur > 0) {
            cur--;
            solutionNrs.push(1);
        }
        coins += cur;
    }
    var endNrLogic = 1;
    solutionNrs.forEach( function (y) {
        endNrLogic *= y;
    });
    if (endNrLogic == 0) {
        coins += 2;
    } else if (endNrLogic == -1 && zeroPresent) {
        // coins--;
    } else if (endNrLogic == -1 && !zeroPresent) {
        coins += 2;
    }
    console.log(coins);
};
var numbers;
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*/
    numbers = lines[0];
    doStuff(lines[1]);
});

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {"use strict";
    // TODO
    var n = rdN();
    var A = rdArN();
    var res = 0;
    var sign = 1;
    var zC = 0;
    for (var i = 0; i < n; ++i) {
        if (A[i] > 0) {
            res += A[i] - 1;
        } else if (A[i] < 0) {
            res += -A[i] - 1;
            sign *= -1;
        } else {
            ++zC;
        }
    }
    if (zC > 0) {
        res += zC;
    } else {
        if (sign === -1) {
            res += 2;
        }
    }
    wr(res);
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
getPrimeFactors=function(n){var primes=getPrimes(Math.floor(Math.sqrt(n))),last=primes.push(n)-1,factors=[],i,p;for(i=0,p=primes[0];primes[last]>1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});

main();
return OUTPUT;
})();

var a = parseInt(readline().trim());var answ = 0;var numbers = readline().trim().split(" ").map(function(x) { return parseInt(x); });var cnt = 0, cn = 0;for(var i = 0; i < numbers.length; i++){answ += Math.abs(numbers[i]);answ--;if(numbers[i]===0){answ++;cnt++;}if(numbers[i] < 0){cn++}}if(cn % 2 === 1 && cnt === 0)answ += 2;else answ += cnt;print(answ);

process.stdin.resume();
process.stdin.setEncoding('utf8');

let input_stdin = "";
let input = "";
let input_currentline = 0;

function readLine() {
    return input[input_currentline++];
}

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

process.stdin.on('end', function () {
    input = input_stdin.split("\n");
    main();
});

// your code goes here
function main() {
    const N = Number(readLine());
    const n = readLine().split(' ').map(x=>+x);

    let ans = 0
    let minus1 = 0;
    let numZeros = 0;
    for (let i = 0; i < N; i ++) {
        let toMinus1 = Math.abs(n[i] + 1);
        let toPlus1 = Math.abs(n[i] - 1)
        ans += Math.min(toMinus1, toPlus1);
        if (toMinus1 < toPlus1) minus1++;
        if (n[i] === 0) numZeros++;
    }
    console.log(minus1%2 === 1 && numZeros === 0 ? ans + 2 : ans);
}

const processData = (lines) => {
debugger
  const [n, a] = lines

  const A = a.split(' ').map(n => Number(n))

  let coins = 0
  let sign = 1
  let closeTo = 2
  for (let i = 0; i < A.length; i++) {
    const el = A[i]
    if (el >= 1) coins += el - 1
    if (el <= -1) coins += Math.abs(el) - 1
    if (el === 0) {
      coins += 1
      closeTo = 0
    }
    sign = sign * (Math.sign(el) === 0 ? 1 : Math.sign(el))
  }
  if (sign < 0) {
    coins += closeTo
  }

  console.log(coins)
}

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 input() {
  return [
    parseInt(readline().trim()),
    readline()
      .trim()
      .split(" ")
      .map(function(i) {
        return parseInt(i);
      })
  ];
}

function main() {
  // get input
  var read = input();
  var n = read[0];
  var values = read[1];

  var negative = 0;
  var positive = 0;

  values.forEach(function(v) {
    var _negative = negative,
      _positive = positive;
    positive = Math.min(
      _negative + Math.abs(v + 1),
      _positive + Math.abs(v - 1)
    );
    negative = Math.min(
      _negative + Math.abs(v - 1),
      _positive + Math.abs(v + 1)
    );
  });

  print(positive);
}

main();

var a = parseInt(readline().trim());var answ = 0;
var numbers = readline().trim().split(" ").map(function(x) { return parseInt(x); });var cnt = 0, cn = 0;
for(var i = 0; i < numbers.length; i++){answ += Math.abs(numbers[i]);answ--;if(numbers[i]===0){answ++;cnt++;}if(numbers[i] < 0){cn++}}
if(cn % 2 === 1 && cnt === 0)answ += 2;
else answ += cn + cnt;
print(answ);

function doStuff (data) {
    var x = data.split(' ');

    var solutionNrs = [];
    var coins = 0;
    var zeroPresent = false;
    for (var i = 0; i < x.nr; i++) {
        var cur = x.numbers[i];
        if (cur == 0) {
            cur++;
            zeroPresent = true;
            solutionNrs.push(1);
        } else if (cur < 0) {
            cur *= -1;
            cur--;
            solutionNrs.push(-1);
        } else if (cur > 0) {
            cur--;
            solutionNrs.push(1);
        }
        coins += cur;
    }
    var endNrLogic = 1;
    solutionNrs.forEach( function (y) {
        endNrLogic *= y;
    });
    if (endNrLogic == 0) {
        coins += 2;
    } else if (endNrLogic == -1 && zeroPresent) {
        coins--;
    } else if (endNrLogic == -1 && !zeroPresent) {
        coins += 2;
    }
    console.log(coins);
};
var numbers;
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*/
    numbers = lines[0];
    doStuff(lines[1]);
});

function doStuff (data) {
    var x = data.split(' ');

    var solutionNrs = [];
    var coins = 0;
    var zeroPresent = false;
    for (var i = 0; i < numbers; i++) {
        var cur = x[i];
        if (cur == 0) {
            cur++;
            zeroPresent = true;
            solutionNrs.push(1);
        } else if (cur < 0) {
            cur *= -1;
            cur--;
            solutionNrs.push(-1);
        } else if (cur > 0) {
            cur--;
            solutionNrs.push(1);
        }
        coins += cur;
    }
    var endNrLogic = 1;
    solutionNrs.forEach( function (y) {
        endNrLogic *= y;
    });
    if (endNrLogic == 0) {
        coins += 2;
    } else if (endNrLogic == -1 && zeroPresent) {
        coins--;
    } else if (endNrLogic == -1 && !zeroPresent) {
        coins += 2;
    }
    console.log(coins);
};
var numbers;
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*/
    numbers = lines[0];
    doStuff(lines[1]);
});

function doStuff (data) {
    var x = data.split(' ');

    var solutionNrs = [];
    var coins = 0;
    var zeroPresent = false;
    for (var i = 0; i < x.nr; i++) {
        var cur = x.numbers[i];
        if (cur == 0) {
            cur++;
            zeroPresent = true;
            solutionNrs.push(1);
        } else if (cur < 0) {
            cur *= -1;
            cur--;
            solutionNrs.push(-1);
        } else if (cur > 0) {
            cur--;
            solutionNrs.push(1);
        }
        coins += cur;
    }
    var endNrLogic = 1;
    solutionNrs.forEach( function (y) {
        endNrLogic *= y;
    });
    if (endNrLogic == 0) {
        coins += 2;
    } else if (endNrLogic == -1 && zeroPresent) {
        coins--;
    } else if (endNrLogic == -1 && !zeroPresent) {
        coins += 2;
    }
    console.log(coins);
};

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*/
    doStuff(lines[0]);
});

function doStuff (x) {
    var solutionNrs = [];
    var coins = 0;
    var zeroPresent = false;
    for (var i = 0; i < x.nr; i++) {
        var cur = x.numbers[i];
        if (cur == 0) {
            cur++;
            zeroPresent = true;
            solutionNrs.push(1);
        } else if (cur < 0) {
            cur *= -1;
            cur--;
            solutionNrs.push(-1);
        } else if (cur > 0) {
            cur--;
            solutionNrs.push(1);
        }
        coins += cur;
    }
    var endNrLogic = 1;
    solutionNrs.forEach( function (y) {
        endNrLogic *= y;
    });
    if (endNrLogic == 0) {
        coins += 2;
    } else if (endNrLogic == -1 && zeroPresent) {
        coins--;
    } else if (endNrLogic == -1 && !zeroPresent) {
        coins += 2;
    }
    console.log(coins);
};

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*/
    doStuff(lines[0]);
});

process.stdin.resume();
process.stdin.setEncoding('utf8');

let input_stdin = "";
let input = "";
let input_currentline = 0;

function readLine() {
    return input[input_currentline++];
}

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

process.stdin.on('end', function () {
    input = input_stdin.split("\n");
    main();
});

// your code goes here
function main() {
    const N = Number(readLine());
    const n = readLine().split(' ').map(x=>+x);

    let memo = [];

    const getCoins = (arr, res) => {
        if (arr.length===1) {
            return res === 1 ? Math.abs(arr[0] - 1) : Math.abs(arr[0] + 1);
        }
        if (memo.findIndex(x => x.id === arr.join("-") && x.res === res) != -1) {
            return memo.find(x => x.id === arr.join("-") && x.res === res).val;
        }
        let v = Math.min(getCoins(arr.slice(1), 1) + Math.abs(arr[0] - 1), getCoins(arr.slice(1), -1) + Math.abs(arr[0] + 1));
        memo.push({id:arr.join("-"), res: res, val: v});
        return v;
    }

    console.log(getCoins(n, 1));

}

process.stdin.resume();
process.stdin.setEncoding('utf8');

let input_stdin = "";
let input = "";
let input_currentline = 0;

function readLine() {
    return input[input_currentline++];
}

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

process.stdin.on('end', function () {
    input = input_stdin.split("\n");
    main();
});

// your code goes here
function main() {
    const N = Number(readLine());
    const n = readLine().split(' ').map(x=>+x);

    let ans = 0
    let minus1 = 0;
    for (let i = 0; i < N; i ++) {
        let toMinus1 = Math.abs(n[i] + 1);
        let toPlus1 = Math.abs(n[i] - 1)
        ans += Math.min(toMinus1, toPlus1);
        if (toMinus1 < toPlus1) minus1++;
    }
    console.log(minus1%2 === 0 ? ans : ans + 2);
}

process.stdin.resume();
process.stdin.setEncoding('utf8');

let input_stdin = "";
let input = "";
let input_currentline = 0;

function readLine() {
    return input[input_currentline++];
}

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

process.stdin.on('end', function () {
    input = input_stdin.split("\n");
    main();
});

// your code goes here
function main() {
    const N = Number(readLine());
    const n = readLine().split(' ').map(x=>+x);

    let memo = [];

    const getCoins = (arr, res) => {
        if (arr.length===1) {
            return res === 1 ? Math.abs(arr - 1) : Math.abs(arr + 1);
        }
        if (memo.findIndex(x => x.id === arr.join("-")) != -1) {
            return memo.find(x => x.id === arr.join("-")).val;
        }
        let v = Math.min(getCoins(arr.slice(1), 1) + Math.abs(arr[0] - 1), getCoins(arr.slice(1), -1) + Math.abs(arr[0] + 1));
        memo.push({id:arr.join("-"), val: v});
        return v;
    }

    console.log(getCoins(n, 1));

}

const processData = (lines) => {
  const [n, a] = lines

  const A = a.split(' ').map(n => Number(n))

  let coins = 0
  let sign = 1
  // let closeTo1 = 1
  for (let i = 0; i < A.length; i++) {
    if (A[i] > 1) coins += A[i] - 1
    if (A[i] < -1) coins += Math.abs(A[i]) - 1
    // if (Math.abs(A[i] - 1) < Math.abs(A[closeTo1] - 1)) closeTo1 = i
    sign = sign * Math.sign(A[i])
  }
  if (sign < 0) coins -= 2

  console.log(coins)
}

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 processData = (lines) => {
  const [n, a] = lines

  const A = a.split(' ').map(n => Number(n))

  let coins = 0
  let sign = 1
  let closeTo = 2
  for (let i = 0; i < A.length; i++) {
    if (A[i] >= 1) coins += A[i] - 1
    if (A[i] <= -1) coins += Math.abs(A[i]) - 1
    if (A[i] === 0) {
      coins += 1
      closeTo = 0
    }
    sign = sign * Math.sign(A[i]) === 0 ? 1 : Math.sign(A[i])
  }
  if (sign < 0) {
    coins += closeTo
  }

  console.log(coins)
}

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 processData = (lines) => {
  const [n, a] = lines

  const A = a.split(' ').map(n => Number(n))

  let coins = 0
  let sign = 1
  // let closeTo1 = 1
  for (let i = 0; i < A.length; i++) {
    if (A[i] > 1) coins += A[i] - 1
    if (A[i] < -1) coins += Math.abs(A[i]) - 1
    // if (Math.abs(A[i] - 1) < Math.abs(A[closeTo1] - 1)) closeTo1 = i
    sign = sign * Math.sign(A[i])
  }
  if (sign < 0) coins += 2

  console.log(coins)
}

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 processData = (lines) => {
  const [n, a] = lines

  const A = a.split(' ').map(n => Number(n))

  let coins = 0
  let sign = 1
  let closeTo1 = 1
  for (let i = 0; i < A.length; i++) {
    if (A[i] >= 1) coins += A[i] - 1
    if (A[i] <= -1) coins += Math.abs(A[i]) - 1
    if (A[i] === 0) coins += 1
    if (Math.abs(A[i] - 1) < Math.abs(A[closeTo1] - 1)) closeTo1 = i
    sign = sign * Math.sign(A[i])
  }
  if (sign < 0) {
    if (A[closeTo1] <= -1) {
      coins += 2
    }
    if (A[closeTo1] >= 1) {
      coins += 2
    }
    // if (A[closeTo1] === 0) {
    //
    // }
  }

  console.log(coins)
}

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


'use strict';

var readline = require('readline');

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

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

function solve(x, d) {
  let count = 0;
  while (x % d === 0) {
    count++;
    x /= d;
  }
  if (count < 2) {
    console.log('NO');
    return;
  }
  for (let i = 2; i <= x / i; i++) {
    if (x % i === 0) {
      console.log('YES');
      return;
    }
  }
  if (count > 2) {
    for (let i = 2; i <= d / i; i++) {
      if (d % i === 0) {
        if (i === d / i) {
          if (i !== x) {
            console.log('YES');
            return;
          } else if (count > 3) {
            console.log('YES');
            return;
          }
        } else {
          console.log('YES');
          return;
        }
      }
    }
  }
  console.log('NO');
}

async function main(read) {
  const t = Number(await read());
  for (let i = 0; i < t; i++) {
    const [x, d] = (await read()).split(' ').map(Number);
    solve(x, d);
  }
}

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

function solve() {
   const [x, d] = readArray(Number);
   const count = countBeatyMul(x, d, 1);
   write(count > 1 ? 'YES' : 'NO');
}

function countBeatyMul(x, d, start) {
   if (x % d !== 0) {
      return 0;
   }
   if (isBeaty(x, d)) {
      return 1;
   }
   let ans = 0;
   for (let i = start; i <= Math.floor(Math.sqrt(x)); i++) {
      if (x % i !== 0) {
         continue;
      }
      const xDivI = Math.floor(x / i);
      if (xDivI < start) {
         continue;
      }
      if (isBeaty(i, d)) {
         ans += countBeatyMul(xDivI, d, i)
      }
   }
   return ans;
}

function isBeaty(x, d) {
   return x % d === 0 && x % (d * d) !== 0;
}

function init() {
   try {
      var T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e + e.stack);
   }
}

function modPow(a, n, mod) {
   let d = a;
   let curN = n;
   let ans = 1n;
   while(curN) {
      if (curN & 1n) {
         ans = modMul(ans, d, mod);
      }
      curN >>= 1n;
      d = modMul(d, d, mod);
   }
   return ans;
}

function modMul(a, b, mod) {
   return (a * b) % mod;
}

function modSum(a, b, mod) {
   return (a + b) % mod;
}

function modDiff(a, b, mod) {
   return (a + mod - b) % mod;
}

function isZero(num) {
   if (typeof num === 'bigint') {
      return num === 0n;
   }
   return num === 0;
}
function div(a, b) {
   if (typeof a !== typeof b) {
      throw new Error('Different types on division');
   }
   if (typeof a === 'bigint') {
      return a / b;
   }
   return Math.floor(a / b);
}

function gcd(x, y) {
   if (isZero(y)) {
      return x;
   }
   return gcd(y, x % y);
}

function lcm(x, y) {
   return div(x * y, gcd(x, y));
}

function allIndexOf(arr, value) {
   var index = arr.indexOf(value)
   var ans = [];
   while (index !== -1) {
      ans.push(index);
      index = arr.indexOf(value, index + 1);
   }
   return ans;
}

function xor(a, b, k) {
   if (k === 2) {
      return a ^ b;
   }
}

function decToBin(num) {
   let n = num;
   const ans = [];
   while(n > 0) {
      ans.push(n & 1);
      n = (n >> 1);
   }
   return ans;
}

function binToDec(binN) {
   let ans = 0;
   for (let i = binN.length - 1; i >= 0; i--) {
      ans = ((ans << 1) | binN[i]);
   }
   return ans;
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');

   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

'use strict';

var readline = require('readline');

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

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

function solve(x, d) {
  let count = 0;
  while (x % d === 0) {
    count++;
    x /= d;
  }
  if (count < 2) {
    console.log('NO');
    return;
  }
  for (let i = 2; i <= x / i; i++) {
    if (x % i === 0) {
      console.log('YES');
      return;
    }
  }
  if (count > 2) {
    for (let i = 2; i <= d / i; i++) {
      if (d % i === 0) {
        if (i === d / i) {
          if (i !== x) {
            console.log('YES');
            return;
          }
        } else {
          console.log('YES');
          return;
        }
      }
    }
  }
  console.log('NO');
}

async function main(read) {
  const t = Number(await read());
  for (let i = 0; i < t; i++) {
    const [x, d] = (await read()).split(' ').map(Number);
    solve(x, d);
  }
}

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

'use strict';

var readline = require('readline');

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

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

function solve(x, d) {
  let count = 0;
  while (x % d === 0) {
    count++;
    x /= d;
  }
  if (count < 2) {
    console.log('NO');
    return;
  }
  for (let i = 2; i <= x / i; i++) {
    if (x % i === 0) {
      console.log('YES');
      return;
    }
  }
  if (count > 2) {
    for (let i = 2; i <= d / i; i++) {
      if (count > 3) {
        if (d % i === 0) {
          console.log('YES');
          return;
        }
      } else {
        if (d % i === 0 && i !== x && d / i !== x) {
          console.log('YES');
          return;
        }
      }
    }
  }
  console.log('NO');
}

async function main(read) {
  const t = Number(await read());
  for (let i = 0; i < t; i++) {
    const [x, d] = (await read()).split(' ').map(Number);
    solve(x, d);
  }
}

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

'use strict';

var readline = require('readline');

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

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

function solve(x, d) {
  let count = 0;
  while (x % d === 0) {
    count++;
    x /= d;
  }
  if (count < 2) {
    console.log('NO');
    return;
  }
  for (let i = 2; i <= x / i; i++) {
    if (x % i === 0) {
      console.log('YES');
      return;
    }
  }
  if (count > 2) {
    for (let i = 2; i <= d / i; i++) {
      if (count > 3) {
        if (d % i === 0) {
          console.log('YES');
          return;
        }
      } else {
        if (i !== x && d / i !== x) {
          console.log('YES');
          return;
        }
      }
    }
  }
  console.log('NO');
}

async function main(read) {
  const t = Number(await read());
  for (let i = 0; i < t; i++) {
    const [x, d] = (await read()).split(' ').map(Number);
    solve(x, d);
  }
}

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

'use strict';

var readline = require('readline');

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

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

function solve(x, d) {
  let count = 0;
  while (x % d === 0) {
    count++;
    x /= d;
  }
  if (count < 2) {
    console.log('NO');
    return;
  }
  for (let i = 2; i <= x / i; i++) {
    if (x % i === 0) {
      console.log('YES');
      return;
    }
  }
  if (count > 2) {
    for (let i = 2; i <= d / i; i++) {
      if (d % i === 0 && i !== x && d / i !== x) {
        console.log('YES');
        return;
      }
    }
  }
  console.log('NO');
}

async function main(read) {
  const t = Number(await read());
  for (let i = 0; i < t; i++) {
    const [x, d] = (await read()).split(' ').map(Number);
    solve(x, d);
  }
}

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


//import { readline, print } from '@ip-algorithmics/codeforces-io';
var t = +readline();
var _loop_1 = function () {
    readline();
    var a = readline().split(' ').map(function (v) { return +v; });
    var b = readline().split(' ').map(function (v) { return +v; });
    var A = a.map(function (_, i) { return [a[i], b[i]]; });
    A.sort(function (a, b) { return a[0] - b[0]; });
    var count = 0;
    var i = 0;
    while (i < A.length) {
        var temp = i;
        while (A[i][0]) {
            A[i][0] = 0;
            i = A[i][1] - 1;
            count++;
        }
        count -= (count % 2);
        i = temp + 1;
    }
    print(count * (a.length - (count >> 1)));
};
while (t-- > 0) {
    _loop_1();
}

'use strict';

var readline = require('readline');

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

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

function solve(n, a, b) {
  a = a.map(num => num - 1);
  b = b.map(num => num - 1);
  const p = [...new Array(n).keys()];
  const count = new Array(n).fill(1);
  const find = i => {
    if (p[i] !== i) p[i] = find(p[p[i]]);
    return p[i];
  };
  const union = (i, j) => {
    const ri = find(i),
          rj = find(j);
    if (ri !== rj) {
      p[rj] = ri;
      count[ri] += count[rj];
    }
  };
  for (let i = 0; i < n; i++) {
    if (a[i] !== b[i]) union(a[i], b[i]);
  }
  const roots = new Set();
  for (let i = 0; i < n; i++) {
    roots.add(find(i));
  }
  let res = 0,
      l = 1,
      r = n;
  for (let i of roots) {
    let c = count[i];
    if (c === 1) continue;
    if (c & 1) c = c - 1;
    let nums = new Array(c).fill(0);
    for (let i = 0, j = c - 1; i < j; i++, j--) {
      if (i & 1) {
        nums[i] = r--;
        nums[j] = l++;
      } else {
        nums[i] = l++;
        nums[j] = r--;
      }
    }
    for (let i = 0; i < c; i++) {
      res += Math.abs(nums[(i + 1) % c] - nums[i]);
    }
  }
  return res;
}

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

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

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

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

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

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

// SOLUTION:
IS_MULTITEST = 1;

let stackRecursion = (fn, init_state)=>{
  let stack = [];
  let rec = (cb, a0, a1, a2)=>{
    let state = Object.assign({}, init_state);
    stack.push([state, cb, a0, a1, a2]);
  };
  return (cb, a0, a1, a2)=>{
    rec(cb, a0, a1, a2);
    while (stack.length){
      let [state, cb, a0, a1, a2] = stack[stack.length-1];
      let added = false;
      fn((cb, a0, a1, a2)=>{
        added = true;
        rec(cb, a0, a1, a2);
      }, state, a0, a1, a2);
      if (!added){
        cb(state);
        stack.pop();
      }
    }
  };
};

const calc = ()=>{
  // READING:
  let [n] = ra();
  let A = ra();
  let B = ra();
  LT({n, A, B});
  // PROCESSING:
  let posB = new Array(n).fill(0);
  for (let i=0; i<n; i++){
    posB[B[i]] = i;
  }
  let visit = new Set();
  let cnt;
  let dfs = stackRecursion((rec, state, v)=>{
    if (visit.has(v)){
      return;
    }
    visit.add(v);
    cnt++;
    rec(()=>{}, posB[A[v]]);
  }, {});
  let c = 0;
  for (let i=0; i<n; i++){
    cnt = 0;
    dfs(()=>{}, i);
    c += cnt>>1;
  }
  return Math.floor((c*(n-c))*2);
};

'use strict';

var readline = require('readline');

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

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

function solve(n, a, b) {
  a = a.map(num => num - 1);
  b = b.map(num => num - 1);
  const p = [...new Array(n).keys()];
  const count = new Array(n).fill(1);
  const find = i => {
    if (p[i] !== i) p[i] = find(p[p[i]]);
    return p[i];
  };
  const union = (i, j) => {
    const ri = find(i),
          rj = find(j);
    if (ri !== rj) {
      p[rj] = ri;
      count[ri] += count[rj];
    }
  };
  for (let i = 0; i < n; i++) {
    if (a[i] !== b[i]) union(a[i], b[i]);
  }
  const roots = new Set();
  for (let i = 0; i < n; i++) {
    roots.add(find(i));
  }
  let res = 0,
      l = 1,
      r = n;
  for (let i of roots) {
    const c = count[i];
    if (c === 1) continue;
    if (c === 2) {
      res += (r - l) * 2;
      r--;
      l--;
      continue;
    }
    res += r - l;
    for (let i = 0; i < (c - 2) / 2; i++) {
      res += (r - l - 1) * 2;
      r--, l++;
    }
    res += r - l;
    r--, l++;
  }
  return res;
}

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

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

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

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

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

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

// SOLUTION:
IS_MULTITEST = 1;

let stackRecursion = (fn, init_state)=>{
  let stack = [];
  let rec = (cb, a0, a1, a2)=>{
    let state = Object.assign({}, init_state);
    stack.push([state, cb, a0, a1, a2]);
  };
  return (cb, a0, a1, a2)=>{
    rec(cb, a0, a1, a2);
    while (stack.length){
      let [state, cb, a0, a1, a2] = stack[stack.length-1];
      let added = false;
      fn((cb, a0, a1, a2)=>{
        added = true;
        rec(cb, a0, a1, a2);
      }, state, a0, a1, a2);
      if (!added){
        cb(state);
        stack.pop();
      }
    }
  };
};

const calc = ()=>{
  // READING:
  let [n] = ra();
  let A = ra();
  let B = ra();
  LT({n, A, B});
  // PROCESSING:
  let posB = new Array(n).fill(0);
  for (let i=0; i<n; i++){
    posB[B[i]] = i;
  }
  let visit = new Set();
  let cnt;
  let dfs = stackRecursion((rec, state, v)=>{
    if (visit.has(v)){
      return;
    }
    visit.add(v);
    cnt++;
    rec(()=>{}, posB[A[v]]);
  }, {});
  let c = 0;
  for (let i=0; i<n; i++){
    cnt = 0;
    dfs(()=>{}, i);
    c += cnt>>1;
  }
  return (c*(n-c))<<1;
};

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

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

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

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

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let [n] = ra();
  let A = ra();
  let B = ra();
  LT({n, A, B});
  // PROCESSING:
  let nums = new Set();
  let posA = new Array(n).fill(0)
  let posB = new Array(n).fill(0)
  for (let i=0; i<n; i++){
    A[i]--;
    posA[A[i]] = i;
    B[i]--;
    posB[B[i]] = i;
    if (A[i]!=B[i]){
      nums.add(A[i])
      nums.add(B[i])
    }
  }
  let arr = Array.from(nums).sort((a, b)=>a-b)
  let l = 0, r = n-1;
  L(arr)
  let ans = 0;
  let i=0;
  let alloc = new Array(n).fill(-1);
  while (i<n){
    let valL = alloc[A[i]];
    let valR = alloc[B[i]];
    if (A[i]==B[i]){
      i++;
     continue;
    }
    if (valL==-1 && valR==-1){
      valL = alloc[A[i]] = l++;
      valR = alloc[B[i]] = r--;
      ans += Math.abs(valR-valL);
    } else if (valL>=0 && valR>=0){
      ans += Math.abs(valL-valR);
    } else {
      if (valL==-1){
        if (Math.abs(l-valR)>Math.abs(r-valR)){
          alloc[A[i]] = l++;

        } else {
          alloc[A[i]] = r--;
        }
      } else {
        if (Math.abs(l-valL)>Math.abs(r-valL)){
          alloc[B[i]] = l++;
        } else {
          alloc[B[i]] = r--;
        }

      }
      ans += Math.abs(alloc[A[i]]-alloc[B[i]]);
    }
    i++;

  }
  return ans;
};


"use strict";
exports.__esModule = true;
function main(rawInput) {
    var lines = rawInput.split("\n");
    var tests = parseInt(lines.shift(), 10);
    for (var i = 0; i < tests; i++) {
        var _a = lines.shift().split(" ").map(function (v) { return parseInt(v); }), busCost = _a[0], tramCost = _a[1], balance = _a[2];
        var stations = lines.shift().trim().split("");
        var res = stations.map(function (v) { return 0; });
        costs(stations, busCost, tramCost, res);
        var j = 0;
        while (j < stations.length && res[j] > balance) {
            j++;
        }
        // console.log(j === stations.length ? j - 1 : j + 1);
        console.log(j + 1);
    }
}
function costs(stations, busCost, tramCost, res) {
    res[stations.length - 1] = 0;
    res[stations.length - 2] = stations[stations.length - 2] === "A" ? busCost : tramCost;
    for (var i = stations.length - 3; i >= 0; i--) {
        if (stations[i] !== stations[i + 1]) {
            res[i] = res[i + 1] + (stations[i] === "A" ? busCost : tramCost);
        }
        else {
            res[i] = res[i + 1];
        }
    }
}
(function () {
    var s = "";
    process.stdin.on("data", function (d) { return s += d; });
    process.stdin.on("end", function () { return main(s); });
})();

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data, ost) {
        let [a, b, p] = data;

        const substr = [];
        const substrInd = [];

        for (let i=0; i<ost.length - 1; i++) {
            if (ost[i] !== ost[i-1]) {
                substr.push(ost[i]);
                substrInd.push(i+1);
            }
        }

        substr.push(ost[ost.length - 1]);
        substrInd.push(ost.length);

        for (let k = substr.length - 2; k >= 0; k--) {
            if (substr[k] === 'B' && p >= b) {
                p = p - b;
            } else if (substr[k] === 'A' && p >= a) {
                p = p - a;
            } else {
                return substrInd[k+1];
            }
        }

        return 1;
    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let data = lines[testCount*2-1].split(" ").map(Number);
        let ost = lines[testCount*2].split("");
        let result = foo(data, ost);
        answer += result +"\n";
        testCount++;
    }
    console.log(answer);
})

function main(rawInput) {
    var lines = rawInput.split("\n");
    var tests = parseInt(lines.shift(), 10);
    for (var i = 0; i < tests; i++) {
        var _a = lines.shift().split(" ").map(function (v) { return parseInt(v); }), busCost = _a[0], tramCost = _a[1], balance = _a[2];
        var stations = lines.shift().split("");
        var j = 0;
        var found = false;
        while (j < stations.length && !found) {
            if (remainingBalance(j, stations, busCost, tramCost, balance) >= 0) {
                found = true;
            }
            else {
                j++;
            }
        }
        console.log(j + 1);
    }
}
var dm = {};
function remainingBalance(pos, stations, busCost, tramCost, balance) {
    if (pos === void 0) { pos = 0; }
    if (balance < 0) {
        dm[pos + "-" + balance] = -1;
        return -1;
    }
    if (pos === stations.length - 1) {
        dm[pos + "-" + balance] = balance;
        return balance;
    }
    var newPos = pos;
    var fst = stations[pos];
    while (stations[newPos] === fst) {
        if (newPos === stations.length) {
            // dm[newPos + "-" + balance] = balance;
            return balance;
        }
        newPos++;
    }
    return remainingBalance(newPos, stations, busCost, tramCost, balance - (fst === "A" ? busCost : tramCost));
}
(function () {
    var s = "";
    process.stdin.on("data", function (d) { return s += d; });
    process.stdin.on("end", function () { return main(s); });
})();

"use strict";
exports.__esModule = true;
function main(rawInput) {
    var lines = rawInput.split("\n");
    var tests = parseInt(lines.shift(), 10);
    for (var i = 0; i < tests; i++) {
        var _a = lines.shift().split(" ").map(function (v) { return parseInt(v); }), busCost = _a[0], tramCost = _a[1], balance = _a[2];
        var stations = lines.shift().split("");
        var res = stations.map(function (v) { return 0; });
        costs(stations, busCost, tramCost, res);
        var j = 0;
        while (j < stations.length - 1 && res[j] > balance) {
            j++;
        }
        // console.log(j === stations.length ? j - 1 : j + 1, balance, busCost, tramCost, res, stations);
        console.log(j + 1);
    }
}
function costs(stations, busCost, tramCost, res) {
    res[stations.length - 1] = 0;
    res[stations.length - 2] = stations[stations.length - 2] === "A" ? busCost : tramCost;
    for (var i = stations.length - 3; i >= 0; i--) {
        if (stations[i] !== stations[i + 1]) {
            res[i] = res[i + 1] + (stations[i] === "A" ? busCost : tramCost);
        }
        else {
            res[i] = res[i + 1];
        }
    }
}
(function () {
    var s = "";
    process.stdin.on("data", function (d) { return s += d; });
    process.stdin.on("end", function () { return main(s); });
})();

"use strict";
exports.__esModule = true;
function main(rawInput) {
    var lines = rawInput.split("\n");
    var tests = parseInt(lines.shift(), 10);
    for (var i = 0; i < tests; i++) {
        var _a = lines.shift().split(" ").map(function (v) { return parseInt(v); }), busCost = _a[0], tramCost = _a[1], balance = _a[2];
        var stations = lines.shift().split("");
        var res = stations.map(function (v) { return 0; });
        costs(stations, busCost, tramCost, res);
        var j = 0;
        while (j < stations.length - 1 && res[j] > balance) {
            j++;
        }
        // console.log(j === stations.length ? j - 1 : j + 1, balance, busCost, tramCost, res, stations);
        console.log(j);
    }
}
function costs(stations, busCost, tramCost, res) {
    res[stations.length - 1] = 0;
    res[stations.length - 2] = stations[stations.length - 2] === "A" ? busCost : tramCost;
    for (var i = stations.length - 3; i >= 0; i--) {
        if (stations[i] !== stations[i + 1]) {
            res[i] = res[i + 1] + (stations[i] === "A" ? busCost : tramCost);
        }
        else {
            res[i] = res[i + 1];
        }
    }
}
(function () {
    var s = "";
    process.stdin.on("data", function (d) { return s += d; });
    process.stdin.on("end", function () { return main(s); });
})();

"use strict";
exports.__esModule = true;
function main(rawInput) {
    var lines = rawInput.split("\n");
    var tests = parseInt(lines.shift(), 10);
    for (var i = 0; i < tests; i++) {
        var _a = lines.shift().split(" ").map(function (v) { return parseInt(v); }), busCost = _a[0], tramCost = _a[1], balance = _a[2];
        var stations = lines.shift().split("");
        var res = stations.map(function (v) { return 0; });
        costs(stations, busCost, tramCost, res);
        var j = 0;
        while (j < stations.length - 1 && res[j] > balance) {
            j++;
        }
        console.log(j === stations.length ? j - 1 : j + 1);
        // console.log(j+1);
    }
}
function costs(stations, busCost, tramCost, res) {
    res[stations.length - 1] = 0;
    res[stations.length - 2] = stations[stations.length - 2] === "A" ? busCost : tramCost;
    for (var i = stations.length - 3; i >= 0; i--) {
        if (stations[i] !== stations[i + 1]) {
            res[i] = res[i + 1] + (stations[i] === "A" ? busCost : tramCost);
        }
        else {
            res[i] = res[i + 1];
        }
    }
}
(function () {
    var s = "";
    process.stdin.on("data", function (d) { return s += d; });
    process.stdin.on("end", function () { return main(s); });
})();

"use strict";
exports.__esModule = true;
function main(rawInput) {
    var lines = rawInput.split("\n");
    var tests = parseInt(lines.shift(), 10);
    for (var i = 0; i < tests; i++) {
        var _a = lines.shift().split(" ").map(function (v) { return parseInt(v); }), busCost = _a[0], tramCost = _a[1], balance = _a[2];
        var stations = lines.shift().split("");
        var res = stations.map(function (v) { return 0; });
        costs(stations, busCost, tramCost, res);
        var j = 0;
        while (j < stations.length && res[j] > balance) {
            j++;
        }
        console.log(j === stations.length ? j - 1 : j + 1);
        // console.log(j+1);
    }
}
function costs(stations, busCost, tramCost, res) {
    res[stations.length - 1] = 0;
    res[stations.length - 2] = stations[stations.length - 2] === "A" ? busCost : tramCost;
    for (var i = stations.length - 3; i >= 0; i--) {
        if (stations[i] !== stations[i + 1]) {
            res[i] = res[i + 1] + (stations[i] === "A" ? busCost : tramCost);
        }
        else {
            res[i] = res[i + 1];
        }
    }
}
(function () {
    var s = "";
    process.stdin.on("data", function (d) { return s += d; });
    process.stdin.on("end", function () { return main(s); });
})();


function reversed(first, second)
{
    var ans = true;
    for(var i = 0; i < first.length; i++)
    {
        if (first[i] != second[first.length - 1 - i])
        {
            ans = false;
            break;
        }
    }
    return ans;
}

function pal(str)
{
    var half = Math.floor(str.length / 2);
    var ans = true;
    for(var i = 0; i < half; i++)
        if (str[i] != str[str.length - 1 - i])
        {
            ans = false;
            break;
        }
    return ans;
}

var input = readline().split(" ").map(function(x) { return parseInt(x); });
var n = input[0];
var m = input[1];

var arr = [];
while(n--)
    arr.push(readline());

var taked = Array.apply(null, Array(arr.length)).map(Number.prototype.valueOf,0);

var count = 0;
for(var i = 0; i < arr.length - 1; i++)
{
    if (taked[i] != 0)
        continue;

    for(var j = i + 1; j < arr.length; j++)
    {
        if (taked[j] != 0)
            continue;

        if (reversed(arr[i], arr[j]))
        {
            taked[i] = j;
            taked[j] = -1;
            count += 2;
        }
    }
}

var center = -1;
for(var i = 0; i < arr.length; i++)
    if (taked[i] == 0)
        if (pal(arr[i]))
        {
            count++;
            center = i;
            break;
        }

var ans = "";
if (center != -1)
    ans = arr[center];

for(var i = 0; i < arr.length - 1; i++)
    if (taked[i] > 0)
        ans = arr[i] + ans + arr[taked[i]];

print(count * m)
print(ans)

var palindromicPairs = {}
var palindromicStrings = []
var head = [], tail = [];
var input = []
var input1 = readline().split(' ').map((val)=>{
    return parseInt(val)
})
for (var m = 0; m < input1[0];m++){
    input.push(readline())
}
input.forEach((val)=>{
    var interim = val.split('').reverse().join('')
    if (interim == val){
        palindromicStrings.push(val)
    }
    else {
        if (!palindromicPairs.hasOwnProperty(val)){
            palindromicPairs[interim] = val
        }
        else{
            head.push(interim)
            tail.push(val)
        }
    }
})
var res = head.join('');
res += (palindromicStrings.length > 0) ? palindromicStrings[0] + tail.reverse().join('') : tail.reverse().join('')
if (head.length >0 || palindromicStrings.length>0){
    print(res.length)
    print(res)
}
else{
    print(0);
    print(' ')
}

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//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((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));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 one = myconv(next(),4);
  var N = one[0];
  var M = one[1];
  var list = new Array(N);
  var output = "";
  for(var i = 0; i < N; i++){
      list[i] = next();
  }
  for(var i = 0; i < N; i++){
      var check = myconv(list[i],6);
      var isKaibun = true;
      //kaibun check
      for(var j = 0; j < M; j++){
          if(check[j] != check[M - j - 1]){
              isKaibun = false;
              break;
          }
      }
      if(isKaibun){
          output = list[i];
          list.splice(i,1);
          break;
      }
  }

  for(var i = 0; i < list.length; i++){
      var tmp = myconv(list[i],6);
      var inverse = "";
      //myout(tmp);
      for(var j = 0; j < M; j++){
          inverse += tmp[M - j - 1];
      }
      if(list.indexOf(inverse) != -1 && list.indexOf(inverse) != i){
          output = myconv(tmp,0) + output + inverse;
          //myout(list.length);
          list.splice(i,1);
          list.splice(list.indexOf(inverse),1);
          //myout(list.length);
          i -= 1;
      }
  }
  myout(output.length);
  myout(output);

}

var palindromicPairs = {};
var palindromicStrings = [];
var head = [], tail = [];
var input = [];
var input1 = readline().split(' ').map((val)=>{
    return parseInt(val)
})
for (var m = 0; m < input1[0];m++){
    input.push(readline())
}
input.forEach((val)=>{
    var interim = val.split('').reverse().join('')
    if (interim == val){
        palindromicStrings.push(val)
    }
    else {
        if (!palindromicPairs.hasOwnProperty(val)){
            palindromicPairs[interim] = val
        }
        else{
            head.push(interim)
            tail.push(val)
        }
    }
})
var res = head.join('')+palindromicStrings[0]+tail.reverse().join('')
if (head.length >0 || palindromicStrings.length>0){
    print(res.length)
    print(res)
}
else{
    print(0);
    print(' ')
}

function reversed(first, second)
{
    var ans = true;
    for(var i = 0; i < first.length; i++)
    {
        if (first[i] != second[first.length - 1 - i])
        {
            ans = false;
            break;
        }
    }
    return ans;
}

function pal(str)
{
    var half = Math.floor(str.length / 2);
    var ans = true;
    for(var i = 0; i < half; i++)
        if (str[i] != str[str.length - 1 - i])
        {
            ans = false;
            break;
        }
    return ans;
}

var input = readline().split(" ").map(function(x) { return parseInt(x); });
var n = input[0];
var m = input[1];

var arr = [];
while(n--)
    arr.push(readline());

var taked = Array.apply(null, Array(arr.length)).map(Number.prototype.valueOf,0);

var count = 0;
for(var i = 0; i < arr.length - 1; i++)
{
    if (taked[i] != 0)
        continue;

    for(var j = i + 1; j < arr.length; j++)
    {
        if (taked[j] != 0)
            continue;

        if (reversed(arr[i], arr[j]))
        {
            taked[i] = j;
            taked[j] = -1;
            count += 2;
        }
    }
}

var center = -1;
for(var i = 0; i < arr.length; i++)
    if (taked[i] == 0)
        if (pal(arr[i]))
        {
            count++;
            center = i;
        }

var ans = "";
if (center != -1)
    ans = arr[center];

for(var i = 0; i < arr.length - 1; i++)
    if (taked[i] > 0)
        ans = arr[i] + ans + arr[taked[i]];

print(count * m)
print(ans)


const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var N, indicator = 0, stock = {};
rl.on('line', (input) => {
    if (indicator == 0) {
        let temp = input.split(" ").map(item => parseInt(item));
        let S = temp[0], M = temp[1], L = temp[2], XL = temp[3], XXL = temp[4];
        stock = {
            "S": S,
            "M": M,
            "L": L,
            "XL": XL,
            "XXL": XXL
        };
        indicator++;
    }
    else if (indicator == 1) {
        N = parseInt(input);
        indicator++;
    }
    else {
        switch (input) {
            case "S":
                if (stock["S"]) {
                    console.log("S");
                    stock["S"]--;
                }
                else if (stock["M"]) {
                    console.log("M");
                    stock["M"]--;
                }
                else if (stock["L"]) {
                    console.log("L");
                    stock["L"]--;
                }
                else if (stock["XL"]) {
                    console.log("XL");
                    stock["XL"]--;
                }
                else {
                    console.log("XXL");
                    stock["XXL"]--;
                }
                break;

            case "M":
                if (stock["M"]) {
                    console.log("M");
                    stock["M"]--;
                }
                else if (stock["L"]) {
                    console.log("L");
                    stock["L"]--;
                }
                else if (stock["S"]) {
                    console.log("S");
                    stock["S"]--;
                }
                else if (stock["XL"]) {
                    console.log("XL");
                    stock["XL"]--;
                }
                else {
                    console.log("XXL");
                    stock["XXL"]--;
                }
                break;

            case "L":
                if (stock["L"]) {
                    console.log("L");
                    stock["L"]--;
                }
                else if (stock["XL"]) {
                    console.log("XL");
                    stock["XL"]--;
                }
                else if (stock["M"]) {
                    console.log("M");
                    stock["M"]--;
                }
                else if (stock["XXL"]) {
                    console.log("XXL");
                    stock["XXL"]--;
                }
                else {
                    console.log("S");
                    stock["S"]--;
                }
                break;

            case "XL":
                if (stock["XL"]) {
                    console.log("XL");
                    stock["XL"]--;
                }
                else if (stock["XXL"]) {
                    console.log("XXL");
                    stock["XXL"]--;
                }
                else if (stock["L"]) {
                    console.log("L");
                    stock["L"]--;
                }
                else if (stock["M"]) {
                    console.log("M");
                    stock["M"]--;
                }
                else {
                    console.log("S");
                    stock["S"]--;
                }
                break;

            default:
                if (stock["XXL"]) {
                    console.log("XXL");
                    stock["XXL"]--;
                }
                else if (stock["XL"]) {
                    console.log("XL");
                    stock["XL"]--;
                }
                else if (stock["L"]) {
                    console.log("L");
                    stock["L"]--;
                }
                else if (stock["M"]) {
                    console.log("M");
                    stock["M"]--;
                }
                else {
                    console.log("S");
                    stock["S"]--;
                }
                break;
        }
    }
});

const readline = require("readline");

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

var findName = function (index) {
  switch (index) {
    case 0:
      return "S";
      break;
    case 1:
      return "M";
      break;
    case 2:
      return "L";
      break;
    case 3:
      return "XL";
      break;
    default:
      return "XXL";
      break;
  }
};
var search = function (index) {
  if (cont[index] > 0) {
    console.log(findName(index));
    cont[index]--;
  } else if (index < 4 && cont[index + 1] > 0) {
    console.log(findName(index + 1));
    cont[index + 1]--;
  } else if (index > 0 && cont[index - 1] > 0) {
    console.log(findName(index - 1));
    cont[index - 1]--;
  } else if (index < 3 && cont[index + 2] > 0) {
    console.log(findName(index + 2));
    cont[index + 2]--;
  } else if (index > 1 && cont[index - 2] > 0) {
    console.log(findName(index - 2));
    cont[index - 2]--;
  } else if (index < 2 && cont[index + 3] > 0) {
    console.log(findName(index + 3));
    cont[index + 3]--;
  } else if (index > 2 && cont[index - 3] > 0) {
    console.log(findName(index - 3));
    cont[index - 3]--;
  } else if (index < 1 && cont[index + 4] > 0) {
    console.log(findName(index + 4));
    cont[index + 4]--;
  } else {
    console.log(findName(index - 4));
    cont[index - 4]--;
  }
};

var cont = [],
  indicator = 0,
  n;
/*
while(true){
    string input = Console.ReadLine();
}

*/

rl.on("line", (input) => {
  if (indicator == 0) {
    cont = input.split(" ").map((item) => parseInt(item));
    indicator++;
  } else if (indicator == 1) {
    n = parseInt(input);
    indicator++;
  } else {
    switch (input) {
      case "S":
        search(0);
        break;

      case "M":
        search(1);
        break;
      case "L":
        search(2);
        break;
      case "XL":
        search(3);
        break;
      default:
        search(4);
        break;
    }
  }
});

'use strict'

let ss = readline().split(' ').map(v => parseInt(v))
let N = +readline()
let s

let res = []
while (s = readline()) {
  switch (s) {
    case 'S': s = 0; break
    case 'M': s = 1; break
    case 'L': s = 2; break
    case 'XL': s = 3; break
    case 'XXL': s = 4; break
  }

  let sts = [0, 1, -1, 2, -2, 3, -3, 4, -4, 5, -5]
  for (let j = 0; j < sts.length; j++) {
    if (ss[s + sts[j]]) {
      ss[s + sts[j]]--
      res.push(s + sts[j])
      break
    }
  }
}

res = res.map(v => {
  switch (v) {
    case 0: return 'S'
    case 1: return 'M'
    case 2: return 'L'
    case 3: return 'XL'
    case 4: return 'XXL'
  }
})

res.forEach(v => print(v))

'use strict';

/*let input = `1 0 2 0 1
3
XL
XXL
M`.split('\n');
function print(output) {
	console.log(output);
}
function readline() {
	return input.shift();
}*/

//code

var storage = readline().split(' ').map(Number);
var n = Number(readline());
var sizes = ["S", "M", "L", "XL", "XXL"];
for (var i = 0; i < n; i++) {
	var preference = sizes.indexOf(readline());
	var j = 0;
	while (true) {
		var index = preference + Math.ceil(j / 2) * (j % 2 === 0 ? -1 : 1);
		if (index < storage.length && index >= 0 && storage[index] !== 0) {
			print(sizes[index]);
			storage[index]--;
			break;
		}
		j++;
	}
}


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

    B();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function gcd(x, y) {
    if ((typeof x !== 'number') || (typeof y !== 'number'))
      return false;
    x = Math.abs(x);
    y = Math.abs(y);
    while(y) {
      var t = y;
      y = x % y;
      x = t;
    }
    return x;
  }

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,m] = ti(readline().split(' '));
        let mat = new Array(n);
        for(let i = 0; i < n; i++){
            mat[i] = ti(readline().split(' '));
        }

        for(let i = 0; i < n; i++){
            for(let j = 1; j < m; j++){
                if(mat[i][j] < 0 && mat[i][j-1] < 0){
                    mat[i][j] = -1*mat[i][j];
                    mat[i][j-1] = -1*mat[i][j-1];
                }
            }
        }

        for(let i = 0; i < m; i++){
            for(let j = 1; j < n; j++){
                if(mat[j][i] < 0 && mat[j-1][i] < 0){
                    mat[j][i] *= -1;
                    mat[j-1][i] *= -1;
                }
            }
        }

        let count = 0;
        let min = 99999999999;
        let sum = 0;
        for(let i = 0; i < n; i++){
            for(let j = 0; j < m; j++){
                if(mat[i][j] < 0){
                    count += 1;
                }

                min = Math.min(min, Math.abs(mat[i][j]));
                sum += Math.abs(mat[i][j]);
            }
        }

        if(count % 2 === 0){
            console.log(sum);
        }else{
            console.log(sum-2*min);
        }
    }
}

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

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

function main() {
  let t = +readLine();
  while (t--) {
    const [rowLen, colLen] = readLine().split(" ").map(Number);
    let [sum, min, countMinus] = [0, Infinity, 0];
    for (let row = 0; row < rowLen; row++) {
      readLine()
        .split(" ")
        .map((n) => {
          n = parseInt(n);
          if (n < 0) countMinus++;
          sum += Math.abs(n);
          min = Math.min(min, Math.abs(n));
          return n;
        });
    }
    if (countMinus % 2 === 1) sum -= 2 * min;

    console.log(sum);
  }
}

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

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

function main() {
  let t = +readLine();
  while (t--) {
    const [rowLen, colLen] = readLine().split(" ").map(Number);
    let [sum, min, foundMinus] = [0, Infinity, false];
    for (let row = 0; row < rowLen; row++) {
      readLine()
        .split(" ")
        .map((n) => {
          n = parseInt(n);
          if (!foundMinus && n < 0) foundMinus = true;
          sum += Math.abs(n);
          min = Math.min(min, Math.abs(n));
          return n;
        });
    }
    if (foundMinus) sum -= 2 * min;

    console.log(sum);
  }
}