Polycarp is playing a new computer game. This game has $$$n$$$ stones in a row. The stone on the position $$$i$$$ has integer power $$$a_i$$$. The powers of all stones are distinct.Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone). When Polycarp destroys the stone it does not exist any more.Now, Polycarp wants two achievements. He gets them if he destroys the stone with the least power and the stone with the greatest power. Help Polycarp find out what is the minimum number of moves he should make in order to achieve his goal.For example, if $$$n = 5$$$ and $$$a = [1, 5, 4, 3, 2]$$$, then Polycarp could make the following moves:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the rightmost stone. After this move $$$a = [5, 4, 3]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game. Please note that in the example above, you can complete the game in two steps. For example:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3, 2]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stones. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the power of the stones.

For each test case, output the minimum number of moves required to destroy the stones with the greatest and the lowest power.

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

function readLine() {
  return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  let t = parseInt(readLine()); // number of test cases

  while (t--) {
    let n = parseInt(readLine()); // number of stones

    let a = readLine()
      .split(" ")
      .map((x) => parseInt(x)); // array of power of stones

    console.log(getMoves(a));
  }
}

function getMoves(a) {
  let minPoz = 0;
  let maxPoz = 0;

  // find the least and greatest power stone
  for (let i = 1; i < a.length; i++) {
    if (a[i] > a[maxPoz]) maxPoz = i;
    if (a[i] < a[minPoz]) minPoz = i;
  }

  let stones = a.length;

  // 1st case
  let case1 = minPoz + 1 + stones - maxPoz;

  // 2nd case
  let case2 = maxPoz + 1 + stones - minPoz;

  // 3rd case
  let case3 = Math.max(minPoz, maxPoz) + 1;

  // 4th case
  let case4 = Math.max(stones - maxPoz, stones - minPoz);

  return Math.min(case1, case2, case3, case4);
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var n = +lines[l++];
        console.log(solve(lines[l++].split(' ').map(Number)));
    }
});

const solve = (l) => {
    const indexMin = l.indexOf(Math.min(...l));
    const indexMax = l.indexOf(Math.max(...l));

    const max = Math.max(indexMin, indexMax);
    const min = Math.min(indexMin, indexMax);

    // CASE 1
    const case_1 = max + 1;

    // CASE 2
    const case_2 = l.length - min;

    // case 3
    const case_3 = min + 1 + l.length - max;

    return Math.min(case_1, case_2, case_3);
};

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

  if (c % 2 === 1) {
    c++;
    return;
  }

  const arr = d.split(" ").map(Number);
  const min = arr.indexOf(Math.min(...arr));
  const max = arr.indexOf(Math.max(...arr));
  const ans = Math.min(
    Math.max(min + 1, max + 1),
    Math.max(arr.length - min, arr.length - max),
    min + 1 + arr.length - max,
    max + 1 + arr.length - min
  );

  console.log(ans);

  c++;
});

rl.on("close", () => {});

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

let c = 0;
let found = 0;

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

  if (c % 2 === 1) {
    c++;
    return;
  }

  const arr = d.split(" ").map(Number);
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  let ans = Infinity;

  found = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === min) {
      found++;
    }

    if (arr[i] === max) {
      found++;
    }

    if (found === 2) {
      ans = Math.min(ans, i + 1);
      break;
    }
  }

  arr.reverse();
  found = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === min) {
      found++;
    }

    if (arr[i] === max) {
      found++;
    }

    if (found === 2) {
      ans = Math.min(ans, i + 1);
      break;
    }
  }

  const firstNumber = Math.min(arr.indexOf(min), arr.indexOf(max)) + 1;
  arr.reverse();
  const secondNumber = Math.min(arr.indexOf(min), arr.indexOf(max)) + 1;
  ans = Math.min(ans, firstNumber + secondNumber);

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

rl.on("close", () => {});

process.stdin.resume();

process.stdin.setEncoding('utf8');

var input = '';

process.stdin.on('data' , data=>{
    input += data;
});
process.stdin.on('end' , ()=>{
    main(input);
});

function main(input) {
    input = input.split("\n");
    let z = 0;
    let testCases = +input[z++];

    while(testCases--){
        let arrLen = +input[z++];
        let arr = input[z++].split(' ').map(x=>Number(x));

        let firstIdx = arr.indexOf(1)
        let lastIdx = arr.indexOf(arrLen);
        let maxIdx = Math.max(firstIdx, lastIdx);
        let minIdx = Math.min(firstIdx, lastIdx);

        let option1 = (arrLen - maxIdx) + minIdx + 1;
        let option2 = minIdx + (maxIdx - minIdx) + 1;
        let option3 = (arrLen - maxIdx) + (arrLen - minIdx - (arrLen - maxIdx));

        console.log(Math.min(option1, option2, option3));
    }
}

process.stdin.resume();

process.stdin.setEncoding('utf8');

var input = '';

process.stdin.on('data' , data=>{
    input += data;
});
process.stdin.on('end' , ()=>{
    main(input);
});

function main(input) {
    input = input.split("\n");
    let z = 0;
    let testCases = +input[z++];

    while(testCases--){
        let arrLen = +input[z++];
        let arr = input[z++].split(' ').map(x=>Number(x));

        let firstIdx = arr.indexOf(1);
        let lastIdx = arr.indexOf(arrLen);
        let maxIdx = Math.max(firstIdx, lastIdx);
        let minIdx = Math.min(firstIdx, lastIdx);

        let option1 = (arrLen - maxIdx) + minIdx + 1;
        let option2 = minIdx + (maxIdx - minIdx) + 1;
        let option3 = (arrLen - maxIdx) + (arrLen - minIdx - (arrLen - maxIdx));

        console.log(Math.min(option1, option2, option3));
    }
}

'use strict';

function solve(n, a) {
  const min = Math.min(...a),
        max = Math.max(...a);
  let mi = a.findIndex(num => num === min),
      ma = a.findIndex(num => num === max);
  if (mi > ma) [mi, ma] = [ma, mi];
  return Math.min(ma + 1, n - mi, mi + 1 + n - ma);
}

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

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

let q = '';
process.stdin.on('data', c => q += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = q.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);
            var max = 0, min = 110000000000;
            for(j = 0; j < n; j++){
                max = Math.max(max, k[j]);
                min = Math.min(min, k[j]);
            }
            var lma = 0, lmi = 0;
            for(j = 0; j < n; j++){
                if(k[j] == max){
                    lma = j + 1;
                }
                if(k[j] == min){
                    lmi = j + 1;
                }
            }
            var rma = n - lma + 1;
            var rmi = n - lmi + 1;
            var a1 = Math.max(rma, rmi);
            var a2 = Math.max(lma, lmi);
            var a3 = Math.min(lma + rmi, rma + lmi);
            console.log(Math.min(a1, Math.min(a2, a3)));
        }
    }
});

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

