Monocarp is playing a computer game once again. He is a wizard apprentice, who only knows a single spell. Luckily, this spell can damage the monsters.The level he's currently on contains $$$n$$$ monsters. The $$$i$$$-th of them appears $$$k_i$$$ seconds after the start of the level and has $$$h_i$$$ health points. As an additional constraint, $$$h_i \le k_i$$$ for all $$$1 \le i \le n$$$. All $$$k_i$$$ are different.Monocarp can cast the spell at moments which are positive integer amounts of second after the start of the level: $$$1, 2, 3, \dots$$$ The damage of the spell is calculated as follows. If he didn't cast the spell at the previous second, the damage is $$$1$$$. Otherwise, let the damage at the previous second be $$$x$$$. Then he can choose the damage to be either $$$x + 1$$$ or $$$1$$$. A spell uses mana: casting a spell with damage $$$x$$$ uses $$$x$$$ mana. Mana doesn't regenerate.To kill the $$$i$$$-th monster, Monocarp has to cast a spell with damage at least $$$h_i$$$ at the exact moment the monster appears, which is $$$k_i$$$.Note that Monocarp can cast the spell even when there is no monster at the current second.The mana amount required to cast the spells is the sum of mana usages for all cast spells. Calculate the least amount of mana required for Monocarp to kill all monsters.It can be shown that it's always possible to kill all monsters under the constraints of the problem.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of the testcase contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of monsters in the level. The second line of the testcase contains $$$n$$$ integers $$$k_1 < k_2 < \dots < k_n$$$ ($$$1 \le k_i \le 10^9$$$) — the number of second from the start the $$$i$$$-th monster appears at. All $$$k_i$$$ are different, $$$k_i$$$ are provided in the increasing order. The third line of the testcase contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le k_i \le 10^9$$$) — the health of the $$$i$$$-th monster. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^4$$$.

For each testcase, print a single integer — the least amount of mana required for Monocarp to kill all monsters.

NoteIn the first testcase of the example, Monocarp can cast spells $$$3, 4, 5$$$ and $$$6$$$ seconds from the start with damages $$$1, 2, 3$$$ and $$$4$$$, respectively. The damage dealt at $$$6$$$ seconds is $$$4$$$, which is indeed greater than or equal to the health of the monster that appears.In the second testcase of the example, Monocarp can cast spells $$$3, 4$$$ and $$$5$$$ seconds from the start with damages $$$1, 2$$$ and $$$3$$$, respectively.In the third testcase of the example, Monocarp can cast spells $$$4, 5, 7, 8$$$ and $$$9$$$ seconds from the start with damages $$$1, 2, 1, 1$$$ and $$$2$$$, respectively.

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;
function readline() {
    return lines[rli++];
}

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

function div(val, by){
    return (val - val % by) / by;
}

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (n, k, h)=>{
    let result = 0n;

    let intervals = [];

    for (let i = 0; i < n; i++) {
        intervals.push([k[i] - h[i], k[i]]);
    }
    intervals = intervals.sort((i1, i2) => {
        let x = i1[0] - i2[0];
        if (x === 0) {
            return i1[1] - i2[1];
        } else {
            return x;
        }
    })

    let [l, r] = intervals[0];

    for (let i = 1; i < intervals.length; i++) {
        let [curL, curR] = intervals[i];
        if (curL < r) {
            r = Math.max(r, curR);
        } else {
            result += sumab(1, r - l);
            l = curL;
            r = curR;
        }
    }
    result += sumab(1, r - l);

    return result;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let k = ra();
        let h = ra();
        console.log(`${calc(n, k, h)}`);
    }
}

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const k = rna();
		const h = rna();

		const st = [];
		for (let i = 0; i < n; i++) {
			const [L, R] = [k[i] - h[i] + 1, k[i]];

			while (st.length) {
				const [l, r] = st.pop();
				if (L > r) {
					st.push([l, r]);
					st.push([L, R]);
					break;
				} else if (L < l) {
					continue;
				} else if (L >= l) {
					st.push([l, R]);
					break;
				}
			}

			if (!st.length) {
				st.push([L, R]);
			}
		}

		let ans = 0n;
		for (const [l, r] of st) {
			ans += BigInt(r - l + 1) * BigInt(r - l + 2) / 2n;
		}

		console.log(ans.toString());
	}
}

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;
function readline() {
    return lines[rli++];
}

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

function div(val, by){
    return (val - val % by) / by;
}

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (n, k, h)=>{
    let result = 0n;

    let intervals = [];

    for (let i = 0; i < n; i++) {
        intervals.push([k[i] - h[i], k[i]]);
    }
    intervals = intervals.sort((i1, i2) => {
        let x = i1[0] - i2[0];
        if (x === 0) {
            return i1[1] - i2[1];
        } else {
            return x;
        }
    })

    for (let i = 1; i < intervals.length; i++) {
        let cur = intervals[i], prev = intervals[i - 1];
        if (cur[0] < prev[1]) {
            cur[0] = prev[0];
            cur[1] = Math.max(prev[1], cur[1]);
            intervals.shift();
            i--;
        }
    }

    for (let i = 0; i < intervals.length; i++) {
        let cur = intervals[i];
        result += sumab(1, cur[1] - cur[0]);
    }
    return result;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let k = ra();
        let h = ra();
        console.log(`${calc(n, k, h)}`);
    }
}

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const k = rna();
		const h = rna();

		const st = [];
		for (let i = 0; i < n; i++) {
			const [L, R] = [k[i] - h[i] + 1, k[i]];

			while (st.length) {
				const [l, r] = st.pop();
				if (L > r) {
					st.push([l, r]);
					st.push([L, R]);
					break;
				} else if (L < l) {
					continue;
				} else if (L >= l) {
					st.push([l, R]);
					break;
				}
			}

			if (!st.length) {
				st.push([L, R]);
			}
		}

		let ans = 0;
		for (const [l, r] of st) {
			ans += (r - l + 1) * (r - l + 2) / 2;
		}

		console.log(ans);
	}
}


The robot is placed in the top left corner of a grid, consisting of $$$n$$$ rows and $$$m$$$ columns, in a cell $$$(1, 1)$$$.In one step, it can move into a cell, adjacent by a side to the current one:   $$$(x, y) \rightarrow (x, y + 1)$$$;  $$$(x, y) \rightarrow (x + 1, y)$$$;  $$$(x, y) \rightarrow (x, y - 1)$$$;  $$$(x, y) \rightarrow (x - 1, y)$$$. The robot can't move outside the grid.The cell $$$(s_x, s_y)$$$ contains a deadly laser. If the robot comes into some cell that has distance less than or equal to $$$d$$$ to the laser, it gets evaporated. The distance between two cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ is $$$|x_1 - x_2| + |y_1 - y_2|$$$.Print the smallest number of steps that the robot can take to reach the cell $$$(n, m)$$$ without getting evaporated or moving outside the grid. If it's not possible to reach the cell $$$(n, m)$$$, print -1.The laser is neither in the starting cell, nor in the ending cell. The starting cell always has distance greater than $$$d$$$ to the laser.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The only line of each testcase contains five integers $$$n, m, s_x, s_y, d$$$ ($$$2 \le n, m \le 1000$$$; $$$1 \le s_x \le n$$$; $$$1 \le s_y \le m$$$; $$$0 \le d \le n + m$$$) — the size of the grid, the cell that contains the laser and the evaporating distance of the laser. The laser is neither in the starting cell, nor in the ending cell ($$$(s_x, s_y) \neq (1, 1)$$$ and $$$(s_x, s_y) \neq (n, m)$$$). The starting cell $$$(1, 1)$$$ always has distance greater than $$$d$$$ to the laser ($$$|s_x - 1| + |s_y - 1| > d$$$).

For each testcase, print a single integer. If it's possible to reach the cell $$$(n, m)$$$ from $$$(1, 1)$$$ without getting evaporated or moving outside the grid, then print the smallest amount of steps it can take the robot to reach it. Otherwise, print -1.

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

function distance(ax, ay, bx, by) {
    return Math.abs(ax - bx) + Math.abs(ay - by);
}

function solve([n, m, sx, sy, d]) {
    if (distance(n, m, sx, sy) <= d) {
        return -1;
    }

    // compute vertical block
    if (distance(sx, 1, sx, sy) <= d && distance(sx, m, sx, sy) <= d) {
        return -1;
    }

    // compute horizontal block
    if (distance(1, sy, sx, sy) <= d && distance(n, sy, sx, sy) <= d) {
        return -1;
    }

    if (distance(sx, m, sx, sy) <= d && distance(n, sy, sx, sy) <= d) {
        return -1;
    }

    if (distance(sx, 1, sx, sy) <= d && distance(1, sy, sx, sy) <= d) {
        return -1;
    }

    return n - 1 + m - 1;
}

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (let i = 1; i < lines.length; i += 1) {
        const solution = solve(lines[i].split(' ').map(Number))
        process.stdout.write(String(solution) + '\n');
    }
});

var inputString = [], currentLine = 0;
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var readline = require('readline');
var rl = readline.createInterface(process.stdin);
rl.on('line', line => { inputString.push(line) });
process.stdin.on('end', () => {  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[0], arr[1], arr[2], arr[3], arr[4]);
        console.log(result);
    }
}

