You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) — the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each testcase print a single integer — the maximum beauty of a proper subsegment.

NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.

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

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

/* 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])
    }

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


Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≤ ai ≤ 100).

Print the single number — the maximum number of frames Nicholas can make for his future canvases.

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

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


You are given $$$n$$$ numbers $$$a_1, a_2, \dots, a_n$$$. With a cost of one coin you can perform the following operation:Choose one of these numbers and add or subtract $$$1$$$ from it.In particular, we can apply this operation to the same number several times.We want to make the product of all these numbers equal to $$$1$$$, in other words, we want $$$a_1 \cdot a_2$$$ $$$\dots$$$ $$$\cdot a_n = 1$$$. For example, for $$$n = 3$$$ and numbers $$$[1, -3, 0]$$$ we can make product equal to $$$1$$$ in $$$3$$$ coins: add $$$1$$$ to second element, add $$$1$$$ to second element again, subtract $$$1$$$ from third element, so that array becomes $$$[1, -1, -1]$$$. And $$$1\cdot (-1) \cdot (-1) = 1$$$.What is the minimum cost we will have to pay to do that?

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the numbers.

Output a single number — the minimal number of coins you need to pay to make the product equal to $$$1$$$.

NoteIn the first example, you can change $$$1$$$ to $$$-1$$$ or $$$-1$$$ to $$$1$$$ in $$$2$$$ coins.In the second example, you have to apply at least $$$4$$$ operations for the product not to be $$$0$$$.In the third example, you can change $$$-5$$$ to $$$-1$$$ in $$$4$$$ coins, $$$-3$$$ to $$$-1$$$ in $$$2$$$ coins, $$$5$$$ to $$$1$$$ in $$$4$$$ coins, $$$3$$$ to $$$1$$$ in $$$2$$$ coins, $$$0$$$ to $$$1$$$ in $$$1$$$ coin.

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

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

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

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

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


Madoka is going to enroll in "TSUNS PTU". But she stumbled upon a difficult task during the entrance computer science exam:  A number is called good if it is a multiple of $$$d$$$.  A number is called beatiful if it is good and it cannot be represented as a product of two good numbers. Notice that a beautiful number must be good.Given a good number $$$x$$$, determine whether it can be represented in at least two different ways as a product of several (possibly, one) beautiful numbers. Two ways are different if the sets of numbers used are different.Solve this problem for Madoka and help her to enroll in the best school in Russia!

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — number of test cases. Below comes their description. Each test case consists of two integers $$$x$$$ and $$$d$$$, separated by a space ($$$2 \leq x, d \leq 10^9$$$). It is guaranteed that $$$x$$$ is a multiple of $$$d$$$.

For each set of input data, output "NO" if the number cannot be represented in at least two ways. Otherwise, output "YES". You can output each letter in any case (for example, "YES", "Yes", "yes", "yEs", "yEs" will be recognized as a positive answer).

NoteIn the first example, $$$6$$$ can be represented as $$$6$$$, $$$1 \cdot 6$$$, $$$2 \cdot 3$$$. But $$$3$$$ and $$$1$$$ are not a good numbers because they are not divisible by $$$2$$$, so there is only one way.In the second example, $$$12$$$ can be represented as $$$6 \cdot 2$$$, $$$12$$$, $$$3 \cdot 4$$$, or $$$3 \cdot 2 \cdot 2$$$. The first option is suitable. The second is— no, because $$$12$$$ is not beautiful number ($$$12 = 6 \cdot 2$$$). The third and fourth are also not suitable, because $$$3$$$ is not good number.In the third example, $$$36$$$ can be represented as $$$18 \cdot 2$$$ and $$$6 \cdot 6$$$. Therefore it can be decomposed in at least two ways.

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


Tokitsukaze has two colorful tapes. There are $$$n$$$ distinct colors, numbered $$$1$$$ through $$$n$$$, and each color appears exactly once on each of the two tapes. Denote the color of the $$$i$$$-th position of the first tape as $$$ca_i$$$, and the color of the $$$i$$$-th position of the second tape as $$$cb_i$$$.Now Tokitsukaze wants to select each color an integer value from $$$1$$$ to $$$n$$$, distinct for all the colors. After that she will put down the color values in each colored position on the tapes. Denote the number of the $$$i$$$-th position of the first tape as $$$numa_i$$$, and the number of the $$$i$$$-th position of the second tape as $$$numb_i$$$.  For example, for the above picture, assuming that the color red has value $$$x$$$ ($$$1 \leq x \leq n$$$), it appears at the $$$1$$$-st position of the first tape and the $$$3$$$-rd position of the second tape, so $$$numa_1=numb_3=x$$$.Note that each color $$$i$$$ from $$$1$$$ to $$$n$$$ should have a distinct value, and the same color which appears in both tapes has the same value. After labeling each color, the beauty of the two tapes is calculated as $$$$$$\sum_{i=1}^{n}|numa_i-numb_i|.$$$$$$Please help Tokitsukaze to find the highest possible beauty.

The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$1\leq n \leq 10^5$$$) — the number of colors. The second line contains $$$n$$$ integers $$$ca_1, ca_2, \ldots, ca_n$$$ ($$$1 \leq ca_i \leq n$$$) — the color of each position of the first tape. It is guaranteed that $$$ca$$$ is a permutation. The third line contains $$$n$$$ integers $$$cb_1, cb_2, \ldots, cb_n$$$ ($$$1 \leq cb_i \leq n$$$) — the color of each position of the second tape. It is guaranteed that $$$cb$$$ is a permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^{5}$$$.

For each test case, print a single integer — the highest possible beauty.

NoteAn optimal solution for the first test case is shown in the following figure:  The beauty is $$$\left|4-3 \right|+\left|3-5 \right|+\left|2-4 \right|+\left|5-2 \right|+\left|1-6 \right|+\left|6-1 \right|=18$$$.An optimal solution for the second test case is shown in the following figure:  The beauty is $$$\left|2-2 \right|+\left|1-6 \right|+\left|3-3 \right|+\left|6-1 \right|+\left|4-4 \right|+\left|5-5 \right|=10$$$.

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

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


After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are $$$n$$$ crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string $$$s$$$ of length $$$n$$$, where $$$s_i = \texttt{A}$$$, if there is a bus station at $$$i$$$-th crossroad, and $$$s_i = \texttt{B}$$$, if there is a tram station at $$$i$$$-th crossroad. Currently Petya is at the first crossroad (which corresponds to $$$s_1$$$) and his goal is to get to the last crossroad (which corresponds to $$$s_n$$$).If for two crossroads $$$i$$$ and $$$j$$$ for all crossroads $$$i, i+1, \ldots, j-1$$$ there is a bus station, one can pay $$$a$$$ roubles for the bus ticket, and go from $$$i$$$-th crossroad to the $$$j$$$-th crossroad by the bus (it is not necessary to have a bus station at the $$$j$$$-th crossroad). Formally, paying $$$a$$$ roubles Petya can go from $$$i$$$ to $$$j$$$ if $$$s_t = \texttt{A}$$$ for all $$$i \le t < j$$$. If for two crossroads $$$i$$$ and $$$j$$$ for all crossroads $$$i, i+1, \ldots, j-1$$$ there is a tram station, one can pay $$$b$$$ roubles for the tram ticket, and go from $$$i$$$-th crossroad to the $$$j$$$-th crossroad by the tram (it is not necessary to have a tram station at the $$$j$$$-th crossroad). Formally, paying $$$b$$$ roubles Petya can go from $$$i$$$ to $$$j$$$ if $$$s_t = \texttt{B}$$$ for all $$$i \le t < j$$$.For example, if $$$s$$$="AABBBAB", $$$a=4$$$ and $$$b=3$$$ then Petya needs:  buy one bus ticket to get from $$$1$$$ to $$$3$$$,  buy one tram ticket to get from $$$3$$$ to $$$6$$$,  buy one bus ticket to get from $$$6$$$ to $$$7$$$. Thus, in total he needs to spend $$$4+3+4=11$$$ roubles. Please note that the type of the stop at the last crossroad (i.e. the character $$$s_n$$$) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the $$$n$$$-th crossroad. After the party he has left with $$$p$$$ roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad $$$i$$$ to go on foot the first, so he has enough money to get from the $$$i$$$-th crossroad to the $$$n$$$-th, using only tram and bus tickets.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The first line of each test case consists of three integers $$$a, b, p$$$ ($$$1 \le a, b, p \le 10^5$$$) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has. The second line of each test case consists of one string $$$s$$$, where $$$s_i = \texttt{A}$$$, if there is a bus station at $$$i$$$-th crossroad, and $$$s_i = \texttt{B}$$$, if there is a tram station at $$$i$$$-th crossroad ($$$2 \le |s| \le 10^5$$$). It is guaranteed, that the sum of the length of strings $$$s$$$ by all test cases in one test doesn't exceed $$$10^5$$$.

For each test case print one number — the minimal index $$$i$$$ of a crossroad Petya should go on foot. The rest of the path (i.e. from $$$i$$$ to $$$n$$$ he should use public transport).

5
2 2 1
BB
1 1 1
AB
3 2 8
AABBBBAABB
5 3 4
BBBBB
2 1 1
ABABAB

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

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

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


There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts.  Current character pointer (CP);  Direction pointer (DP) which can point left or right; Initially CP points to the leftmost character of the sequence and DP points to the right.We repeat the following steps until the first moment that CP points to somewhere outside the sequence.  If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was 0 then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one.  If CP is pointing to "<" or ">" then the direction of DP changes to "left" or "right" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is "<" or ">" then the previous character will be erased from the sequence. If at any moment the CP goes outside of the sequence the execution is terminated.It's obvious the every program in this language terminates after some steps.We have a sequence s1, s2, ..., sn of "<", ">" and digits. You should answer q queries. Each query gives you l and r and asks how many of each digit will be printed if we run the sequence sl, sl + 1, ..., sr as an independent program in this language.

The first line of input contains two integers n and q (1 ≤ n, q ≤ 105) — represents the length of the sequence s and the number of queries.  The second line contains s, a sequence of "<", ">" and digits (0..9) written from left to right. Note, that the characters of s are not separated with spaces.  The next q lines each contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the i-th query.

For each query print 10 space separated integers: x0, x1, ..., x9 where xi equals the number of times the interpreter prints i while running the corresponding program. Print answers to the queries in the order they are given in input.

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

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

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

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], qNum = data[1],
		s = trim(readline());
	for (var q = 0; q < qNum; ++q) {
		data = tokenizeIntegers(readline());
		var left = data[0]-1, right = data[1]-1,
			tape = s.substring(left, right+1).split(''),
			len = right-left+1,
			pos = 0, dir = +1,
			counts = new Array(10);
		for (var i = 0; i < 10; ++i) {
			counts[i] = 0;
		}
		function display() {
			print(tape.join('') + ' pos = '+pos);
		}
		while (pos >= 0 && pos < len) {
			var value = tape[pos];
			if (value != '<' && value != '>') {
				pos += dir;
				counts[value] += 1;
				tape[pos-dir] -= 1;
				if (tape[pos-dir] == -1) {
					tape.splice(pos-dir, 1);
					len -= 1;
					if (dir == 1) {
						pos -= 1;
					}
				}
			} else {
				dir = (value == '<' ? -1 : 1);
				pos += dir;
				if (pos != -1 && pos != len) {
					if (tape[pos] == '<' || tape[pos] == '>') {
						tape.splice(pos-dir, 1);
						len -= 1;
						if (dir == 1) {
							pos -= 1;
						}
					}
				}
			}
		}
		print(counts.join(' '));
	}
}

main();


Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has $$$n$$$ distinct strings of equal length $$$m$$$. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 50$$$) — the number of strings and the length of each string. Next $$$n$$$ lines contain a string of length $$$m$$$ each, consisting of lowercase Latin letters only. All strings are distinct.

In the first line, print the length of the longest palindrome string you made. In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.

9 4
abab
baba
abcd
bcde
cdef
defg
wxyz
zyxw
ijji

NoteIn the first example, "battab" is also a valid answer.In the second example, there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example, the empty string is the only valid palindrome string.

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

}

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


One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not exactly paper the walls with the oversupply). After considerable brain racking and some pre-estimating, the sponsor representatives ordered a certain number of T-shirts of sizes S, M, L, XL and XXL. The T-shirts turned out to bring good luck, that's why on the contest day there built up a line of K participants willing to get one. Every contestant is characterized by his/her desired T-shirt size (so it happens that for all the participants it is also one of the sizes S, M, L, XL and XXL). The participants come up to get a T-shirt one by one and try to choose the most suitable one, choosing it like this. If there is still a T-shirt of the optimal size left, that he/she takes it without further ado. Otherwise the contestant would prefer to choose a T-shirt with the size as close to the optimal one as possible (the distance between neighboring sizes is considered equal to one). If the variant of choice is not unique, the contestant will take a T-shirt of a bigger size (in case he/she grows more). For example, for a person whose optimal size is L the preference list looks like this: L, XL, M, XXL, S. Using the data on how many T-shirts of every size had been ordered by the organizers, on the size of contestants in the line determine who got a T-shirt of what size.

The first line contains five non-negative integers NS, NM, NL, NXL, NXXL not exceeding 1000 which represent the number of T-shirts of the corresponding sizes. The second line contains an integer K (1 ≤ K ≤ 1000) which represents the number of participants. The next K lines contain the optimal T-shirt sizes for the contestants. The sizes are given in the order in which the participants stand in the line. It is guaranteed that NS + NM + NL + NXL + NXXL ≥ K.

For each contestant, print a line containing the size of the T-shirt he/she got.

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

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