function main(input) {
    var args = input.split("\n");
    const t = parseInt(args[0], 10);
    for (var i = 1; i <= t; i++) {
        var n = parseInt(args[2 * i - 1], 10);
        var v = args[2 * i].split(" ").map((n) => parseInt(n, 10));
        var a = 0, b = 0;
        for (var j = 0; j < n; j++) {
            if (v[j] == 1) {
                a = j;
            }
            if (v[j] == n) {
                b = j;
            }
        }
        var c = Math.min(a, b) + 1;
        var d = Math.max(a, b) + 1;
        console.log(Math.min(d, n - c + 1, c + n - d + 1));
    }
}

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

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i = 0; i < t; i++){
		let m = nl.num();
		let a = nl.nums();
		let mi = a.indexOf(1);
		let ma = a.indexOf(m);
		let r = [mi + 1, ma + 1, Math.abs(mi - ma), m - mi, m - ma];
		r.sort((a, b) => a - b);
		ans.push(r[0] + r[1]);

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

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

process.stdin.resume();
process.stdin.setEncoding("utf8");
let standardInputString = "";
let currentLine = 0;
function readLine() {
  return standardInputString[currentLine++];
}
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function main() {
  const numArray = (a) => a.split(" ").map((line) => +line),
    cl = console.log,
    rl = readLine,
    tc = rl();

  for (let i = 0; i < tc; i++) {
    let n = rl();
    let array = numArray(rl());
    let step = 0;

    let greatest = array.indexOf(Math.max(...array)) + 1;
    let least = array.indexOf(Math.min(...array)) + 1;
    let i = 0;

    let dleft = Math.max(least, greatest);
    let dright = Math.max(n - greatest, n - least) + 1;

    let dleftRight = n - greatest + least + 1;
    let drightLeft = greatest + (n - least) + 1;

    console.log(Math.min(dleft, dright, drightLeft, dleftRight));
  }
}

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

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

function div(a, b) {
   return Math.floor(a / b);
}

function solve() {
   var n = Number(read());
   var arr = readArray((a, i) => [Number(a), i]);
   arr.sort((a, b) => a[0] - b[0]);
   var i1 = arr[0][1];
   var i2 = arr[n - 1][1];
   if (i1 > i2) {
      var temp = i1;
      i1 = i2;
      i2 = temp;
   }
   var ans1 = n - i2 + i1 + 1;
   var ans2 = i2 + 1;
   var ans3 = n - i1;
   write(Math.min(ans1, Math.min(ans2, ans3)));
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

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

let lineContent = ''

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

    const testNumbers = parseInt(lines[0]);

    for (let i = 0; i < testNumbers; i++) {
        const [n] = lines[1 + i * 2].split(" ").map((e) => parseInt(e));
        const arr = lines[2 + i * 2].split(" ").map(e => parseInt(e));

        console.log(f(n, arr));
    }

})

const f = (n, arr) => {
    let max = 0, min = 0;
    for (let i = 0; i < n; i++) {
        const curr = arr[i];
        if (arr[max] < curr) {
            max = i;
        }
        if (arr[min] > curr) {
            min = i;
        }
    }

    const a = max > min ? max : min;
    const b = max > min ? min : max;

    return Math.min(a + 1, n - b, b + 1 + n - a);
}

//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] = BigInt(next());
		}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 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 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);
		var output = 1 << 30;
		var L = list.indexOf(1);
		var R = list.indexOf(N);
		if(L > R){
			var tmp = L;
			L = R;
			R = tmp;
		}
		output = Math.min(output, R + 1);
		output = Math.min(output, N - L);
		output = Math.min(output, L + (N - R) + 1);
		myout(output);
	}
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        console.log(solve(lines[l++].split(' ').map(Number)));
    }
});

function solve(nums) {
    const max = Math.max(...nums)
    const min = Math.min(...nums)
    let a = nums.indexOf(max)
    let b = nums.indexOf(min)
    if (a > b) {
        const t = a
        a = b
        b = t
    }

    const t1 = b + 1
    const t2 = nums.length - a
    const t3 = a + 1 + nums.length - b
    const t4 = nums.length - a + b + 1
    return Math.min(t1, t2, t3, t4)
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));
  var min = 101;
  var a;
  var max = -1;
  var b;

  a.forEach((el, i) => {
    if (el > max) {
      max = el;
      a = i;
    }
    if (el < min) {
      min = el;
      b = i;
    }
  })

  if (b < a) {
    var tt = a;
    a = b;
    b = tt;
  }

  print(Math.min(b + 1, n - a, n - b + a + 1));
}

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var x = +readline();
    var nums = readNumArray();
    var maxInd = 0;
    var minInd = 0;
    for (var j = 1; j < x; j++) {
      if (nums[j] > nums[maxInd]) {
        maxInd = j;
      }
      if (nums[j] < nums[minInd]) {
        minInd = j;
      }
    }

    var mnInd = maxInd > minInd ? minInd : maxInd;
    var mxInd = maxInd < minInd ? minInd : maxInd
    var n12 = mxInd - mnInd - 1;
    var n1 = mnInd;
    var n2 = nums.length - mxInd - 1;
    var max = Math.max(n1, n2, n12);
    print(nums.length - max);
  }
}

main();

var numberOfCases = Number(readline());
for (var i = 0; i < numberOfCases; ++i) {
    processCase();
}

function processCase() {
    var numsCount = Number(readline());
    var nums = readline().split(" ").map(x => Number(x));

    var indicies = [0, 0];
    for (var i = 0; i < nums.length; ++i) {
        if (nums[i] < nums[indicies[0]]) {
            indicies[0] = i;
        }

        if (nums[i] > nums[indicies[1]]) {
            indicies[1] = i
        }
    }

    if (indicies[0] > indicies[1]) {
        var tmp = indicies[0];
        indicies[0] = indicies[1];
        indicies[1] = tmp;
    }

    var distances = [
        indicies[0] + 1,
        nums.length - indicies[1]
    ];

    var indexDistance = indicies[1] - indicies[0];
    print(Math.min(distances[0] + indexDistance, distances[1] + indexDistance, distances[0] + distances[1]))
}

var tc = parseInt(readline());
while(tc--) {
    var n = parseInt(readline());
    var arr = readline().split(' ').map(i => parseInt(i));
    var indexMax = arr.indexOf(Math.max(...arr));
    var indexMin = arr.indexOf(Math.min(...arr));

    var min = Math.min(indexMax, indexMin);
    var max = Math.max(indexMax, indexMin);

    var case1 = max + 1;
    var case2 = n - min;
    var case3 = min + 1 + n - max;

    print(Math.min(case1, case2, case3));
}

var n = parseInt(readline());
  while (n--) {
    var s = parseInt(readline());
    var stones = readline()
      .split(" ")
      .map((data) => +data);
    var stonesort = [].concat(stones).sort((a, b) => a - b);
    var max = stones.indexOf(stonesort[s - 1]);
    var min = stones.indexOf(stonesort[0]);
    var maxleft = stones.slice(max).length;
    var minleft = stones.slice(min).length;

    var maxright = stones.slice(0, max + 1).length;
    var minright = stones.slice(0, min + 1).length;

    var middleright = Math.max(maxright, minright);
    var middleleft = Math.max(maxleft, minleft);

    var mid = Math.min(maxright, minright);
    var midd = Math.min(maxleft, minleft);
    var middle = mid + midd;
    var ans = Math.min(middleright, middleleft, middle);
    print(ans);
  }

// A. Stone Game

var l0 = readline();
var n = +l0;
var arr = [];
for (var a = 0; a<n; a++) {
    var ignore = readline();
    arr.push(readline().split(' ').map(v => +v));
}