function myFunc(l, c, sx, sy, d){

    if(sy + d >= c && sy - d <= 1) return -1; //ocupa toda linha
    if(sx + d >= l && sx - d <= 1) return -1; //ocupa toda coluna

    if(sy + d >= c && sx + d >= l) return -1; // contorna objetivo
    if(sy - d <= 1 && sx - d <= 1) return -1; // contorna jogador

    return l + c - 2;

}

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[0], arr[1], arr[2], arr[3], arr[4]);
        console.log(result);
    }
}

function myFunc(l, c, sx, sy, d){

    if(sy + d >= c && sy - d <= 1) return -1; //ocupa toda linha
    if(sx + d >= l && sx - d <= 1) return -1; //ocupa toda coluna

    if(sy + d >= c && sx + d >= l) return -1; // contorna objetivo
    if(sy - d <= 1 && sx - d <= 1) return -1; // contorna jogador

    return l + c - 2;

}

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

/***
Educational Codeforces Round 134 (Div. 2)
2022-08-26

B. Deadly Laser
***/

function main() {
  // INPUT: Number of test cases
  let t = readline();
  t = parseInt(t);
  for (let tc = 0; tc < t; tc++) {
    // INPUT: grid size (n, m); laser at (sx, sy); range d
    let args = readline();
    args = args.split(" ");
    args = args.map((k) => parseInt(k));
    const [n, m] = args.slice(0, 2);

    if (badLaser(...args)) {
      console.log(-1);
    } else {
      // number of steps will always be the same
      // if it is possible robot can always take
      // either right->down or down->right the whole board
      console.log(n + m - 2);
    }
  }
}

// Manhattan distance between 2 points
function manDist(x1, y1, x2, y2) {
  return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}

// Is the route impossible?
function badLaser(n, m, sx, sy, d) {
  return (
    (sx - 1 <= d && sy - 1 <= d) ||
    (n - sx <= d && m - sy <= d) ||
    (sx - 1 <= d && n - sx <= d) ||
    (m - sy <= d && sy - 1 <= d)
  );
}

let fs = require("fs");
let sc = {
    _buf: new Buffer.alloc(1 << 14),
    _bufPos: 0,
    _bufLen: 0,
    _ensure: function ()
    {
        if (this._bufPos === this._bufLen)
        {
            this._bufPos = 0;
            this._bufLen = fs.readSync(0, this._buf, 0, this._buf.length, null);
        }
    },
    _isws: function (ch)
    {
        return ch === 32 || ch === 9 || ch === 10 || ch === 13;
    },
    _islf: function (ch)
    {
        return ch === 10 || ch === 13;
    },
    _peekChar: function ()
    {
        this._ensure();
        return this._bufPos === this._bufLen ? 0 : this._buf[this._bufPos];
    },
    _skipWs: function ()
    {
        while (this._isws(this._peekChar()))
            this._bufPos++;
    },
    _readUntil: function (stop)
    {
        this._ensure();
        if (this._bufPos === this._bufLen)
            throw new Error("eof");
        let start = this._bufPos;
        let before = null;
        for (; ;)
        {
            if (this._bufPos === this._bufLen)
            {
                let len = this._bufPos - start, preLen = (before ? before.length : 0);
                let nbuf = new Buffer(len + preLen);
                if (before)
                    before.copy(nbuf);
                before = nbuf;
                this._buf.copy(before, preLen, start);
                this._ensure();
                start = this._bufPos;
            }
            if (this._bufPos === this._bufLen || stop(this._buf[this._bufPos])) break;
            this._bufPos++;
        }
        if (!before)
            return this._buf.toString("utf8", start, this._bufPos);
        let after = this._buf.slice(start, this._bufPos);
        let res = new Buffer(before.length + after.length);
        before.copy(res);
        after.copy(res, before.length);
        return res.toString();
    },

    nextToken: function ()
    {
        this._skipWs();
        return this._readUntil(this._isws);
    },
    L: function ()
    {
        let line = this._readUntil(this._islf);
        if (this._peekChar() === 13) this._bufPos++;
        if (this._peekChar() === 10) this._bufPos++;
        return line;
    },
    N: function ()
    {
        return +this.nextToken();
    },
    S: function ()
    {
        return this.nextToken();
    }
};

// DO NOT CHANGE TEMPLATE BEFORE

const Def = Number(1e9);

const Solve = () =>
{
    let n = sc.N(), m = sc.N(), sx = sc.N(), sy = sc.N(), d = sc.N();

    // console.log(`n = ${n} and m = ${m} and sx = ${sx} and sy = ${sy} and d = ${d}`);

    if ((sx + d >= n && sy + d >= m) || (sx - d <= 1 && sy - d <= 1) || (sx + d >= n && sx - d <= 1) || (sy + d >= m && sy - d <= 1))
    {
        console.log(-1);
        return;
    }

    // if ((sx + d >= n && sx - d <= 1) || (sy + d >= m && sy - d <= 1))
    // {
    //     console.log(-1);
    //     return;
    // }

    console.log(n + m - 2);

    // let arr = new Array(n).fill(new Array(m).fill(0));

    // arr[sx - 1][sy - 1] = 1;
    //
    // for (let i = 0; i < n; ++i)
    // {
    //     for (let j = 0; j < m; ++j)
    //     {
    //         console.log(arr[i][j]);
    //     }
    // }

}

const main = () =>
{
    let cases = sc.N();
    while (cases-- > 0) Solve();

    // Solve();
}
main();

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, m, sx, sy, d] = input[index]
      .split(" ")
      .map((item) => parseInt(item));
    const testCase = {
      n,
      m,
      sx,
      sy,
      d,
    };

    testCases.push(testCase);
  }
}

function solution(testCase) {
  const { n, m, sx, sy, d } = testCase;

  if (
    (sy - d <= 1 && sy + d >= m) ||
    (sx - d <= 1 && sx + d >= n) ||
    (sx + d >= n && sy + d >= m) ||
    (sx - d <= 1 && sy - d <= 1)
  )
    console.log(-1);
  else {
    console.log(n - 1 + m - 1);
  }
}

parseInput();

testCases.forEach(solution);

const readline = require('readline')

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

function solve(n, m, sx, sy, d) {
    sx--; sy--
    if (!ok(0, 0) || !ok(n - 1, m - 1)) return -1
    const top = !ok(0, sy)
    const bottom = !ok(n - 1, sy)
    const left = !ok(sx, 0)
    const right = !ok(sx, m - 1)
    if (top && bottom || top && left
        || bottom && right || left && right) return -1
    return n + m - 2
    function ok(i, j) {
        return Math.abs(sx - i) + Math.abs(sy - j) > d
    }
}

var repeatTimes = readline();

while (repeatTimes--) {
    var a = readline().split(' ')
    var n = parseInt(a[0])
    var m = parseInt(a[1])
    var sx = parseInt(a[2])
    var sy = parseInt(a[3])
    var d = parseInt(a[4])
    if(((sx - d <= 1 || sy + d >= m) && (sx + d >= n || sy - d <= 1)))
				print(-1);
			else
				print(n+m-2);
}

var tests = parseInt(readline());
    var n, m, sx, sy, d;

    for (var t=0; t < tests; t++) {
        var a = readline().split(' ').map(x=>parseInt(x));
        n = a[0];
        m = a[1];
        sx = a[2];
        sy = a[3];
        d = a[4];

        if ((sx - d <= 1 && sy - d <= 1) || (sx + d >= n && sy + d >= m)
        || (sx - d <= 1 && sx + d >= n ) || ( sy - d <= 1 && sy + d >= m)) {
            print(-1);
            continue;
        }
        print(n + m - 2);
    }

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

function distance(ax, ay, bx, by) {
    return Math.abs(ax - bx) + Math.abs(ay - by);
}

function solve([n, m, sx, sy, d]) {
    if (distance(n, m, sx, sy) <= d) {
        return -1;
    }

    // compute vertical block
    // if (distance(sx, 1, sx, sy) <= d && distance(sx, m, sx, sy) <= d) {
    //     return -1;
    // }

    // compute horizontal block
    // if (distance(1, sy, sx, sy) <= d && distance(n, sy, sx, sy) <= d) {
    //     return -1;
    // }

    if (distance(sx, m, sx, sy) <= d && distance(n, sy, sx, sy) <= d) {
        return -1;
    }

    return n - 1 + m - 1;
}

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (let i = 1; i < lines.length; i += 1) {
        const solution = solve(lines[i].split(' ').map(Number))
        process.stdout.write(String(solution) + '\n');
    }
});

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

function distance(ax, ay, bx, by) {
    return Math.abs(ax - bx) + Math.abs(ay - by);
}

function solve([n, m, sx, sy, d]) {
    if (distance(n, m, sx, sy) <= d) {
        return -1;
    }

    // compute vertical block
    if (distance(sx, 1, sx, sy) <= d && distance(sx, m, sx, sy) <= d) {
        return -1;
    }

    // compute horizontal block
    if (distance(1, sy, sx, sy) <= d && distance(n, sy, sx, sy) <= d) {
        return -1;
    }

    if (distance(sx, m, sx, sy) <= d && distance(n, sy, sx, sy) <= d) {
        return -1;

    }

    return n - 1 + m - 1;
}

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (let i = 1; i < lines.length; i += 1) {
        const solution = solve(lines[i].split(' ').map(Number))
        process.stdout.write(String(solution) + '\n');
    }
});

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

function distance(ax, ay, bx, by) {
    return Math.abs(ax - bx) + Math.abs(ay - by);
}