for (var x = 0; x< n; x++) {
    var min = Infinity;
    var max = 0;
    var aIndex;
    var bIndex;
    for (var y = 0; y< arr[x].length; y++) {
        if (arr[x][y] < min) {
            min = arr[x][y];
            aIndex = y;
        }

        if (arr[x][y] > max) {
            max = arr[x][y];
            bIndex = y;
        }
    }

    // sort index
    var temp = aIndex;
    if (aIndex > bIndex) {
        aIndex = bIndex;
        bIndex = temp;
    }

    var t1 = 0;
    // 1* Destroy the stones on the left until we destroy the smallest stone.
    // Then destroy the stones on the right, until we destroy the largest stone.
    t1 = t1 + Math.abs(0 - aIndex) + 1;
    t1 = t1 + Math.abs(arr[x].length - bIndex);

    // 2* Destroy the stones on the right until we destroy the smallest stone.
    // Then destroy the stones on the left, until we destroy the largest stone.
    // ignore it, because I ordered the indexes
    var t2 = Infinity

    // 3* Destroy the stones on the left until we destroy both stones.
    var t3 = 0
    var t3 = t3 + Math.abs(0 - bIndex) + 1;

    // 4* Destroy the stones on the right until we destroy both stones.
    var t4 = 0;
    var t4 = t4 + Math.abs(arr[x].length - aIndex);

    print(Math.min(t1,t2,t3,t4));
}

var t = parseInt(readline());

for(i = 0; i < t; i++) {
    var n = parseInt(readline());
    var a = readline().split(" ");
    var min = 0, max = 0;
    for(j = 0; j < n; j++) {
        if(a[j] == 1) min = j + 1;
        else if(a[j] == n) max = j + 1;
        if(min !== 0 && max !== 0) break;
    }
    if(n % 2 === 1 && ((min === (n + 1)/2) || (max === (n + 1)/2))) {
        print((n + 1)/2);
    }
    else {
        var left = Math.max(min, max);
        var right = Math.max(n - min + 1, n - max + 1);
        var middle;
        if(min < max) middle = min + n - max + 1;
        else middle = max + n - min + 1;
        print(Math.min(left, right, middle));
    }
}

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

function readLine() {
  return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  let t = parseInt(readLine()); // number of test cases

  while (t--) {
    let n = parseInt(readLine()); // number of stones

    let a = readLine()
      .split(" ")
      .map((x) => parseInt(x)); // array of power of stones

    console.log(getMoves(a));
  }
}

function getMoves(a) {
  let minPoz = 0;
  let maxPoz = 0;

  // find the least and greatest power stone
  for (let i = 1; i < a.length; i++) {
    if (a[i] > a[maxPoz]) maxPoz = i;
    if (a[i] < a[minPoz]) minPoz = i;
  }

  let stones = a.length;

  // 1st case
  let case1 = minPoz + 1 + stones - maxPoz;

  // 2nd case
  let case2 = maxPoz + 1 + stones - minPoz;

  // 3rd case
  let case3 = Math.max(minPoz, maxPoz);

  return Math.min(case1, case2, case3);
}

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

function readLine() {
  return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  let t = parseInt(readLine()); // number of test cases

  while (t--) {
    let n = parseInt(readLine()); // number of stones

    let a = readLine()
      .split(" ")
      .map((x) => parseInt(x)); // array of power of stones

    console.log(getMoves(a));
  }
}

function getMoves(a) {
  let minPoz = 0;
  let maxPoz = 0;

  // find the least and greatest power stone
  for (let i = 1; i < a.length; i++) {
    if (a[i] > a[maxPoz]) maxPoz = i;
    if (a[i] < a[minPoz]) minPoz = i;
  }

  if (minPoz <= Math.abs(a.length / 2) && maxPoz <= Math.abs(a.length / 2))
    return Math.max(minPoz + 1, maxPoz + 1);

  if (minPoz >= Math.abs(a.length / 2) && maxPoz >= Math.abs(a.length / 2))
    return Math.max(a.length - minPoz, a.length - maxPoz);

  if (
    (minPoz <= Math.abs(a.length / 2) && maxPoz >= Math.abs(a.length / 2)) ||
    (minPoz >= Math.abs(a.length / 2) && maxPoz <= Math.abs(a.length / 2))
  ) {
    return (
      Math.min(minPoz + 1, maxPoz + 1) +
      Math.min(a.length - minPoz, a.length - maxPoz)
    );
  }
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        console.log(solve(lines[l++].split(' ').map(Number)));
    }
});

const solve = (l) => {
    let lowest = l.indexOf(Math.min(...l)) + 1;
    let highest = l.indexOf(Math.max(...l)) + 1;

    const mid = Math.ceil(l.length/2);
    console.log(lowest, highest, mid);

    let num = Number.POSITIVE_INFINITY;

    // CASE 1
    num = Math.min(num, Math.max(lowest, highest));

    // CASE 2
    const reveseL = l.reverse();
    let rightLowest = reveseL.indexOf(Math.min(...reveseL)) + 1 ;
    let rightHighest = reveseL.indexOf(Math.max(...reveseL)) + 1;
    num = Math.min(num, Math.max(rightLowest, rightHighest));

    // case 3
    const left = Math.min(lowest, rightLowest);
    const right = Math.min(highest, rightHighest);

    num = Math.min(num, left +  right);

    return num;
};

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));
  var min = 101;
  var a;
  var max = -1;
  var b;

  a.forEach((el, i) => {
    if (el > max) {
      max = el;
      a = i;
    }
    if (el < min) {
      min = el;
      b = i;
    }
  })

  if (b < a) {
    var tt = a;
    a = b;
    b = tt;
  }

  var ans;
  var mid = parseInt((n - 1) / 2);

  if ((a < mid && b < mid) || (a > mid && b > mid)) {
    ans = Math.min(Math.max(a, b), n - 1- Math.min(a, b)) + 1;
  }
  else {
    ans = Math.min(a + n - b + 1, b + 1, n - a + 1);
  }

  print(ans);

}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));
  var min = 101;
  var a;
  var max = -1;
  var b;

  a.forEach((el, i) => {
    if (el > max) {
      max = el;
      a = i;
    }
    if (el < min) {
      min = el;
      b = i;
    }
  })

  if (b < a) {
    var tt = a;
    a = b;
    b = tt;
  }

  var ans;
  var mid = parseInt((n - 1) / 2);

  if ((a < mid && b < mid) || (a > mid && b > mid)) {
    ans = Math.min(Math.max(a, b), n - 1- Math.min(a, b)) + 1;
  }
  else {
    var r = Math.min((b - a), (n - b));
    ans = a + (r > 0? r + 1 : r);
  }

  print(ans);

}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));
  var min = 101;
  var a;
  var max = -1;
  var b;

  a.forEach((el, i) => {
    if (el > max) {
      max = el;
      a = i;
    }
    if (el < min) {
      min = el;
      b = i;
    }
  })

  if (b < a) {
    var tt = a;
    a = b;
    b = tt;
  }

  var ans;
  var mid = parseInt((n - 1) / 2);

  if ((a < mid && b < mid) || (a > mid && b > mid)) {
    ans = Math.min(Math.max(a, b) + 1, n - Math.max(a, b) + 1);
  }
  else {
    var r = Math.min((b - a), (n - b));
    ans = a + (r > 0? r + 1 : r);
  }

  print(ans);

}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var n = parseInt(readline());
  var a = readline().split(' ').map(d => parseInt(d));
  var min = 101;
  var a;
  var max = -1;
  var b;

  a.forEach((el, i) => {
    if (el > max) {
      max = el;
      a = i;
    }
    if (el < min) {
      min = el;
      b = i;
    }
  })

  if (b < a) {
    var tt = a;
    a = b;
    b = tt;
  }

  var ans;
  var mid = parseInt((n - 1) / 2);

  if ((a < mid && b < mid) || (a > mid && b > mid))
    ans = Math.min(Math.max(a, b) + 1, n - Math.max(a, b) + 1);
  else
    ans = a + Math.min((b - a), (n - b)) + 1;

  print(ans);

}

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var x = +readline();
    var nums = readNumArray();
    var maxInd = nums[0];
    var minInd = nums[0];
    for (var j = 0; j < x; j++) {
      if (nums[j] > nums[maxInd]) {
        maxInd = j;
      }
      if (nums[j] < nums[minInd]) {
        minInd = j;
      }
    }

    var mnInd = maxInd > minInd ? minInd : maxInd;
    var mxInd = maxInd < minInd ? minInd : maxInd
    var n12 = mxInd - mnInd - 1;
    var n1 = mnInd;
    var n2 = nums.length - mxInd - 1;
    var max = Math.max(n1, n2, n12);
    print(nums.length - max);
  }
}

main();

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var x = +readline();
    var nums = readNumArray();
    var maxInd = nums[0];
    var minInd = nums[0];
    for (var j = 0; j < x; j++) {
      if (nums[j] > nums[maxInd]) {
        maxInd = j;
      }
      if (nums[j] < nums[minInd]) {
        minInd = j;
      }
    }

    var mnInd = maxInd > minInd ? minInd : maxInd;
    var mxInd = maxInd < minInd ? minInd : maxInd
    var n12 = mxInd - mnInd;
    var n1 = mnInd + 1;
    var n2 = Math.abs(nums.length - mxInd);
    var max = Math.max(n1, n2, n12);
    print(nums.length - max + 1);;
  }
}
main();

function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var x = +readline();
    var nums = readNumArray();
    var maxInd = nums[0];
    var minInd = nums[0];
    for (var j = 0; j < x; j++) {
      if (nums[j] > nums[maxInd]) {
        maxInd = j;
      }
      if (nums[j] < nums[minInd]) {
        minInd = j;
      }
    }

    var mnInd = maxInd > minInd ? minInd : maxInd;
    var mxInd = maxInd < minInd ? minInd : maxInd
    var n12 = Math.abs(mxInd - mnInd - 1);
    var n1 = mnInd;
    var n2 = Math.abs(nums.length - mxInd - 1);
    var max = Math.max(n1, n2, n12);
    print(nums.length - max);;
  }

}

main();

var numberOfCases = Number(readline());
for (var i = 0; i < numberOfCases; ++i) {
    processCase();
}

function processCase() {
    var numsCount = Number(readline());
    var nums = readline().split(" ").map(x => Number(x));

    var indicies = [0, 0];
    for (var i = 0; i < nums.length; ++i) {
        if (nums[i] < nums[indicies[0]]) {
            indicies[0] = i;
        }

        if (nums[i] > nums[indicies[1]]) {
            indicies[1] = i
        }
    }

    indicies.sort();
    var distances = [
        indicies[0] + 1,
        nums.length - indicies[1]
    ];

    var indexDistance = indicies[1] - indicies[0];
    print(Math.min(distances[0] + indexDistance, distances[1] + indexDistance, distances[0] + distances[1]))
}


Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.

The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.

If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".

NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.

var number = readline();
var formerStandings = [];
var nextStandings = [];
var flag2 = true;
for(var i=0; i<number; i++) {
    var line = readline().split(" ");
    formerStandings.push(parseInt(line[0]));
    if(line[0]!=line[1])
    flag2 = false;
}
var flag = true;
for(var i=0;i<number-1;i++) {
    if(Math.min(formerStandings[i],formerStandings[i+1])!=formerStandings[i+1])
    flag=  false;
}

if(!flag2)
print("rated");
else if(flag)
print("maybe");
else
print("unrated");

  var n = parseInt(readline());
  var last = Infinity;
  var res = 'maybe';
  for(var i = 0; i < n; i += 1) {
    var tmp = readline().split(' ').map(x => parseInt(x));
    if(tmp[0] !== tmp[1]) {
      res = 'rated';
    }
    if(res === 'maybe') {
      if(tmp[0] > last) {
        res = 'unrated'
      }
    }
    last = tmp[0];
  }
  print(res);

 function cal() {
        var n = +readline();
        var temp = 0;
        var maybe = true;
        var res = '';
        for (var i = 0; i < n; i++) {
            var token = readline().split(' ');
            var numA = +token[0];
            var numB = +token[1];

            if (numA != numB) {
                print("rated");
                return;
            }

            if (temp != 0 && numA > temp)
                maybe = false;
            temp = numA;

        }

        if (maybe)
            print("maybe");
        else
            print("unrated");

    }
    cal();

var rounds = parseInt(readline());

var rated = false;
var unrated = false;

var before;
var after;

for (var i = 0; i < rounds; i++) {
    var values = readline().split(" ").map(Number);
    if (values[0] > before || values[1] > after) {
        unrated = true;
    }

    before = values[0];
    after = values[1];

    if (before !== after) {
        rated = true;
        break;
    }
}

if (rated) {
    print('rated');
} else if (unrated) {
    print('unrated');
} else {
    print('maybe');
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
let prev = Infinity;
let ans = 'maybe';

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

  const [a, b] = d.split(' ').map(Number);

  if (b > a) {
    ans = 'rated';
  }

  if (a !== b) {
    ans = 'rated';
  }

  if (prev < a && ans !== 'rated') {
    ans = 'unrated';
  }
  else {
    prev = a;
  }

  c++;
});

rl.on('close', () => {
  console.log(ans);
});

'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 readint() {
    let line = readline().split(' ').map(function(num) {
        return parseInt(num);
    });
    return line;
}

function readfloat() {
    let line = readline().split(' ').map(function(num) {
        return parseFloat(num);
    });
    return line;
}

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

function write(x) {
    process.stdout.write(x);
}

function array2d(r,c) {
    let ans =[];
    for(let i = 0; i < r; i++) {
        let rowElements = [];
        for(let j = 0; j < c; j++) {
            rowElements.push(0);
        }
        ans.push(rowElements);
    }
    return ans;
}
function max(a,b){
    if(a > b) return a;
    else return b;
}
function main() {
    let [n] = readint();
    let changed = false;
    let sorted = true;
    let [prevA,prevB] = [5000,5000];
    while(n--) {
        let [a,b] = readint();
        if(a != b) changed = true;
        if(prevA < a) sorted = false;
        prevA = a;
        prevB = b;
    }
    if(changed) print("rated");
    else if(!sorted) print("unrated");
    else print("maybe");

}

var number = readline();
var formerStandings = [];
var nextStandings = [];
var flag2 = true;
for(var i=0; i<number; i++) {
    var line = readline().split(" ");
    formerStandings.push(parseInt(line[0]));
    if(line[0]!=line[1])
    flag2 = false;
}
var flag = true;
if(formerStandings.reduce(function(x,y){return Math.min(x,y)})!=formerStandings[number-1])
    flag = false;

if(!flag2)
print("rated");
else if(flag)
print("maybe");
else
print("unrated");

var number = readline();
var formerStandings = [];
var nextStandings = [];
var flag2 = true;
for(var i=0; i<number; i++) {
    var line = readline().split(" ");
    formerStandings.push(parseInt(line[0]));
    if(line[0]!=line[1])
    flag2 = false;
}
var flag = true;
for(var i=0;i<number-1;i++) {
    if(Math.min(formerStandings[i],formerStandings[i+1]!=formerStandings[i+1]))
    flag=  false;
}

if(!flag2)
print("rated");
else if(flag)
print("maybe");
else
print("unrated");