function solve([n, m, sx, sy, d]) {
    if (distance(n, m, sx, sy) <= d) {
        return -1;
    }

    // compute vertical block
    // if (distance(sx, 1, sx, sy) <= d && distance(sx, m, sx, sy) <= d) {
    //     return -1;
    // }

    // compute horizontal block
    // if (distance(1, sy, sx, sy) <= d && distance(n, sy, sx, sy) <= d) {
    //     return -1;
    // }

    return n - 1 + m - 1;
}

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (let i = 1; i < lines.length; i += 1) {
        const solution = solve(lines[i].split(' ').map(Number))
        process.stdout.write(String(solution) + '\n');
    }
});

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

function distance(ax, ay, bx, by) {
    return Math.abs(ax - bx) + Math.abs(ay - by);
}

function solve([n, m, sx, sy, d]) {
    if (distance(n, m, sx, sy) <= d) {
        return -1;
    }

    // compute vertical block
    if (distance(sx, 1, sx, sy) <= d && distance(sx, m, sx, sy) <= d) {
        return -1;
    }

    // compute horizontal block
    if (distance(1, sy, sx, sy) <= d && distance(n, sy, sx, sy) <= d) {
        return -1;
    }

    return n - 1 + m - 1;
}

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (let i = 1; i < lines.length; i += 1) {
        const solution = solve(lines[i].split(' ').map(Number))
        process.stdout.write(String(solution) + '\n');
    }
});

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

function distance(ax, ay, bx, by) {
    return Math.abs(ax - bx) + Math.abs(ay - by);
}

function solve([n, m, sx, sy, d]) {
    if (distance(m, n, sx, sy) <= d) {
        return -1;
    }

    // compute vertical block
    if (distance(sx, 1, sx, sy) <= d && distance(sx, n, sx, sy) <= d) {
        return -1;
    }

    // compute horizontal block
    if (distance(1, sy, sx, sy) <= d && distance(m, sy, sx, sy) <= d) {
        return -1;
    }

    return n - 1 + m - 1;
}

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (let i = 1; i < lines.length; i += 1) {
        const solution = solve(lines[i].split(' ').map(Number))
        process.stdout.write(String(solution) + '\n');
    }
});

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

function distance(ax, ay, bx, by) {
    return Math.abs(ax - bx) + Math.abs(ay - by);
}

function solve([n, m, sx, sy, d]) {
    if (distance(n, m, sx, sy) <= d) {
        return -1;
    }

    // compute vertical block
    if (distance(sx, 1, sx, sy) <= d && distance(sx, n, sx, sy) <= d) {
        return -1;
    }

    // compute horizontal block
    if (distance(1, sy, sx, sy) <= d && distance(m, sy, sx, sy) <= d) {
        return -1;
    }

    return n - 1 + m - 1;
}

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (let i = 1; i < lines.length; i += 1) {
        const solution = solve(lines[i].split(' ').map(Number))
        process.stdout.write(String(solution) + '\n');
    }
});

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

function distance(ax, ay, bx, by) {
    return Math.abs(ax - bx) + Math.abs(ay - by);
}

function solve([n, m, sx, sy, d]) {
    if (d === 0) {
        return n - 1 + m - 1;
    }

    if (distance(n, m, sx, sy) <= d) {
        return -1;
    }

    // compute vertical block
    if (distance(sx, 1, sx, sy) <= d && distance(sx, m, sx, sy) <= d) {
        return -1;
    }

    // compute horizontal block
    if (distance(1, sy, sx, sy) <= d && distance(n, sy, sx, sy) <= d) {
        return -1;
    }

    return n - 1 + m - 1;
}

var input = '';
process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n');
    for (let i = 1; i < lines.length; i += 1) {
        const solution = solve(lines[i].split(' ').map(Number))
        process.stdout.write(String(solution) + '\n');
    }
});

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[0], arr[1], arr[2], arr[3], arr[4]);
        console.log(result);
    }
}

function myFunc(l, c, sx, sy, d){

    if(sy + d >= c && sy - d <= 1) return -1;
    if(sx + d >= l && sx - d <= 1) return -1;

    // if(sx == l && sy + d >= c) return -1;
    // if(sy == c && sx + d >= l) return -1;

    if(sy + d >= c && sx + d >= l) return -1;
    if(sy + d <= 1 && sx + d <= 1) return -1;

    return l + c - 2;

}

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[0], arr[1], arr[2], arr[3], arr[4]);
        console.log(result);
    }
}

function myFunc(l, c, sx, sy, d){

    if(sy + d >= c && sy - d <= 1) return -1;
    if(sx + d >= l && sx - d <= 1) return -1;

    if(sx == l && sy + d >= c) return -1;
    if(sy == c && sx + d >= l) return -1;

    if(sy + d >= c && sx + d >= l) return -1;

    return l + c - 2;

}

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[0], arr[1], arr[2], arr[3], arr[4]);
        console.log(result);
    }
}

function myFunc(l, c, sx, sy, d){

    if(sy + d >= c && sy - d <= 1) return -1;
    if(sx + d >= l && sx - d <= 1) return -1;

    if(sx == l && sy + d >= c) return -1;
    if(sy == c && sx + d >= l) return -1;

    return l + c - 2;

}

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

/***
Educational Codeforces Round 134 (Div. 2)
2022-08-26

B. Deadly Laser
***/

function main() {
  // INPUT: Number of test cases
  let t = readline();
  t = parseInt(t);
  for (let tc = 0; tc < t; tc++) {
    // INPUT: grid size (n, m); laser at (sx, sy); range d
    let args = readline();
    args = args.split(" ");
    args = args.map((k) => parseInt(k));
    const [n, m] = args.slice(0, 2);

    if (badLaser(...args)) {
      console.log(-1);
    } else {
      // number of steps will always be the same
      // if it is possible robot can always take
      // either right->down or down->right the whole board
      console.log(n + m - 2);
    }
  }
}

// Manhattan distance between 2 points
function manDist(x1, y1, x2, y2) {
  return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}

// Is the route impossible?
function badLaser(n, m, sx, sy, d) {
  return (sx - 1 <= d && sy - 1 <= d) || (n - sx <= d && m - sy <= d);
}

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

/***
Educational Codeforces Round 134 (Div. 2)
2022-08-26

B. Deadly Laser
***/

function main() {
  // INPUT: Number of test cases
  let t = readline();
  t = parseInt(t);
  for (let tc = 0; tc < t; tc++) {
    // INPUT: grid size (n, m); laser at (sx, sy); range d
    let args = readline();
    args = args.split(" ");
    args = args.map((k) => parseInt(k));
    const [n, m, sx, sy, d] = args;

    if (manDist(n, m, sx, sy) <= d) {
      console.log(-1);
    } else {
      // number of steps will always be the same
      // if it is possible robot can always take
      // either right->down or down->right the whole board
      console.log(n + m - 2);
    }
  }
}

// Manhattan distance between 2 points
function manDist(x1, y1, x2, y2) {
  return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}

let fs = require("fs");
let sc = {
    _buf: new Buffer.alloc(1 << 14),
    _bufPos: 0,
    _bufLen: 0,
    _ensure: function ()
    {
        if (this._bufPos === this._bufLen)
        {
            this._bufPos = 0;
            this._bufLen = fs.readSync(0, this._buf, 0, this._buf.length, null);
        }
    },
    _isws: function (ch)
    {
        return ch === 32 || ch === 9 || ch === 10 || ch === 13;
    },
    _islf: function (ch)
    {
        return ch === 10 || ch === 13;
    },
    _peekChar: function ()
    {
        this._ensure();
        return this._bufPos === this._bufLen ? 0 : this._buf[this._bufPos];
    },
    _skipWs: function ()
    {
        while (this._isws(this._peekChar()))
            this._bufPos++;
    },
    _readUntil: function (stop)
    {
        this._ensure();
        if (this._bufPos === this._bufLen)
            throw new Error("eof");
        let start = this._bufPos;
        let before = null;
        for (; ;)
        {
            if (this._bufPos === this._bufLen)
            {
                let len = this._bufPos - start, preLen = (before ? before.length : 0);
                let nbuf = new Buffer(len + preLen);
                if (before)
                    before.copy(nbuf);
                before = nbuf;
                this._buf.copy(before, preLen, start);
                this._ensure();
                start = this._bufPos;
            }
            if (this._bufPos === this._bufLen || stop(this._buf[this._bufPos])) break;
            this._bufPos++;
        }
        if (!before)
            return this._buf.toString("utf8", start, this._bufPos);
        let after = this._buf.slice(start, this._bufPos);
        let res = new Buffer(before.length + after.length);
        before.copy(res);
        after.copy(res, before.length);
        return res.toString();
    },

    nextToken: function ()
    {
        this._skipWs();
        return this._readUntil(this._isws);
    },
    L: function ()
    {
        let line = this._readUntil(this._islf);
        if (this._peekChar() === 13) this._bufPos++;
        if (this._peekChar() === 10) this._bufPos++;
        return line;
    },
    N: function ()
    {
        return +this.nextToken();
    },
    S: function ()
    {
        return this.nextToken();
    }
};

// DO NOT CHANGE TEMPLATE BEFORE

const Def = Number(1e9);