var n = +readline();
        var temp = 0;
        var maybe = true;
        var res ='';
        for (var i = 0; i < n; i++) {
            var token = readline().split(' ');
            var numA = token[0];
            var numB = token[1];

            if (numA != numB) {
                res = "rated";
            }

            if (temp != 0 && numA > temp)
                maybe = false;
            temp = numA;

        }
        if (res != '') {
            print(res);

        } else
        if (maybe)
            print("maybe");
        else
            print("unrated");

function cal() {
        var n = +readline();
        var temp = 0;
        var maybe = true;
        var res = '';
        for (var i = 0; i < n; i++) {
            var token = readline().split(' ');
            var numA = token[0];
            var numB = token[1];

            if (numA != numB) {
                print("rated");
                return;
            }

            if (temp != 0 && numA > temp)
                maybe = false;
            temp = numA;

        }

        if (maybe)
            print("maybe");
        else
            print("unrated");

    }
    cal();

function cal() {
        var n = +readline();
        var temp = 0;
        var maybe = true;
        var res = '';
        for (var i = 0; i < n; i++) {
            var token = readline().split(' ');
            var numA = token[0];
            var numB = token[1];

            if (numA != numB) {
                res = "rated";
                return;
            }

            if (temp != 0 && numA > temp)
                maybe = false;
            temp = numA;

        }

        if (maybe)
            print("maybe");
        else
            print("unrated");

    }
    cal();

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
let prev = Infinity;
let ans = 'maybe';

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

  const [a, b] = d.split(' ').map(Number);

  if (b > a) {
    ans = 'rating';
  }

  if (prev < a) {
    ans = 'unrated';
  }
  else {
    prev = a;
  }

  c++;
});

rl.on('close', () => {
  console.log(ans);
});

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
let prev = Infinity;
let ans = 'maybe';

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

  const [a, b] = d.split(' ').map(Number);

  if (b > a) {
    ans = 'rating';
  }

  if (prev < a && ans !== 'rating') {
    ans = 'unrated';
  }
  else {
    prev = a;
  }

  c++;
});

rl.on('close', () => {
  console.log(ans);
});

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
let prev = Infinity;
let ans = 'maybe';

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

  const [a, b] = d.split(' ').map(Number);

  if (b > a) {
    ans = 'rated';
  }

  if (prev < a && ans !== 'rated') {
    ans = 'unrated';
  }
  else {
    prev = a;
  }

  c++;
});

rl.on('close', () => {
  console.log(ans);
});


Screen resolution of Polycarp's monitor is $$$a \times b$$$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $$$(x, y)$$$ ($$$0 \le x < a, 0 \le y < b$$$). You can consider columns of pixels to be numbered from $$$0$$$ to $$$a-1$$$, and rows — from $$$0$$$ to $$$b-1$$$.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.

In the first line you are given an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. In the next lines you are given descriptions of $$$t$$$ test cases. Each test case contains a single line which consists of $$$4$$$ integers $$$a, b, x$$$ and $$$y$$$ ($$$1 \le a, b \le 10^4$$$; $$$0 \le x < a$$$; $$$0 \le y < b$$$) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that $$$a+b>2$$$ (e.g. $$$a=b=1$$$ is impossible).

Print $$$t$$$ integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.

NoteIn the first test case, the screen resolution is $$$8 \times 8$$$, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.

var toInt = x =>parseInt(x);

var t = parseInt(readline());

for(var tt=0;tt<t;tt++) {
    var abxy = readline().split(' ').map(toInt);
    var c = Math.max(abxy[1]-abxy[3]-1, abxy[3]);
    var r = Math.max(abxy[0]-abxy[2]-1, abxy[2]);

    var best = Math.max(r * abxy[1], abxy[0] * c);
    print(best);
}

const getSquare = ([a, b, x, y]) => Math.max(
  x * b,
  (a - (x + 1)) *b,
  a * y,
  a * (b - (y + 1))
);

const main = (data) => {
  const n = +data[0];

  for (let i = 1; i <= n; i++) {
    console.log(getSquare(data[i].split(' ').map(x => +x)));
  }
};

let data = '';

process.stdin.on('data', input => data += input);
process.stdin.on('end', () => {
  data = data.split('\n');

  main(data);
});

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var a = one[0];
    var b = one[1];
    var x = one[2];
    var y = one[3];
    var list = [(b - y - 1) * a, y * a, b * (a - x - 1), b * x];
    output[i] = Math.max.apply(null, list);
  }
  myout(myconv(output, 9));
}

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) {
        const [a, b, x, y] = data;
        return Math.max(b*x, a*y, a*(b-y-1), b*(a-x-1));

    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let data = lines[testCount].split(" ").map(Number);

        let result = foo(data);
        answer += result +"\n";
        testCount++;
    }
    console.log(answer);
})

let data = '';
process.stdin.on('data', input => data += input);
process.stdin.on('end', () => {
    const inputStrings = data.split('\n');
    const n = parseInt(inputStrings[0], 10);
    const place = ([a,b,x,y]) => Math.max( (a - x - 1) * b, x * b, a * (b - y - 1), a * y);
    let answ = '';
    for (let i = 1; i <= n; i++) {
        const inputArr = inputStrings[i].split(' ').map(Number);
        answ += place(inputArr)+'\n';
    }
    process.stdout.write(answ);
});

let data = '';
process.stdin.on('data', input => data += input);
process.stdin.on('end', () => {
    const inputStrings = data.split('\n');
    const n = parseInt(inputStrings[0], 10);
    const place = ([a,b,x,y]) => Math.max( (a - x - 1) * b, x * b, a * (b - y - 1), a * y);
    for (let i = 1; i <= n; i++) {
        const inputArr = inputStrings[i].split(' ').map(Number);
        process.stdout.write( place(inputArr)+'\n' );
    }
});

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

  const [a, b, x, y] = d.split(" ").map(Number);
  const ans = Math.max(y * a, (b - y - 1) * a, x * b, (a - x - 1) * b);

  if (Number.isInteger(ans)) {
    console.log(ans);
  }
  c++;
});

const processData = (lines) => {
  const num = +lines[0]

  for (let j=0; j<num; j++){
    const [a, b, x, y] = lines[j+1].split(' ').map( x => +x)
    const sq = [ (a-x-1) * (b), (b-y-1) * (a), (x)*b, (y) * a ]
    console.log(Math.max.apply(null, sq));
  }
}

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

function 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, 10); }), w = _a[0], h = _a[1], x = _a[2], y = _a[3];
        console.log(solve(w, h, x, y));
    }
}
function solve(w, h, x, y) {
    return [
        w * (y),
        w * (h - (y + 1)),
        h * (x),
        h * (w - (x + 1))
    ].reduce(function (a, v) { return a > v ? a : v; });
}
(function () {
    var s = "";
    process.stdin.on("data", function (d) { return s += d; });
    process.stdin.on("end", function () { return main(s); });
})();

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

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	let t = nl.num();
    let r = [];
    for(let i = 0; i < t; i++) {
        let [a, b, x, y] = nl.nums();
        let mx = Math.max(x, a - x - 1) * b;
        let my = Math.max(y, b - y - 1) * a;
        r.push(Math.max(mx, my));
    }
    console.log(r.join('\n'));
};

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

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let answer = '';
process.stdin.on('data', inputStdin => {
    let inputStrings = inputStdin.split('\n');
    const n = parseInt(inputStrings[0], 10);
    for (let i = 1; i < inputStrings.length; i++) {
        const inputArr = inputStrings[i].trim().split(' ');
        if (inputArr.length !== 4) break;
        answer += place(inputArr)+'\n';
    }
});
process.stdin.on('end', _ => {
    process.stdout.write( answer );
});
function place(arr) {
    let aW = 0, bW = 0, a = arr[0], b = arr[1], x = arr[2], y = arr[3];
    if (x >= y) {
        bW = b;
        if ( 0.5 * a > x ) {
            aW = a - x - 1;
        } else {
            aW = a;
        }
    } else {
        aW = a;
        if ( 0.5 * b > y ) {
            bW = b - y - 1;
        } else {
            bW = y;
        }
    }
    return aW * bW;
}

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

  const [a, b, x, y] = d.split(" ").map(Number);
  const ans = Math.max(y * a, (b - y - 1) * a, x * b, (a - x - 1) * b);

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


The Government of Mars is not only interested in optimizing space flights, but also wants to improve the road system of the planet.One of the most important highways of Mars connects Olymp City and Kstolop, the capital of Cydonia. In this problem, we only consider the way from Kstolop to Olymp City, but not the reverse path (i. e. the path from Olymp City to Kstolop).The road from Kstolop to Olymp City is $$$\ell$$$ kilometers long. Each point of the road has a coordinate $$$x$$$ ($$$0 \le x \le \ell$$$), which is equal to the distance from Kstolop in kilometers. So, Kstolop is located in the point with coordinate $$$0$$$, and Olymp City is located in the point with coordinate $$$\ell$$$.There are $$$n$$$ signs along the road, $$$i$$$-th of which sets a speed limit $$$a_i$$$. This limit means that the next kilometer must be passed in $$$a_i$$$ minutes and is active until you encounter the next along the road. There is a road sign at the start of the road (i. e. in the point with coordinate $$$0$$$), which sets the initial speed limit.If you know the location of all the signs, it's not hard to calculate how much time it takes to drive from Kstolop to Olymp City. Consider an example:  Here, you need to drive the first three kilometers in five minutes each, then one kilometer in eight minutes, then four kilometers in three minutes each, and finally the last two kilometers must be passed in six minutes each. Total time is $$$3\cdot 5 + 1\cdot 8 + 4\cdot 3 + 2\cdot 6 = 47$$$ minutes.To optimize the road traffic, the Government of Mars decided to remove no more than $$$k$$$ road signs. It cannot remove the sign at the start of the road, otherwise, there will be no limit at the start. By removing these signs, the Government also wants to make the time needed to drive from Kstolop to Olymp City as small as possible.The largest industrial enterprises are located in Cydonia, so it's the priority task to optimize the road traffic from Olymp City. So, the Government of Mars wants you to remove the signs in the way described above.

The first line contains three integers $$$n$$$, $$$\ell$$$, $$$k$$$ ($$$1 \le n \le 500$$$, $$$1 \le \ell \le 10^5$$$, $$$0 \le k \le n-1$$$), the amount of signs on the road, the distance between the cities and the maximal number of signs you may remove. The second line contains $$$n$$$ integers $$$d_i$$$ ($$$d_1 = 0$$$, $$$d_i < d_{i+1}$$$, $$$0 \le d_i \le \ell - 1$$$) — coordinates of all signs. The third line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^4$$$) — speed limits.

Print a single integer — minimal possible time to drive from Kstolop to Olymp City in minutes, if you remove no more than $$$k$$$ road signs.

NoteIn the first example, you cannot remove the signs. So the answer is $$$47$$$, as it's said in the statements above.In the second example, you may remove the second and the fourth sign. In this case, you need to drive four kilometers in $$$4\cdot5 = 20$$$ minutes, and then six kilometers in $$$6\cdot3 = 18$$$, so the total time is $$$4\cdot5 + 6\cdot3 = 38$$$ minutes.

const readline = require('readline')

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

function solve(n, k, len, ps, vs) {
    const dp = []
    let ans = Infinity
    for (let i = 0; i <= n; i++) { // till ith and kept ith
        dp[i] = Array(k + 1).fill(Infinity)
        if (!i) {
            dp[i][k] = 0
            continue
        }
        for (let j = 0; j <= k; j++) { // can removed j more
            for (let prev = 0; prev < i; prev++) {
                const d = (ps[i] || len) - ps[prev]
                // console.log(d)
                if (j + (i - prev - 1) <= k) {
                    dp[i][j] = Math.min(dp[i][j], dp[prev][j + (i - prev - 1)] + vs[prev] * d)
                }
            }
            if (i === n) {
                ans = Math.min(ans, dp[i][j])
            }
        }
    }
    // console.log(dp)
    return ans
}

const readline = require('readline')

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

function solve(n, k, len, ps, vs) {
    // const limit = 1e4
    let prev
    let ans = len * vs[0]
    for (let i = 0; i < n; i++) {
        const dp = {}
        if (!i) {
            dp[vs[0]] = [vs[0] * (ps[1] - ps[0]), 0]
        } else {
            for (let p in prev) {
                const v = +p
                let remove = prev[p][1]
                if (remove < k) {
                    const t = prev[p][0] + ((ps[i + 1] || len) - ps[i]) * v
                    update(dp, v, t, remove + 1)
                    if (i === n - 1) {
                        ans = Math.min(ans, dp[v][0])
                    }
                }
                const t = prev[p][0] + ((ps[i + 1] || len) - ps[i]) * vs[i]
                update(dp, vs[i], t, remove)
                if (i === n - 1) {
                    ans = Math.min(ans, dp[vs[i]][0])
                }
            }
        }
        prev = dp
        // console.log(dp)
    }
    return ans
}
function update(dp, v, t, remove) {
    if (v in dp) {
        if (t < dp[v][0]) {
            dp[v] = [t, remove]
        } else if (t === dp[v]) {
            dp[v] = [t, Math.min(dp[v][1], remove)]
        }
    } else {
        dp[v] = [t, remove]
    }
}

const readline = require('readline')

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

function solve(n, k, len, ps, vs) {
    const limit = 1e4
    let prev
    let ans = len * vs[0]
    for (let i = 0; i < n; i++) {
        const dp = {}
        if (!i) {
            dp[vs[0]] = [vs[0] * (ps[1] - ps[0]), 0]
        } else {
            for (let p in prev) {
                const v = +p
                let remove = prev[p][1]
                if (remove < k) {
                    const t = prev[p][0] + ((ps[i + 1] || len) - ps[i]) * v
                    update(dp, v, t, remove + 1)
                    if (i === n - 1) {
                        ans = Math.min(ans, dp[v][0])
                    }
                }
                const t = prev[p][0] + ((ps[i + 1] || len) - ps[i]) * vs[i]
                update(dp, vs[i], t, remove)
                if (i === n - 1) {
                    ans = Math.min(ans, dp[vs[i]][0])
                }
            }
        }
        prev = dp
        console.log(dp)
    }
    return ans
}
function update(dp, v, t, remove) {
    if (v in dp) {
        if (t < dp[v][0]) {
            dp[v] = [t, remove]
        } else if (t === dp[v]) {
            dp[v] = [t, Math.min(dp[v][1], remove)]
        }
    } else {
        dp[v] = [t, remove]
    }
}

const readline = require('readline')

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