const Solve = () =>
{
    let n = sc.N(), m = sc.N(), sx = sc.N(), sy = sc.N(), d = sc.N();

    if ((sx + d >= n && sy + d >= m) || (sx - d <= 1 && sy - d <= 1))
    {
        console.log(-1);
        return;
    }

    // if ((sx + d >= n && sx - d <= 1) || (sy + d >= m && sy - d <= 1))
    // {
    //     console.log(-1);
    //     return;
    // }

    console.log(n + m - 2);

    // let arr = new Array(n).fill(new Array(m).fill(0));

    // arr[sx - 1][sy - 1] = 1;
    //
    // for (let i = 0; i < n; ++i)
    // {
    //     for (let j = 0; j < m; ++j)
    //     {
    //         console.log(arr[i][j]);
    //     }
    // }

}

const main = () =>
{
    let cases = sc.N();
    while (cases-- > 0) Solve();

    // Solve();
}
main();

let fs = require("fs");
let sc = {
    _buf: new Buffer.alloc(1 << 14),
    _bufPos: 0,
    _bufLen: 0,
    _ensure: function ()
    {
        if (this._bufPos === this._bufLen)
        {
            this._bufPos = 0;
            this._bufLen = fs.readSync(0, this._buf, 0, this._buf.length, null);
        }
    },
    _isws: function (ch)
    {
        return ch === 32 || ch === 9 || ch === 10 || ch === 13;
    },
    _islf: function (ch)
    {
        return ch === 10 || ch === 13;
    },
    _peekChar: function ()
    {
        this._ensure();
        return this._bufPos === this._bufLen ? 0 : this._buf[this._bufPos];
    },
    _skipWs: function ()
    {
        while (this._isws(this._peekChar()))
            this._bufPos++;
    },
    _readUntil: function (stop)
    {
        this._ensure();
        if (this._bufPos === this._bufLen)
            throw new Error("eof");
        let start = this._bufPos;
        let before = null;
        for (; ;)
        {
            if (this._bufPos === this._bufLen)
            {
                let len = this._bufPos - start, preLen = (before ? before.length : 0);
                let nbuf = new Buffer(len + preLen);
                if (before)
                    before.copy(nbuf);
                before = nbuf;
                this._buf.copy(before, preLen, start);
                this._ensure();
                start = this._bufPos;
            }
            if (this._bufPos === this._bufLen || stop(this._buf[this._bufPos])) break;
            this._bufPos++;
        }
        if (!before)
            return this._buf.toString("utf8", start, this._bufPos);
        let after = this._buf.slice(start, this._bufPos);
        let res = new Buffer(before.length + after.length);
        before.copy(res);
        after.copy(res, before.length);
        return res.toString();
    },

    nextToken: function ()
    {
        this._skipWs();
        return this._readUntil(this._isws);
    },
    L: function ()
    {
        let line = this._readUntil(this._islf);
        if (this._peekChar() === 13) this._bufPos++;
        if (this._peekChar() === 10) this._bufPos++;
        return line;
    },
    N: function ()
    {
        return +this.nextToken();
    },
    S: function ()
    {
        return this.nextToken();
    }
};

// DO NOT CHANGE TEMPLATE BEFORE

const Def = Number(1e9);

const Solve = () =>
{
    let n = sc.N(), m = sc.N(), sx = sc.N(), sy = sc.N(), d = sc.N();

    if ((sx + d >= n && sx - d <= 1) || (sy + d >= m && sy - d <= 1))
    {
        console.log(-1);
        return;
    }

    console.log(n + m - 2);

    let arr = new Array(n).fill(new Array(m).fill(0));

    // arr[sx - 1][sy - 1] = 1;
    //
    // for (let i = 0; i < n; ++i)
    // {
    //     for (let j = 0; j < m; ++j)
    //     {
    //         console.log(arr[i][j]);
    //     }
    // }

}

const main = () =>
{
    let cases = sc.N();
    while (cases-- > 0) Solve();

    // Solve();
}
main();

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, m, sx, sy, d] = input[index]
      .split(" ")
      .map((item) => parseInt(item));
    const testCase = {
      n,
      m,
      sx,
      sy,
      d,
    };

    testCases.push(testCase);
  }
}

function solution(testCase) {
  const { n, m, sx, sy, d } = testCase;

  if (
    (sy - d <= 1 && sy + d >= m) ||
    (sx - d <= 1 && sx + d >= n) ||
    Math.abs(sx - n) + Math.abs(sy - m) <= d
  )
    console.log(-1);
  else {
    console.log(n - 1 + m - 1);
  }
}

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, m, sx, sy, d] = input[index]
      .split(" ")
      .map((item) => parseInt(item));
    const testCase = {
      n,
      m,
      sx,
      sy,
      d,
    };

    testCases.push(testCase);
  }
}

function solution(testCase) {
  const { n, m, sx, sy, d } = testCase;

  if ((sy - d <= 1 && sy + d >= m) || (sx - d <= 1 && sx + d >= n))
    console.log(-1);
  else {
    console.log(n - 1 + m - 1);
  }
}

parseInput();

testCases.forEach(solution);


Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.  Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:let starting_time be an array of length ncurrent_time = 0dfs(v):	current_time = current_time + 1	starting_time[v] = current_time	shuffle children[v] randomly (each permutation with equal possibility)	// children[v] is vector of children cities of city v	for u in children[v]:		dfs(u)As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.

The first line of input contains a single integer n (1 ≤ n ≤ 105) — the number of cities in USC. The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.

In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i]. Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.

 var n = parseInt(readline());
  if(n > 1) {
    var g = readline().split(' ').map(x => parseInt(x) - 1);
    g.unshift(0);
    var gt = new Array(n).fill(0).map(x => []);
    var vn = [];
    for(var i = 0; i < n; i += 1) {
      gt[g[i]].push(i);
    }
    var stack = [[0, 0]];
    while(stack.length > 0) {
      // var tr = function(nd) {
      var tmp = stack.pop();
      var nd = tmp[0];
      var dir = tmp[1];
      if(dir === 0) {
        stack.push([nd, 1]);
        gt[nd].forEach(function(x) {
          // res += x === nd ? 0 : tr(x);
          if(nd !== x) {
            stack.push([x, 0]);
          }
        });
      } else {
        var res = 1;
        gt[nd].forEach(function(x) {
          if(nd !== x)
          res += vn[x];
        });
        vn[nd] = res;
      }
    }
    var pb = [];
    stack = [[0, 0]];
    while(stack.length > 0) {
      var tmp = stack.pop();
      var nd = tmp[0];
      var t = tmp[1];
      pb[nd] = t + 1;
      for(var i = 0; i < gt[nd].length; i += 1) {
        if(gt[nd][i] !== 0) {
          stack.push([gt[nd][i], t + 1 + (vn[nd] - vn[gt[nd][i]] - 1) / 2]);
        }
      }
    }
    print(pb.join(' '));
  } else {
    print(1);
  }


The hero is addicted to glory, and is fighting against a monster. The hero has $$$n$$$ skills. The $$$i$$$-th skill is of type $$$a_i$$$ (either fire or frost) and has initial damage $$$b_i$$$. The hero can perform all of the $$$n$$$ skills in any order (with each skill performed exactly once). When performing each skill, the hero can play a magic as follows:   If the current skill immediately follows another skill of a different type, then its damage is doubled.  In other words,   If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$c$$$ damage;  If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type frost, then it will deal $$$2c$$$ damage;  If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$2c$$$ damage;  If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type frost , then it will deal $$$c$$$ damage. Your task is to find the maximum damage the hero can deal.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$), indicating the number of skills.  The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 1$$$), where $$$a_i$$$ indicates the type of the $$$i$$$-th skill. Specifically, the $$$i$$$-th skill is of type fire if $$$a_i = 0$$$, and of type frost if $$$a_i = 1$$$.  The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$), where $$$b_i$$$ indicates the initial damage of the $$$i$$$-th skill.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output the maximum damage the hero can deal.

NoteIn the first test case, we can order the skills by $$$[3, 1, 4, 2]$$$, and the total damage is $$$100 + 2 \times 1 + 2 \times 1000 + 10 = 2112$$$.In the second test case, we can order the skills by $$$[1, 4, 2, 5, 3, 6]$$$, and the total damage is $$$3 + 2 \times 6 + 2 \times 4 + 2 \times 7 + 2 \times 5 + 2 \times 8 = 63$$$.In the third test case, we can order the skills by $$$[1, 2, 3]$$$, and the total damage is $$$1000000000 + 1000000000 + 1000000000 = 3000000000$$$.In the fourth test case, there is only one skill with initial damage $$$1$$$, so the total damage is $$$1$$$.

// Common Template Starts //
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++];
}
// Common Template Ends //

const getSolution = (n,a,b) => {
    if( n == 1 ) return b[0]

    let fire = a.filter( n => n === 0 )
    let frost = a.filter( n => n === 1 )

    if( fire.length === n || frost.length === n ) return b.reduce((partialSum, a) => partialSum + a, 0)

    let skills = []
    for( let i = 0; i< n; i++){
        skills.push({
           'attack' : a[i],
           'damage' : b[i]
        })
    }

    fire = skills.filter( s => s.attack === 0 ).sort((a,b) => b.damage - a.damage)
    frost = skills.filter( s => s.attack === 1 ).sort((a,b) => b.damage - a.damage)

    let damage = []
    let init = 0
    while( fire.length < frost.length )
    {
        damage.push( frost[frost.length - 1].damage )
        frost.pop()
        init = 0
    }

    while( frost.length < fire.length )
    {
        damage.push( fire[fire.length - 1].damage )
        fire.pop()
        init = 1
    }

    if( damage.length == 0 ) {

        let firemin = fire[fire.length - 1].damage
        let frostmin = frost[frost.length - 1].damage

        if( firemin <= frostmin ) {
            damage.push( fire[fire.length - 1].damage )
            fire.pop()
        } else {
            damage.push( frost[frost.length - 1].damage )
            frost.pop()
        }

        for( let f of fire )
        {
            damage.push( 2 * f.damage )
        }

        for( let f of frost )
        {
            damage.push( 2 * f.damage )
        }

    }  else {
        for( let f of fire )
        {
            damage.push( 2 * f.damage )
        }

        for( let f of frost )
        {
            damage.push( 2 * f.damage )
        }
    }

    return damage.reduce((partialSum, a) => partialSum + a, 0)
}