function solve(n, k, len, ps, vs) {
    const limit = 10//1e4
    let prev
    let ans = len * vs[0]
    for (let i = 0; i < n; i++) {
        const dp = {}
        if (!i) {
            dp[vs[0]] = [vs[0] * (ps[1] - ps[0]), 0]
        } else {
            for (let p in prev) {
                const v = +p
                let remove = prev[p][1]
                if (remove < k) {
                    const t = prev[p][0] + ((ps[i + 1] || len) - ps[i]) * v
                    update(dp, v, t, remove + 1)
                    if (i === n - 1) {
                        ans = Math.min(ans, dp[v][0])
                    }
                }
                const t = prev[p][0] + ((ps[i + 1] || len) - ps[i]) * vs[i]
                update(dp, vs[i], t, remove)
                if (i === n - 1) {
                    ans = Math.min(ans, dp[vs[i]][0])
                }
            }
        }
        prev = dp
        // console.log(dp)
    }
    return ans
}
function update(dp, v, t, remove) {
    if (v in dp) {
        if (t < dp[v][0]) {
            dp[v] = [t, remove]
        } else if (t === dp[v]) {
            dp[v] = [t, Math.min(dp[v][1], remove)]
        }
    } else {
        dp[v] = [t, remove]
    }
}

const readline = require('readline')

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

function solve(n, k, len, ps, vs) {
    const limit = ps.map((x, i) => [i, x, vs[i]]) // pos, limit
    limit.shift()
    limit.sort((a, b) => b[2] - a[2])
    const skip = []
    for (let i = 0; i < limit.length && i < k; i++) {
        if (limit[i][2] <= vs[0]) break
        skip[limit[i][0]] = 1
    }
// console.log(skip)
    let ans = 0
    let v = vs[0]
    let prev = 0
    for (let i = 1; i < n; i++) {
        if (!skip[i]) {
            ans += v * (ps[i] - prev)
            v = vs[i]
            prev = ps[i]
        }
    }
    ans += v * (len - prev)
    return ans
}

const readline = require('readline')

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

function solve(n, k, len, ps, vs) {
    const limit = ps.map((x, i) => [i, x, vs[i]]) // pos, limit
    limit.shift()
    limit.sort((a, b) => b[2] - a[2])
    const skip = []
    for (let i = 0; i < limit.length && i < k; i++) {
        skip[limit[i][0]] = 1
    }
// console.log(skip)
    let ans = 0
    let v = vs[0]
    let prev = 0
    for (let i = 1; i < n; i++) {
        if (!skip[i]) {
            ans += v * (ps[i] - prev)
            v = vs[i]
            prev = ps[i]
        }
    }
    ans += v * (len - prev)
    return ans
}

const readline = require('readline')

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

function solve(n, k, len, ps, vs) {
    let ans = 0
    // const signs = {}
    for (let i = 0; i < n; i++) {
        ans += vs[i] * ((ps[i + 1] || len) - ps[i])
        // if (i) signs[i] = 1
    }
    let limit = ps.map((x, i) => [x, vs[i]]) // pos, limit
    limit.shift()
    // console.log(limit)
    while (k--) {
        // const arr = []
        // for (let i in signs) {
        //     if (signs[i]) {
        //         arr.push(i)
        //     }
        // }
        const sorted = limit.map(([pos, v], i) => {
            const d = ((i + 1 < limit.length ? limit[i + 1][0] : len) - pos)
                * ((i ? limit[i - 1][1] : vs[0]) - v)
            return [i, d]
        }).sort((a, b) => a[1] - b[1])
    // console.log(sorted)
        ans += sorted[0][1]
        limit = limit.filter((x, i) => i !== sorted[0][0])
        // console.log(limit)
    }
    return ans
}


The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition.Teams plan to train for n times during n consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be ai teams on the i-th day.There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two consecutive days (two pizzas in total).As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days.Sereja wants to order exactly ai pizzas on the i-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day n.

The first line of input contains a single integer n (1 ≤ n ≤ 200 000) — the number of training sessions. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 10 000) — the number of teams that will be present on each of the days.

If there is a way to order pizzas using only coupons and discounts and do not buy any extra pizzas on any of the days, then print "YES" (without quotes) in the only line of output. Otherwise, print "NO" (without quotes).

NoteIn the first sample, Sereja can use one coupon to buy one pizza on the first and the second days, one coupon to buy pizza on the second and the third days and one discount to buy pizzas on the fourth days. This is the only way to order pizzas for this sample.In the second sample, Sereja can't use neither the coupon nor the discount without ordering an extra pizza. Note, that it's possible that there will be no teams attending the training sessions on some days.

function extremeCouponing (days, teams) {

  if (days === 1) { if (teams[0] % 2 === 0) return "YES"; else return "NO"; }
  // day 'd' pizza count consists of discounts, evenCoupons[d] and evenCoupons[d-1]. discounts always mean
  // an even number of pizzas. this means: an even total pizzas per day -> even number of coupons
  // and an odd total pizzas per day -> odd number of coupons
  // coupons can be either used on that day or on the previous day though, so take that into account

  var evenCoupons = []; evenCoupons[days-1] = true; // evenCoupons stores whether a given day's coupon count is even or odd.
  // You cant use any coupons on the last day due to wastage so its coupon count is 0 -> even

  // if last day teams is ODD, you must use odd number of coupons on previous day. if EVEN, you must use even (incl 0) coupons on previous day
  evenCoupons[days-2] = (teams[days-1] % 2 === 0);
  // if first day team count is ODD, you must use odd number of coupons on that day. if EVEN, you must use even (incl 0) coupons that day
  evenCoupons[0] = (teams[0] % 2 === 0);

  // iterate from first to 2nd-to-last day
  for (var d=0; d <=days-2; d++) {

      // if ODD coupons on this day, and following day team total is ODD, then following day uses EVEN coupons
      // if EVEN coupons on this day and following day team total is EVEN, then following day uses EVEN coupons
      // otherwise the following day uses ODD coupons
      evenCoupons[d+1] = (evenCoupons[d] === (teams[d+1] % 2 === 0));

      // if this day uses an odd number of coupons and the following day has no pizzas, then a pizza is wasted and the solution is NO
      if (evenCoupons[d] === false && teams[d+1] === 0) return "NO";
  }

  // last day coupon count cant be ODD (because it must be 0) so if this gets switched on, return "NO" immediately
  if (evenCoupons[days-1] === false) return "NO";
  if (evenCoupons[days-2] !== (teams[days-1] % 2 === 0)) return "NO";

  // iterate from last day to 2nd
  for (var bd=days-1; bd> 0; bd--) {

    // if ODD team total on this day and combined coupons of d & d-1 are ODD, ok. if combined EVEN, NNNNNOOO!!!
    // if EVEN team total on this day and combined coupons of d & d-1 are EVEN, ok. if combined ODD, NNNNNOOO!!!
    if (teams[bd] % 2 !== 0 && evenCoupons[bd] === evenCoupons[bd-1]) return "NO";
    if (teams[bd] % 2 === 0 && evenCoupons[bd] !== evenCoupons[bd-1]) return "NO";
  }

  return "YES";
}

var s1 = parseInt(readline());
var s2 = readline().split(" ");
for (var i=0; i < s2.length; i++) {
    s2[i] = parseInt(s2[i]);
}

print (extremeCouponing(s1, s2));

function extremeCouponing (days, teams) {

  var evenCoupons = []; evenCoupons[days-1] = true;
  evenCoupons[0] = (teams[0] % 2 === 0);
  evenCoupons[days-2] = (teams[days-1] % 2 === 0);

  for (var d=0; d <=days-2; d++) {
      evenCoupons[d+1] = (evenCoupons[d] === (teams[d+1] % 2 === 0));
      if (evenCoupons[d] === false && teams[d+1] === 0) return "NO";
  }

  if (evenCoupons[days-1] === false) return "NO";
  for (var bd=days-1; bd> 0; bd--) {
    if (teams[bd] % 2 !== 0 && evenCoupons[bd] === evenCoupons[bd-1]) return "NO";
    if (teams[bd] % 2 === 0 && evenCoupons[bd] !== evenCoupons[bd-1]) return "NO";
  }
  return "YES";
}

var s1 = parseInt(readline());
var s2 = readline().split(" ");
for (var i=0; i < s2.length; i++) {
    s2[i] = parseInt(s2[i]);
}

print (extremeCouponing(s1, s2));


You are given a string $$$s$$$ consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: res = 0for init = 0 to inf    cur = init    ok = true    for i = 1 to |s|        res = res + 1        if s[i] == '+'            cur = cur + 1        else            cur = cur - 1        if cur < 0            ok = false            break    if ok        breakNote that the $$$inf$$$ denotes infinity, and the characters of the string are numbered from $$$1$$$ to $$$|s|$$$.You have to calculate the value of the $$$res$$$ after the process ends.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only lines of each test case contains string $$$s$$$ ($$$1 \le |s| \le 10^6$$$) consisting only of characters + and -. It's guaranteed that sum of $$$|s|$$$ over all test cases doesn't exceed $$$10^6$$$.

For each test case print one integer — the value of the $$$res$$$ after the process ends.

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 => string.trim());

    main();
});

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

const s2i = s => parseInt(s, 10);

function main() {
  let T = s2i(readLine());
  let out = '';
  while (T--) {
    const s = readLine()
    let sum = 0;
    let res = 0;
    for (let i = 0, l = s.length; i < l; i++) {
      const c = s.charAt(i);
      res++;
      if (c === '+') {
        sum++;
      }
      else {
        sum--;
        if (sum < 0) {
          sum = 0;
          res += i + 1;
        }
      }
    }

    out += res + '\n'
  }
  console.log(out)
}

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

let inputString = '';
let currentLine = 0;

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

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

    B();
});

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

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

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

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        if(n % 2 === 0){
            console.log('YES');
        }else{
            console.log('NO');
        }
    }
}

function D(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,k] = ti(readline().split(' '));
        let a = ti(readline().split(' '));
        let b = new Array(n);
        for(let i = 0; i < n; i++){
            let mod = a[i] % k;
            if(mod !== 0){
                mod = k-mod;
            }
            b[i] = [a[i], mod];
        }
        b.sort((c,d) => c[1]-d[1]);
        let count = 0;
        let x = 0;
        for(let i = 0; i < n; i++){
            if((b[i][0] + x) % k === 0){
                x += 1;
                count += 1;
            }else{
                let d = k-((b[i][0]+x)%k);
                x += d+1;
                count += d+1;
            }
        }

        console.log(count);
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let s = readline().split('');
        let res = 0;
        let x = 0;
        for(let i = 0; i < s.length; i++){
            if(s[i] === '+') x++;
            if(s[i] === '-') x--;

            if(x < 0){
                res += i+1;
                x = 0;
            }
        }

        console.log(res + s.length);
    }
}

const readline = require('readline');

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

var lineCount = 0
var testCount = 0
var outputStr = ''

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if (lineCount >= testCount) {
        outputStr += getWinner(input) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += getWinner(input) + '\n'
    }
    lineCount++
});

// console.log(getWinner('++----++-'))

function getWinner(str) {
    var sum = 0;
    var minsum = 0;
    var res = 0;
    var minindex = 0;
    for (var i = 0; i < str.length; i++) {
        if (str[i] == '+') {
            sum += 1
        }
        else {
            sum -= 1
        }
        if (sum < minsum) {
            res += i + 1
            minsum = sum
            minindex = i
        }
    }
    res += i
    return res
}

t = +readline();
while(t--) {
  input = readline();
  res = input.length;
  mn = 0;
  cur = 0;
  for(i = 0;i < input.length; i++) {
    if (input[i] === '+') {
          cur = cur + 1;
      } else
          cur = cur - 1;
      if (cur < mn) {
          mn = cur;
          res += i + 1;
      }
  }
  print(res);

}

function solve() {
   var T = Number(read());
   for (var t = 0; t < T; t++) {
      var s = read();
      var sum = 0;
      var wait = -1;
      var ans = s.length;
      for (var i = 0; i < s.length; i++) {
         sum += s[i] === '+' ? 1 : -1;
         if (sum === wait) {
            ans += i + 1;
            wait--;
         }
      }
      write(ans);
   }
}

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;
   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');
         solve();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', solve);
   }
} else {
   solve();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

var Tc = parseInt(readline());
while (Tc-- > 0) {
  var s = readline();
  var sum = 0;
  var m = -1;
  var ans = s.length;
  for (var i = 0; i < s.length; i++) {
    sum += s[i] === "+" ? 1 : -1;
    if (sum === m) {
      ans += i + 1;
      m--;
    }
  }
  print(ans);
}

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

let inputString = '';
let currentLine = 0;

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

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

    B();
});

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

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

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

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        if(n % 2 === 0){
            console.log('YES');
        }else{
            console.log('NO');
        }
    }
}

function D(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,k] = ti(readline().split(' '));
        let a = ti(readline().split(' '));
        let b = new Array(n);
        for(let i = 0; i < n; i++){
            let mod = a[i] % k;
            if(mod !== 0){
                mod = k-mod;
            }
            b[i] = [a[i], mod];
        }
        b.sort((c,d) => c[1]-d[1]);
        let count = 0;
        let x = 0;
        for(let i = 0; i < n; i++){
            if((b[i][0] + x) % k === 0){
                x += 1;
                count += 1;
            }else{
                let d = k-((b[i][0]+x)%k);
                x += d+1;
                count += d+1;
            }
        }

        console.log(count);
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let s = readline().split('');
        let a = new Array(10);
        let x = 0;
        for(let i = 0; i < s.length; i++){
            if(s[i] === '+')
                x += 1;
            else
                x -= 1;

            if(x < 0){
                if(a[-1*x-1] === undefined)
                    a[-1*x-1] = i+1;
            }
        }

        let res = 0;
        for(let i = 0; i < Math.abs(x); i++){
            if(a[i])
                res += a[i];
        }

        console.log(res + s.length);
    }
}

const readline = require('readline');

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

var lineCount = 0
var testCount = 0
var outputStr = ''

rl.on('line', (input) => {
    if (lineCount == 0) {
        // first line
        testCount = parseInt(input)
    }
    else if (lineCount >= testCount) {
        outputStr += getWinner(input) + '\n'
        console.log(outputStr)
        rl.close()
    }
    else {
        // data
        outputStr += getWinner(input) + '\n'
    }
    lineCount++
});

// console.log(getWinner('++--+-'))

function getWinner(str) {
    var sum = 0;
    var minsum = 0;
    var res = 0;
    var minindex = 0;
    for (var i = 0; i < str.length; i++) {
        if (str[i] == '+') {
            sum += 1
        }
        else {
            sum -= 1
        }
        // console.log(minsum, sum)
        if(sum<minsum){
            minsum = sum
            minindex = i
        }
        if (sum <= minsum && sum<0) {
            res += i + 1
        }
    }
    if(minindex == str.length-1||minindex==0){
        res+=i
    }
    return res
}