// Driver Function Starts //
function main() {

    let testcases = parseInt(readline())
    while (testcases--) {

        let n = parseInt(readline())
        let a = readline().split(' ').map(Number)
        let b = readline().split(' ').map(Number)
        console.log(getSolution(n, a, b))
    }

}
// Driver Function Ends //

var readline = require('readline');
var inputString = [], currentLine = 0;
process.stdin.resume();
process.stdin.setEncoding('utf-8');
var rl = readline.createInterface(process.stdin);
rl.on('line', line => { inputString.push(line) });
process.stdin.on('end', () => {  main()  });

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

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

function myFunc(n, skill, damage){
    let fire = [];
    let ice = [];
    let resp = 0;

    for(let i = 0; i < n; i++){
        if(skill[i] == 0) fire.push(damage[i]);
        else ice.push(damage[i]);
    }

    fire.sort((a, b) => a - b);
    ice.sort((a, b) => a - b);

    if(fire.length == ice.length){
        if(fire[0] <= ice[0]) resp = fire[0] + (2*ice[0]);
        else resp = (2*fire[0]) + ice[0];
        for(let i = 1; i < fire.length; i++){
            resp += (fire[i] * 2) + (ice[i]*2);
        }
    }
    else if(fire.length > ice.length){
        let diff = fire.length - ice.length;
        for(let i = 0; i < fire.length; i++){
            if(i < diff) resp += fire[i];
            else resp += (fire[i] * 2) + (ice[i-diff]*2);
        }
    }
    else{
        let diff = ice.length - fire.length;
        for(let i = 0; i < ice.length; i++){
            if(i < diff) resp += ice[i];
            else resp += (fire[i-diff] * 2) + (ice[i]*2);
        }
    }

    return resp

}

// Common Template Starts //
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++];
}
// Common Template Ends //

const getSolution = (n, d) => {
    const a = [];
    a.push(d[0])
    for (let i = 1; i < n; i++) {

        let k = a.length - 1

        let op = ((a[k] - d[i]) < 0) ? (a[k] + d[i]) : (a[k] - d[i])
        a.push(op)

        k = a.length - 1
        if (a[k] - a[k - 1] < d[i]) return -1

    }

    return a.join(' ')
}

// Driver Function Starts //
function main() {

    let testcases = parseInt(readline())
    while (testcases--) {

        let n = parseInt(readline())
        let d = readline().split(' ').map(Number)
        console.log(getSolution(n, d))
    }

}
// Driver Function Ends //


You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence.

The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct.

In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence.  Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them.

NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing.

var l = readline().split(' ');
var n = +l[0];
var a = readline().split(' ').map(function(v){return +v;});
var b = new Array(n);
for(var i = 0; i < n; i++) {
    b[i] = [a[i], i];
}
function sortB(p,q) {
    return p[0] - q[0];
}
b.sort(sortB);

var p = new Array(n);
for(var i = 0; i < n; i++) {
	p[i] = b[i][1];
}

var chk = new Array(n);
var ansn = 0;
var ans = new Array(n);
for(var i = 0; i < n; i++) {
	if(chk[i] === undefined) {
		chk[i] = true;
		ans[ansn] = [i+1];
		for(var j = p[i]; j != i; j = p[j]) {
			chk[j] = true;
			ans[ansn].push(j+1);
		}
		ansn += 1;
	}
}

print(ansn);
for(var i = 0; i < ansn; i++) {
	print(ans[i].length + " " + ans[i].join(" "));
}


You are given n points on the straight line — the positions (x-coordinates) of the cities and m points on the same line — the positions (x-coordinates) of the cellular towers. All towers work in the same way — they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r = 0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.

The first line contains two positive integers n and m (1 ≤ n, m ≤ 105) — the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1, b2, ..., bm ( - 109 ≤ bj ≤ 109) — the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.

Print minimal r so that each city will be covered by cellular network.

var INF = 100000000000;

var input = readline().split(' ');

var a = readline().split(' ');
var b = readline().split(' ');

// var n = 5, m = 3, a = [1, 5, 10, 14, 17], b = [4, 11, 15];

for (var i = 0; i < a.length; i++) {
    a[i] = Number(a[i]);
}

for (var i = 0; i < b.length; i++) {
    b[i] = Number(b[i]);
}

function find(a, x) {
    var l = 0, r = a.length;
    while (r - l > 1) {
        var m = Math.floor((l + r) / 2);
        if (a[m] < x) {
            l = m;
        }
        else {
            r = m;
        }
    }
    return l + 1;
}

function check(r) {
    var cnt = 0;
    for (var i = 0; i < a.length; i++) {
        var t = find(b, a[i]);
        var flag = 0;
        if (b[t] !== undefined && Math.abs(b[t] - a[i]) <= r) {
            flag = 1;
        }
        if (b[t - 1] !== undefined && Math.abs(b[t - 1] - a[i]) <= r) {
            flag = 1;
        }
        if (b[t + 1] !== undefined && Math.abs(b[t + 1] - a[i]) <= r) {
            flag = 1;
        }
        if (b[t - 2] !== undefined && Math.abs(b[t - 1] - a[i]) <= r) {
            flag = 1;
        }
        if (b[t + 2] !== undefined && Math.abs(b[t + 2] - a[i]) <= r) {
            flag = 1;
        }
        cnt += flag;
    }

    return cnt === a.length;
}

var L = 0; R = INF;

while (R - L > 1) {
    var M = Math.floor((L + R) / 2);
    if (check(M)) {
        R = M;
    }
    else {
        L = M;
    }
}

if (check(L)) R = L;
print(R);

var INF = 100000000000;

var input = readline().split(' ');

var a = readline().split(' ');
var b = readline().split(' ');

// var n = 5, m = 3, a = [1, 5, 10, 14, 17], b = [4, 11, 15];

for (var i = 0; i < a.length; i++) {
    a[i] = Number(a[i]);
}

for (var i = 0; i < b.length; i++) {
    b[i] = Number(b[i]);
}

function find(a, x) {
    var l = 0, r = a.length;
    while (r - l > 1) {
        var m = Math.floor((l + r) / 2);
        if (a[m] < x) {
            l = m;
        }
        else {
            r = m;
        }
    }
    return l + 1;
}

function check(r) {
    var cnt = 0;
    for (var i = 0; i < a.length; i++) {
        var t = find(b, a[i]);
        var cur = t - INF;
        var flag = 0;
        if (b[t] !== undefined && Math.abs(b[t] - a[i]) <= r) {
            flag = 1;
        }
        if (b[t - 1] !== undefined && Math.abs(b[t - 1] - a[i]) <= r) {
            flag = 1;
        }
        if (b[t + 1] !== undefined && Math.abs(b[t + 1] - a[i]) <= r) {
            flag = 1;
        }
        cnt += flag;
    }

    return cnt === a.length;
}

var L = 0; R = INF;

while (R - L > 1) {
    var M = Math.floor((L + R) / 2);
    if (check(M)) {
        R = M;
    }
    else {
        L = M;
    }
}

print(R);

var INF = 100000000000;

var input = readline().split(' ');

var a = readline().split(' ');
var b = readline().split(' ');

// var n = 5, m = 3, a = [1, 5, 10, 14, 17], b = [4, 11, 15];

for (var i = 0; i < a.length; i++) {
    a[i] = Number(a[i]);
}

for (var i = 0; i < b.length; i++) {
    b[i] = Number(b[i]);
}

function find(a, x) {
    var l = 0, r = a.length;
    while (r - l > 1) {
        var m = Math.floor((l + r) / 2);
        if (a[m] < x) {
            l = m;
        }
        else {
            r = m;
        }
    }
    return l + 1;
}

function check(r) {
    var cnt = 0;
    for (var i = 0; i < a.length; i++) {
        var t = find(b, a[i]);
        var flag = 0;
        for (var j = 0; j < b.length; j++) {
            if (Math.abs(b[j] - a[i]) <= r) {
                flag = 1;
            }
        }
        cnt += flag;
    }

    return cnt === a.length;
}

var L = 0; R = INF;

while (R - L > 1) {
    var M = Math.floor((L + R) / 2);
    if (check(M)) {
        R = M;
    }
    else {
        L = M;
    }
}

print(R);

var INF = 100000000000;

var input = readline().split(' ');

var a = readline().split(' ');
var b = readline().split(' ');

// var n = 5, m = 3, a = [1, 5, 10, 14, 17], b = [4, 11, 15];

for (var i = 0; i < a.length; i++) {
    a[i] = Number(a[i]);
}

for (var i = 0; i < b.length; i++) {
    b[i] = Number(b[i]);
}

function find(a, x) {
    var l = 0, r = a.length;
    while (r - l > 1) {
        var m = Math.floor((l + r) / 2);
        if (a[m] < x) {
            l = m;
        }
        else {
            r = m;
        }
    }
    return l + 1;
}

function check(r) {
    var cnt = 0;
    for (var i = 0; i < a.length; i++) {
        var t = find(b, a[i]);
        var flag = 0;
        if (b[t] !== undefined && Math.abs(b[t] - a[i]) <= r) {
            flag = 1;
        }
        if (b[t - 1] !== undefined && Math.abs(b[t - 1] - a[i]) <= r) {
            flag = 1;
        }
        if (b[t + 1] !== undefined && Math.abs(b[t + 1] - a[i]) <= r) {
            flag = 1;
        }
        if (b[t - 2] !== undefined && Math.abs(b[t - 2] - a[i]) <= r) {
            flag = 1;
        }
        if (b[t + 2] !== undefined && Math.abs(b[t + 2] - a[i]) <= r) {
            flag = 1;
        }
        cnt += flag;
    }

    return cnt === a.length;
}

var L = 0; R = INF;

while (R - L > 1) {
    var M = Math.floor((L + R) / 2);
    if (check(M)) {
        R = M;
    }
    else {
        L = M;
    }
}

print(R);


The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts $$$h$$$ hours and each hour lasts $$$m$$$ minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from $$$0$$$ to $$$h-1$$$ and minutes are numbered from $$$0$$$ to $$$m-1$$$.  That's how the digits are displayed on the clock. Please note that digit $$$1$$$ is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day).The image of the clocks in the mirror is reflected against a vertical axis.  The reflection is not a valid time.The reflection is a valid time with $$$h=24$$$, $$$m = 60$$$. However, for example, if $$$h=10$$$, $$$m=60$$$, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment $$$s$$$ and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid.It can be shown that with any $$$h$$$, $$$m$$$, $$$s$$$ such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest.You are asked to solve the problem for several test cases.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. The next $$$2 \cdot T$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers $$$h$$$, $$$m$$$ ($$$1 \le h, m \le 100$$$). The second line contains the start time $$$s$$$ in the described format HH:MM.

For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct.

NoteIn the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct.

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

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

function getPaddedString (x) {
	if (x < 10)
		return '0' + x;
	return String(x);
}

function check (hh, mm, h, m) {
	const mp = new Map([['0', '0'] , ['1', '1'], ['2', '5'], ['5', '2'], ['8', '8']]);

	hh = getPaddedString(hh);
	mm = getPaddedString(mm);
	for (const d of hh + mm) {
		if (!mp.has(d))
			return false
	}

	const hr = [mp.get(hh[0]), mp.get(hh[1])];
	const mr = [mp.get(mm[0]), mp.get(mm[1])];

	return Number(hr[1] + hr[0]) < m && Number(mr[1] + mr[0]) < h;
}

function main () {
	let T = rn();
	while (T--) {
		const [h, m] = rna();

		let [hh, mm]  = rl().split(':').map(x => Number(x));
		while (true) {
			if (check(hh, mm, h, m))
				break;
			mm = (mm + 1) % m;
			if (mm == 0) {
				hh = (hh + 1) % h;
			}
		}

		console.log(getPaddedString(hh) + ':' + getPaddedString(mm));
	}
}

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

var good = new Set([0, 1, 2, 5, 8]);

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var hm = readNumArray();
    var h = hm[0];
    var m = hm[1];
    var hcmc = readline().split(':').map(Number);
    var hc = hcmc[0];
    var mc = hcmc[1];
    print(findNextGood(hc, mc, h, m));
  }
}

function isGoodH(num, m) {
  var first = switch25(Math.floor(num / 10));
  var second = switch25(num % 10);

  return good.has(first) && good.has(second)
    && (second * 10 + first) < m;
}

function isGoodM(num, h) {
  var first = switch25(Math.floor(num / 10));
  var second = switch25(num % 10);

  return good.has(first) && good.has(second)
    && (second * 10 + first) < h;
}

function findNextGood(hc, mc, h, m) {
  while (!isGoodM(mc , h)) {
    mc++;
    if (mc >= m) {
      mc = 0;
      hc++;
      if (hc >= h) {
        hc = 0;
      }
    }
  }

  while (!isGoodH(hc , m)) {
    hc++;
    mc = 0;
    if (hc >= h) {
      hc = 0;
    }
  }
  var hours = hc;
  var ph = hours > 9 ? String(hours) : '0' + hours;
  var minutes = mc;
  var pm = minutes > 9 ? String(minutes) : '0' + minutes;

  return ph + ':' + pm;
}

function switch25(num) {
  if (num === 2) return 5;
  if (num === 5) return 2;
  return num;
}
main();

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

var good = new Set([0, 1, 2, 5, 8]);

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var hm = readNumArray();
    var h = hm[0];
    var m = hm[1];
    var hcmc = readline().split(':').map(Number);
    var hc = hcmc[0];
    var mc = hcmc[1];
    print(findNextGood(hc, mc, h, m));
  }
}

function isGoodH(num, m) {
  var first = switch25(Math.floor(num / 10));
  var second = switch25(num % 10);

  return good.has(first) && good.has(second)
    && (second * 10 + first) < m;
}

function isGoodM(num, h) {
  var first = switch25(Math.floor(num / 10));
  var second = switch25(num % 10);

  return good.has(first) && good.has(second)
    && (second * 10 + first) < h;
}

function findNextGood(hc, mc, h, m) {
  while (!isGoodM(mc , h)) {
    mc++;
    if (mc >= m) {
      mc = 0;
      hc++;
      if (hc >= h) {
        hc = 0;
      }
    }
  }
  var minutes = mc;
  var pm = minutes > 9 ? String(minutes) : '0' + minutes;

  while (!isGoodH(hc , m)) {
    hc++;
    if (hc >= h) {
      hc = 0;
    }
  }
  var hours = hc;
  var ph = hours > 9 ? String(hours) : '0' + hours;

  return ph + ':' + pm;
}

function switch25(num) {
  if (num === 2) return 5;
  if (num === 5) return 2;
  return num;
}
main();

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

var good = new Set([0, 1, 2, 5, 8]);

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var hm = readNumArray();
    var h = hm[0];
    var m = hm[1];
    var hcmc = readline().split(':').map(Number);
    var hc = hcmc[0];
    var mc = hcmc[1];
    print(findNextGood(hc, mc, h, m));
  }
}

function isGoodH(num, m) {
  var first = switch25(Math.floor(num / 10));
  var second = switch25(num % 10);

  return good.has(first) && good.has(second)
    && (second * 10 + first) < m;
}

function isGoodM(num, h) {
  var first = switch25(Math.floor(num / 10));
  var second = switch25(num % 10);

  return good.has(first) && good.has(second)
    && (second * 10 + first) < h;
}

function findNextGood(hc, mc, h, m) {
  while (!isGoodM(mc , h)) {
    mc++;
    if (mc >= m) {
      mc = 0;
      hc++;
    }
  }
  var minutes = mc;
  var pm = minutes > 9 ? String(minutes) : '0' + minutes;

  while (!isGoodH(hc , m)) {
    hc++;
    if (hc >= h) {
      hc = 0;
    }
  }
  var hours = hc;
  var ph = hours > 9 ? String(hours) : '0' + hours;

  return ph + ':' + pm;
}

function switch25(num) {
  if (num === 2) return 5;
  if (num === 5) return 2;
  return num;
}
main();

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

var good = new Set([0, 1, 2, 5, 8]);

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var hm = readNumArray();
    var h = hm[0];
    var m = hm[1];
    var hcmc = readline().split(':').map(Number);
    var hc = hcmc[0];
    var mc = hcmc[1];
    print(findNextGood(hc, mc, h, m));
  }
}

function isGoodH(num, m) {
  var first = switch25(Math.floor(num / 10));
  var second = switch25(num % 10);

  return good.has(first) && good.has(second)
    && (second * 10 + first) < m;
}

function isGoodM(num, h) {
  var first = switch25(Math.floor(num / 10));
  var second = switch25(num % 10);

  return good.has(first) && good.has(second)
    && (second * 10 + first) < h;
}

function findNextGood(hc, mc, h, m) {
  while (!isGoodH(hc , m)) {
    hc++;
    mc = 0;
    if (hc >= h) {
      hc = 0;
    }
  }
  var hours = hc;
  var ph = hours > 9 ? String(hours) : '0' + hours;
  while (!isGoodM(mc , h)) {
    mc++;
    if (mc >= m) {
      mc = 0;
    }
  }
  var minutes = mc;
  var pm = minutes > 9 ? String(minutes) : '0' + minutes;
  return ph + ':' + pm;
}

function switch25(num) {
  if (num === 2) return 5;
  if (num === 5) return 2;
  return num;
}
main();

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

var good = new Set([0, 1, 2, 5, 8]);

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var hm = readNumArray();
    var h = hm[0];
    var m = hm[1];
    var hcmc = readline().split(':').map(Number);
    var hc = hcmc[0];
    var mc = hcmc[1];
    print(findNextGood(hc, mc, h, m));
  }
}

function isGoodH(num, m) {
  var first = Math.floor(num / 10);
  var second = num % 10;

  return good.has(first) && good.has(second)
    && (second * 10 + first) < m;
}

function isGoodM(num, h) {
  var first = Math.floor(num / 10);
  var second = num % 10;

  return good.has(first) && good.has(second)
    && (second * 10 + first) < h;
}

function findNextGood(hc, mc, h, m) {
  while (!isGoodH(hc , m)) {
    hc++;
    mc = 0;
    if (hc >= h) {
      hc = 0;
    }
  }
  var hours = hc;
  var ph = hours > 9 ? String(hours) : '0' + hours;
  while (!isGoodM(mc , h)) {
    mc++;
    if (mc >= m) {
      mc = 0;
    }
  }
  var minutes = mc;
  var pm = minutes > 9 ? String(minutes) : '0' + minutes;
  return ph + ':' + pm;
}
main();

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

var good = new Set([0, 1, 2, 5, 8]);

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var hm = readNumArray();
    var h = hm[0];
    var m = hm[1];
    var hcmc = readline().split(':').map(Number);
    var hc = hcmc[0];
    var mc = hcmc[1];
    print(findNextGood(hc, mc, h, m));
  }
}

function isGoodH(num, m) {
  var first = Math.floor(num / 10);
  var second = num % 10;

  return good.has(first) && good.has(second)
    && (second * 10 + first) < m;
}

function isGoodM(num, h) {
  var first = Math.floor(num / 10);
  var second = num % 10;

  return good.has(first) && good.has(second)
    && (second * 10 + first) < h;
}

function findNextGood(hc, mc, h, m) {
  while (!isGoodH(hc , m)) {
    hc++;
    if (hc >= h) {
      hc = 0;
    }
  }
  var hours = hc;
  var ph = hours > 9 ? String(hours) : '0' + hours;
  while (!isGoodM(mc , h)) {
    mc++;
    if (mc >= m) {
      mc = 0;
    }
  }
  var minutes = mc;
  var pm = minutes > 9 ? String(minutes) : '0' + minutes;
  return ph + ':' + pm;
}
main();


Sonya was unable to think of a story for this problem, so here comes the formal description.You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0.

The first line of the input contains a single integer n (1 ≤ n ≤ 3000) — the length of the array. Next line contains n integer ai (1 ≤ ai ≤ 109).

Print the minimum number of operation required to make the array strictly increasing.

NoteIn the first sample, the array is going to look as follows:2 3 5 6 7 9 11|2 - 2| + |1 - 3| + |5 - 5| + |11 - 6| + |5 - 7| + |9 - 9| + |11 - 11| = 9And for the second sample:1 2 3 4 5|5 - 1| + |4 - 2| + |3 - 3| + |2 - 4| + |1 - 5| = 12

var _0xda93=["\x70\x75\x73\x68","\x73\x6F\x72\x74","\x20","\x73\x70\x6C\x69\x74","\x6C\x65\x6E\x67\x74\x68","\x73\x68\x69\x66\x74"];function push(arr,_0xbdd3x3){arr[_0xda93[0]](_0xbdd3x3);arr= arr[_0xda93[1]](function(_0xbdd3x4,_0xbdd3x5){if(_0xbdd3x4< _0xbdd3x5){return 1}else {if(_0xbdd3x4> _0xbdd3x5){return -1}else {return 0}}});return arr}var N=Number(readline());var arr=readline()[_0xda93[3]](_0xda93[2]);var saved=[];var result=0;for(var i=0;i< arr[_0xda93[4]];i++){arr[i]-= i;saved= push(saved,arr[i]);if(saved[0]> arr[i]){result+= saved[0]- arr[i];saved[_0xda93[5]]();saved= push(saved,arr[i])}};print(result)

var _0xe50a=["\x70\x75\x73\x68","\x73\x6F\x72\x74","\x20","\x73\x70\x6C\x69\x74","\x6C\x65\x6E\x67\x74\x68","\x73\x68\x69\x66\x74"];function push(arr,_0xa013x3){arr[_0xe50a[0]](_0xa013x3);arr= arr[_0xe50a[1]](function(_0xa013x4,_0xa013x5){if(_0xa013x4< _0xa013x5){return true}else {return false}});return arr}var N=Number(readline());var arr=readline()[_0xe50a[3]](_0xe50a[2]);var saved=[];var result=0;for(var i=0;i< arr[_0xe50a[4]];i++){arr[i]-= i;saved= push(saved,arr[i]);if(saved[0]> arr[i]){result+= saved[0]- arr[i];saved[_0xe50a[5]]();saved= push(saved,arr[i])}};print(result)


Theater stage is a rectangular field of size n × m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.A position is good if two conditions hold:   there is no actor in the cell the spotlight is placed to;  there is at least one actor in the direction the spotlight projects. Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.

The first line contains two positive integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the plan. The next n lines contain m integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.

Print one integer — the number of good positions for placing the spotlight.

NoteIn the first example the following positions are good:  the (1, 1) cell and right direction;  the (1, 1) cell and down direction;  the (1, 3) cell and left direction;  the (1, 3) cell and down direction;  the (1, 4) cell and left direction;  the (2, 2) cell and left direction;  the (2, 2) cell and up direction;  the (2, 2) and right direction;  the (2, 4) cell and left direction. Therefore, there are 9 good positions in this example.

var input = readline()
  .split(" ")
  .map((val) => parseInt(val));
var n = input[0],
  m = input[1];
var theater = [];
for (var i = 0; i < n; i++) {
  var inp = readline()
    .split(" ")
    .map((val) => parseInt(val));
  theater.push(inp);
}
var count = 0;
for (var i = 0; i < n; i++) {
  for (var j = 0; j < m; j++) {
    if (theater[i][j] == 1) {
      var left = j - 1,
        top = i - 1,
        bottom = i + 1;
      while (left >= 0) {
        if (theater[i][left] == 0) count++;
        if (theater[i][left] == 1) break;
        left--;
      }
      while (top >= 0) {
        if (theater[top][j] == 0) count++;
        if (theater[top][j] == 1) break;
        top--;
      }
      while (bottom < n) {
        if (theater[bottom][j] == 0) count++;
        if (theater[bottom][j] == 1) {
          break;
        }
        bottom++;
      }
      j++;

      while (j < m) {
        if (theater[i][j] == 0) count++;
        if (theater[i][j] == 1) {
          j--;
          break;
        }
        j++;
      }
    }
  }
}
print(count);

const mapSize = readline().split(" ").map(x => Number(x));
const height = mapSize[0];
const width = mapSize[1];
const map = new Array(height);
const createCell = cell => cell.charCodeAt(0) === 48 /* 0 */;
for (var y = 0; y < height; y++)
  map[y] = readline().split(" ").slice(0, width).map(createCell);
var result = 0;
for (var y = 0; y < height; y++) {
  var row = map[y];
  for (var x = 0; x < width; x++) {
    if (row[x]) continue;
    var cy;
    var cx;
    for (cy = y - 1; cy >= 0 && map[cy][x]; cy--)
      result++;
    for (cy = y + 1; cy < height && map[cy][x]; cy++)
      result++;
    for (cx = x - 1; cx >= 0 && row[cx]; cx--)
      result++;
    for (cx = x + 1; cx < width && row[cx]; cx++)
      result++;
  }
}
print(result);

"use strict";

/*
var write = console.log.bind();
var k = 0;
var readline = function() {

	switch ( k++ ) {
		case 0: return '4 4'
		case 1: return '0 0 0 0'
		case 2: return '1 0 0 1'
		case 3: return '0 1 1 0'
		case 4: return '0 1 0 0'
	}
};
*/

let input = readline().split(' ').map(e => +e);
let n = input[0],
	m = input[1];

let grid = [];

for ( let i = 0; i < n; i++ )
	grid.push(readline().split(' ').map(e => +e));

let accum = 0, dir;

for ( let i = 0; i < n; i++ ) {
	dir = false;
	for ( let j = 0; j < m; j++ ) {
		if ( dir && grid[i][j] === 0 )
			accum++;
		else if ( grid[i][j] === 1 )
			dir = true;
	}
}

for ( let i = 0; i < n; i++ ) {
	dir = false;
	for ( let j = m-1; j >= 0; j-- ) {
		if ( dir && grid[i][j] === 0 )
			accum++;
		else if ( grid[i][j] === 1 )
			dir = true;
	}
}

for ( let i = 0; i < m; i++ ) {
	dir = false;
	for ( let j = 0; j < n; j++ ) {
		if ( dir && grid[j][i] === 0 )
			accum++;
		else if ( grid[j][i] === 1 )
			dir = true;
	}
}

for ( let i = 0; i < m; i++ ) {
	dir = false;
	for ( let j = n-1; j >= 0; j-- ) {
		if ( dir && grid[j][i] === 0 )
			accum++;
		else if ( grid[j][i] === 1 )
			dir = true;
	}
}

write(accum);

const mapSize = readline().split(" ").map(x => Number(x));
const height = mapSize[0];
const width = mapSize[1];
const map = new Array(height);
for (var i = 0; i < height; i++)
  map[i] = readline().split(" ").slice(0, width).map(cell => cell == "0");
var result = 0;
for (var y = 0; y < height; y++) {
  var row = map[y];
  for (var x = 0; x < height; x++) {
    if (row[x]) continue;
    var cy;
    var cx;
    for (cy = y - 1; cy >= 0 && map[cy][x]; cy--)
      result++;
    for (cy = y + 1; cy < height && map[cy][x]; cy++)
      result++;
    for (cx = x - 1; cx >= 0 && row[cx]; cx--)
      result++;
    for (cx = x + 1; cx < width && row[cx]; cx++)
      result++;
  }
}
print(result);


You are given an unweighted tree with $$$n$$$ vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices $$$a, b, c$$$ on this tree such that the number of edges which belong to at least one of the simple paths between $$$a$$$ and $$$b$$$, $$$b$$$ and $$$c$$$, or $$$a$$$ and $$$c$$$ is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.

The first line contains one integer number $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree.  Next $$$n - 1$$$ lines describe the edges of the tree in form $$$a_i, b_i$$$ ($$$1 \le a_i$$$, $$$b_i \le n$$$, $$$a_i \ne b_i$$$). It is guaranteed that given graph is a tree.

In the first line print one integer $$$res$$$ — the maximum number of edges which belong to at least one of the simple paths between $$$a$$$ and $$$b$$$, $$$b$$$ and $$$c$$$, or $$$a$$$ and $$$c$$$. In the second line print three integers $$$a, b, c$$$ such that $$$1 \le a, b, c \le n$$$ and $$$a \ne, b \ne c, a \ne c$$$. If there are several answers, you can print any.

NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices $$$1, 5, 6$$$ then the path between $$$1$$$ and $$$5$$$ consists of edges $$$(1, 2), (2, 3), (3, 4), (4, 5)$$$, the path between $$$1$$$ and $$$6$$$ consists of edges $$$(1, 2), (2, 3), (3, 4), (4, 6)$$$ and the path between $$$5$$$ and $$$6$$$ consists of edges $$$(4, 5), (4, 6)$$$. The union of these paths is $$$(1, 2), (2, 3), (3, 4), (4, 5), (4, 6)$$$ so the answer is $$$5$$$. It can be shown that there is no better answer.

'use strict'

const n = +readline();
const p = [];
const g = Array.from({ length: n + 1 }, () => []);
const d = Array(n+1).fill(0);
const del = [];

const dfs = (U, V) => {
    const q = [ [ U, V ] ];
    while(q.length) {
        const uv = q.pop();
        const u = uv[0], v = uv[1];
        d[v] = d[u] + 1;
        p[v] = u;
        g[v].filter(i => i !== u).forEach(i => q.push([ v, i ]));
    }
}

for(let i = 1; i < n; i++) {
    const uv = readline().split(' ').map(i => +i);
    const u = uv[0], v = uv[1];
    g[u].push(v);
    g[v].push(u);
}

dfs(0, 1);

let u = 0;
for (let i = 1; i <= n; i++) if (d[u] < d[i]) u = i;

d.fill(0);
dfs(0, u);

let v = 0;
for (let i = 1; i <= n; i++) if (d[v] < d[i]) v = i;

let ans = d[v] - 1;

let x = v;
while(x) { del[x] = 1; x = p[x]; }

x = v;
d.fill(0);

while(x) {
    g[x].filter(v => !del[v]).forEach(v => dfs(x, v));
	x = p[x];
}

let w = 0;
for(let i = 1; i <= n; ++i) if (i !== u && i !== v && d[w] <= d[i]) w = i;

print(d[w] + ans);
print(u, v, w);


Dreamoon is a big fan of the Codeforces contests.One day, he claimed that he will collect all the places from $$$1$$$ to $$$54$$$ after two more rated contests. It's amazing!Based on this, you come up with the following problem:There is a person who participated in $$$n$$$ Codeforces rounds. His place in the first round is $$$a_1$$$, his place in the second round is $$$a_2$$$, ..., his place in the $$$n$$$-th round is $$$a_n$$$.You are given a positive non-zero integer $$$x$$$.Please, find the largest $$$v$$$ such that this person can collect all the places from $$$1$$$ to $$$v$$$ after $$$x$$$ more rated contests.In other words, you need to find the largest $$$v$$$, such that it is possible, that after $$$x$$$ more rated contests, for each $$$1 \leq i \leq v$$$, there will exist a contest where this person took the $$$i$$$-th place.For example, if $$$n=6$$$, $$$x=2$$$ and $$$a=[3,1,1,5,7,10]$$$ then answer is $$$v=5$$$, because if on the next two contest he will take places $$$2$$$ and $$$4$$$, then he will collect all places from $$$1$$$ to $$$5$$$, so it is possible to get $$$v=5$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5$$$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains two integers $$$n, x$$$ ($$$1 \leq n, x \leq 100$$$). The second line contains $$$n$$$ positive non-zero integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$).

For each test case print one line containing the largest $$$v$$$, such that it is possible that after $$$x$$$ other contests, for each $$$1 \leq i \leq v$$$, there will exist a contest where this person took the $$$i$$$-th place.

NoteThe first test case is described in the statement.In the second test case, the person has one hundred future contests, so he can take place $$$1,2,\ldots,99$$$ and place $$$101$$$ on them in some order, to collect places $$$1,2,\ldots,101$$$.

for(var t=Number(readline());t;t--){
 var n = readline().trim().split(/\s/).map(x=>Number(x));
 var a = readline().trim().split(/\s/).map(x=>Number(x));
 a.sort((a, b) => a - b);
 var v = 0;
 for(var i=0;(i<n[0])&&(n[1]>=0);i++){
  if(a[i]==v) continue;
  n[1] -= (a[i]-v-1);
  v=a[i];
  if(n[1]<0)v--;
 }
 v+=n[1];
 print(v);
}

var test = parseInt(readline());
while (test--) {
    var firstInput = readline().split(' ').map(y => parseInt(y));
    var n = firstInput[0]; var x = firstInput[1];
    var secondInput = readline().split(' ').map(x => parseInt(x));
    secondInput.sort((a, b) => a - b)
    var count = 0;
    for (var i = 1; i < n + x; i++) {
        var found = secondInput.find(element => element == i);
        if (!found) {
            count++;
        }
        if (count == x) {
            count = 0;
            break;
        }
    }

    for (var j = i + 1; j < 105; j++) {
        var get = secondInput.find(element => element == j);
        if (!get) break;
    }
    print(j - 1)
}

const readline = require('readline');
const rl = readline.createInterface({input: process.stdin});
var stdin = [];
rl.on('line', function (line) {stdin.push(line);});
rl.on('close', main);

function main() {

    const c = parseInt(stdin.shift());

    for (let i = 0; i < c; i++) {
        let input1 = stdin.shift().split(" ");
        let n = parseInt(input1[0]);
        let x = parseInt(input1[1]);
        let p = new Array(201).fill(false);
        p[0] = true;
        stdin.shift()
            .split(" ")
            .map(function (x) {p[x] = true;});

        let j = 0;
        while (x > -1) {
            if (!p[j]) {
                x--;
            }
            j++;
        }

        console.log(j - 2);
    }
}

// Q:

const readline = require('readline');

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

let input = [];

rl.on('line', lineInput => {
	input.push(lineInput);
});

rl.on('close', () => {
    const test = parseInt(input[0]);
    let n, x, a;
    for (let t = 0; t < test; t++) {
        [n, x] = input[2*t + 1].split(' ').map((a) => parseInt(a));
        a = input[2*t + 2].split(' ').map((a) => parseInt(a));
        console.log(solution(a, n, x));
    }
})

function solution(a, n, x) {
    let rankAchieved = Array(n+x).fill(false);
    for (let i = 0; i < n; i++) {
        rankAchieved[a[i]] = true;
    }
    for (let k = n+x; k > 0; k--) {
        let v = 0;
        for (let i = 1; i <= k; i++) {
            if (!rankAchieved[i]) {
                v += 1;
            }
        }
        if (v <= x) {
            return k;
        }
    }
}

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

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

  if (c % 2) {
    c++;
    [n, x] = d.split(' ').map(Number);
    return;
  }

  const arr = d.split(' ').map(Number);
  arr.sort((a, b) => a - b);
  let ans = 0;
  let count = 1;

  while (x > 0) {
    if (!arr.includes(count)) {
      x--;

      if (x === 0) {
        while (arr.includes(count + 1)) {
          count++;
        }
      }
    }

    ans = Math.max(ans, count);
    count++;
  }

  console.log(ans);

  c++;
});

var test = parseInt(readline());
while (test--) {
    var firstInput = readline().split(' ').map(y => parseInt(y));
    var n = firstInput[0]; var x = firstInput[1];
    var secondInput = readline().split(' ').map(x => parseInt(x));
    secondInput.sort((a, b) => a - b)
    var count = 0;
    for (var i = 1; i < n + x; i++) {
        var found = secondInput.find(element => element == i);
        if (!found) {
            count++;
        }
        if (count == x) {
            count = 0;
            break;
        }
    }

    var get = secondInput.find(element => element == i + 1);
    if (get) print(i + 1);
    else print(i);
}

const readline = require('readline');
const rl = readline.createInterface({input: process.stdin});
var stdin = [];
rl.on('line', function (line) {stdin.push(line);});
rl.on('close', main);

function main() {

    const c = parseInt(stdin.shift());

    for (let i = 0; i < c; i++) {
        let input1 = stdin.shift().split(" ");
        let n = parseInt(input1[0]);
        let x = parseInt(input1[1]);
        let p = new Array(201).fill(false);
        p[0] = true;
        stdin.shift()
            .split(" ")
            .map(function (x) {p[x] = true;});

        let j = 0;
        while (x > -1) {
            if (!p[j]) {
                x--;
            }
            j++;
        }

        console.log(j);
    }
}