Polycarp came up with a new programming language. There are only two types of statements in it:   "x := s": assign the variable named x the value s (where s is a string). For example, the statement var := hello assigns the variable named var the value hello. Note that s is the value of a string, not the name of a variable. Between the variable name, the := operator and the string contains exactly one space each. "x = a + b": assign the variable named x the concatenation of values of two variables a and b. For example, if the program consists of three statements a := hello, b := world, c = a + b, then the variable c will contain the string helloworld. It is guaranteed that the program is correct and the variables a and b were previously defined. There is exactly one space between the variable names and the = and + operators. All variable names and strings only consist of lowercase letters of the English alphabet and do not exceed $$$5$$$ characters.The result of the program is the number of occurrences of string haha in the string that was written to the variable in the last statement.Polycarp was very tired while inventing that language. He asks you to implement it. Your task is — for given program statements calculate the number of occurrences of string haha in the last assigned variable.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^3$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of statements in the program. All variable names and strings are guaranteed to consist only of lowercase letters of the English alphabet and do not exceed $$$5$$$ characters. This is followed by $$$n$$$ lines describing the statements in the format described above. It is guaranteed that the program is correct.

For each set of input data, output the number of occurrences of the haha substring in the string that was written to the variable in the last statement.

4
6
a := h
b := aha
c = a + b
c = c + c
e = c + c
d = a + c
15
x := haha
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
x = x + x
1
haha := hah
5
haahh := aaaha
ahhhh = haahh + haahh
haahh = haahh + haahh
ahhhh = ahhhh + haahh
ahhaa = haahh + ahhhh

NoteIn the first test case the resulting value of d is hhahahaha.

function readStringArray() {
  return readline().split(/\s/);
}

function solve() {
	var lines = parseInt(readline(), 10);
	var objVars = {};
	var count = 0;

	for(var i = 0; i < lines; i++){
		var values = readStringArray();
		if(values[1] == ':=') {
			var v = values[2];
			var c = 0;
			if(v.length === 4){
				if(v[0] + v[1] + v[2] + v[3] === 'haha') {
					c++;
				}
			} else if (v.length === 5) {
				if(v[0] + v[1] + v[2] + v[3] === 'haha') {
					c++;
				} else if(v[1] + v[2] + v[3] + v[4] === 'haha') {
					c++;
				}
			}

			objVars[values[0]] = {
				valStart: values[2].substring(0, Math.min(3, values[2].length)),
				valEnd: values[2].substring(Math.max(0, values[2].length - 3)),
				count: c
			}

		}
		else {
			var a = objVars[values[2]].val;
			var b = objVars[values[4]].val;
			var c = objVars[values[2]].count + objVars[values[4]].count;

			var mid = objVars[values[2]].valEnd + objVars[values[4]].valStart;

			for(var j = 0; j + 3 < mid.length; j++) {
				if(mid.substring(j, j + 4) === 'haha'){
					c++;
				}
			}

			objVars[values[0]] = {
				valStart: objVars[values[2]].valStart.length < 3 ? mid.substring(0, Math.min(3, mid.length)) : objVars[values[2]].valStart,
				valEnd: objVars[values[4]].valEnd.length < 3 ? mid.substring(Math.max(0, mid.length - 3)) : objVars[values[4]].valEnd,
				count: c
			}

		}
	}
	print(objVars[values[0]].count);
}

function main(){
	var t = parseInt(readline(), 10);
	for (var i = 0; i < t; i++) {
		solve();
	}
}

main();

function readStringArray() {
  return readline().split(/\s/);
}

function solve() {
	var lines = parseInt(readline(), 10);
	var objVars = {};
	var count = 0;

	for(var i = 0; i < lines; i++){
		var values = readStringArray();
		if(values[1] == ':=') {
			var v = values[2];
			var c = 0;
			if(v.length === 4){
				if(v[0] + v[1] + v[2] + v[3] === 'haha') {
					c++;
				}
			} else if (v.length === 5) {
				if(v[0] + v[1] + v[2] + v[3] === 'haha') {
					c++;
				} else if(v[1] + v[2] + v[3] + v[4] === 'haha') {
					c++;
				}
			}

			objVars[values[0]] = {
				valStart: values[2].substring(0, Math.min(3, values[2].length)),
				valEnd: values[2].substring(Math.max(0, values[2].length - 3)),
				count: c
			}

		}
		else {
			var a = objVars[values[2]].val;
			var b = objVars[values[4]].val;
			var c = objVars[values[2]].count + objVars[values[4]].count;

			var mid = objVars[values[2]].valEnd + objVars[values[4]].valStart;

			for(var j = 0; j + 3 < mid.length; j++) {
				if(mid.substring(j, j + 4) === 'haha'){
					c++;
				}
			}

			objVars[values[0]] = {
				valStart: objVars[values[2]].valStart.length < 3 ? mid.substring(0, Math.min(3, mid.length)) : objVars[values[2]].valStart,
				valEnd: objVars[values[2]].valEnd.length < 3 ? mid.substring(Math.max(0, mid.length - 3)) : objVars[values[2]].valEnd,
				count: c
			}

		}
	}
	print(objVars[values[0]].count);
}

function main(){
	var t = parseInt(readline(), 10);
	for (var i = 0; i < t; i++) {
		solve();
	}
}

main();

function readStringArray() {
  return readline().split(/\s/);
}

function solve() {
	var lines = parseInt(readline(), 10);
	var objVars = {};
	var count = 0;

	for(var i = 0; i < lines; i++){
		var values = readStringArray();
		if(values[1] == ':=') {
			var v = values[2];
			var c = 0;
			if(v.length === 4){
				if(v[0] + v[1] + v[2] + v[3] === 'haha') {
					c++;
				}
			} else if (v.length === 5) {
				if(v[0] + v[1] + v[2] + v[3] === 'haha') {
					c++;
				} else if(v[1] + v[2] + v[3] + v[4] === 'haha') {
					c++;
				}
			}

			objVars[values[0]] = {
				valStart: values[2].substring(0, Math.min(3, values[2].length)),
				valEnd: values[2].substring(Math.max(0, values[2].length - 3)),
				count: c
			}

		}
		else {
			var a = objVars[values[2]].val;
			var b = objVars[values[4]].val;
			var c = objVars[values[2]].count + objVars[values[4]].count;

			var mid = objVars[values[2]].valEnd + objVars[values[4]].valStart;

			for(var j = 0; j < mid.length; j++) {
				if(mid.substring(j, j + 4) === 'haha'){
					c++;
				}
			}

			objVars[values[0]] = {
				valStart: objVars[values[2]].valStart.length < 3 ? mid.substring(0, Math.min(3, mid.length)) : objVars[values[2]].valStart,
				valEnd: objVars[values[2]].valEnd.length < 3 ? mid.substring(Math.max(0, mid.length - 3)) : objVars[values[2]].valEnd,
				count: c
			}

		}
	}
	print(objVars[values[0]].count);
}

function main(){
	var t = parseInt(readline(), 10);
	for (var i = 0; i < t; i++) {
		solve();
	}
}

main();

function readStringArray() {
  return readline().split(/\s/);
}

function solve() {
	var lines = parseInt(readline(), 10);
	var objVars = {};
	var count = 0;

	for(var i = 0; i < lines; i++){
		var values = readStringArray();
		if(values[1] == ':=') {
			var v = values[2];
			var c = 0;
			if(v.length === 4){
				if(v[0] + v[1] + v[2] + v[3] === 'haha') {
					c++;
				}
			} else if (v.length === 5) {
				if(v[1] + v[2] + v[3] + v[4] === 'haha') {
					c++;
				}
			}

			objVars[values[0]] = {
				val : values[2],
				count: c
			}

		} else {
			var v1 = objVars[values[2]].val;
			var v2 = objVars[values[4]].val;
			var c1 = objVars[values[2]].count;
			var c2 = objVars[values[4]].count;

			var vv = v1 + v2;
			var cc = c1 + c2;

			var lv1 = v1.length - 3;
			var lvv = vv.length;

			var index0 = lv1;
			var index1 = lv1 + 3;

			while(index0 < 0) {
				index0++;
				index1++;
			}

			if(index1 <= lvv){
				while(index1 < lv1 + 6){
					if(vv[index0] + vv[index0+1] + vv[index0+2] + vv[index0+3] === 'haha') {
						cc++;
					}
					index1++;
					index0++;
				}
			}

			objVars[values[0]] = {
				val: vv,
				count: cc
			};
		}
	}
	print(objVars[values[0]].count);

}

function main(){
	var t = parseInt(readline(), 10);
	for (var i = 0; i < t; i++) {
		solve();
	}
}

main();

function readStringArray() {
  return readline().split(/\s/);
}

function solve() {
	var lines = parseInt(readline(), 10);
	var objVars = {};
	var count = 0;

	for(var i = 0; i < lines; i++){
		var values = readStringArray();
		print(values[0])
		print(values[1])
		print(values[2])
		if(values.length === 4) {
			objVars[values[0]] = values[2];
		} else {
			objVars[values[0]] = objVars[values[2]] + objVars[values[4]];
		}
	}

	var lastVal = objVars[values[0]];
	for(var i = 0; i < lastVal.length - 3; i++){
		if(lastVal[i] + lastVal[i + 1] + lastVal[i + 2] + lastVal[i + 3] === 'haha'){
			count++;
		}
	}

	print(count);

}

function main(){
	var t = parseInt(readline(), 10);
	for (var i = 0; i < t; i++) {
		solve();
	}
}

main();

function readStringArray() {
  return readline().split(/\s/);
}

function solve() {
	var lines = parseInt(readline(), 10);
	var objVars = {};
	var count = 0;

	for(var i = 0; i < lines; i++){
		var values = readStringArray();
		print(values)
		if(values.length === 4) {
			objVars[values[0]] = values[2];
		} else {
			objVars[values[0]] = objVars[values[2]] + objVars[values[4]];
		}
	}

	var lastVal = objVars[values[0]];
	for(var i = 0; i < lastVal.length - 3; i++){
		if(lastVal[i] + lastVal[i + 1] + lastVal[i + 2] + lastVal[i + 3] === 'haha'){
			count++;
		}
	}

	print(count);

}

function main(){
	var t = parseInt(readline(), 10);
	for (var i = 0; i < t; i++) {
		solve();
	}
}

main();

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

function solve() {
	var lines = parseInt(readline(), 10);
	var objVars = {};
	var count = 0;

	for(var i = 0; i < lines; i++){
		var values = readStringArray();
		if(values.length === 4) {
			objVars[values[0]] = values[2];
		} else {
			objVars[values[0]] = objVars[values[2]] + objVars[values[4]];
		}
	}

	var lastVal = objVars[values[0]];
	for(var i = 0; i < lastVal.length - 3; i++){
		if(lastVal[i] + lastVal[i + 1] + lastVal[i + 2] + lastVal[i + 3] === 'haha'){
			count++;
		}
	}

	print(count);

}

function main(){
	var t = parseInt(readline(), 10);
	for (var i = 0; i < t; i++) {
		solve();
	}
}

main();

function readStringArray() {
  return readline().split(/\s/);
}

function solve() {
	var lines = parseInt(readline(), 10);
	var objVars = {};
	var count = 0;

	for(var i = 0; i < lines; i++){
		var values = readStringArray();
		if(values.length === 4) {
			objVars[values[0]] = values[2];
		} else {
			objVars[values[0]] = objVars[values[2]] + objVars[values[4]];
		}
	}

	var lastVal = objVars[values[0]];
	for(var i = 0; i < lastVal.length - 3; i++){
		if(lastVal[i] + lastVal[i + 1] + lastVal[i + 2] + lastVal[i + 3] === 'haha'){
			count++;
		}
	}

	print(count);

}

function main(){
	var t = parseInt(readline(), 10);
	for (var i = 0; i < t; i++) {
		solve();
	}
}

main();

function readStringArray() {
  return readline().split(/\s/);
}

function solve() {
	var lines = parseInt(readline(), 10);
	var objVars = {};
	var count = 0;

	for(var i = 0; i < lines; i++){
		var values = readStringArray();
		if(values.length === 4) {
			objVars[values[0]] = values[2];
		} else {
			objVars[values[0]] = objVars[values[2]] + objVars[values[4]];
		}
	}

	var lastVal = objVars[values[0]];
	for(var i = 0; i < lastVal.length - 3; i++){
		if(lastVal[i] + lastVal[i + 1] + lastVal[i + 2] + lastVal[i + 3] === 'haha'){
			count++;
		}
	}
	print(count++);

}

function main(){
	var t = parseInt(readline(), 10);
	for (var i = 0; i < t; i++) {
		solve();
	}
}

main();


In the Bus of Characters there are $$$n$$$ rows of seat, each having $$$2$$$ seats. The width of both seats in the $$$i$$$-th row is $$$w_i$$$ centimeters. All integers $$$w_i$$$ are distinct.Initially the bus is empty. On each of $$$2n$$$ stops one passenger enters the bus. There are two types of passengers:   an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it;  an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it. You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of rows in the bus. The second line contains the sequence of integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le 10^{9}$$$), where $$$w_i$$$ is the width of each of the seats in the $$$i$$$-th row. It is guaranteed that all $$$w_i$$$ are distinct. The third line contains a string of length $$$2n$$$, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the $$$j$$$-th character is '0', then the passenger that enters the bus on the $$$j$$$-th stop is an introvert. If the $$$j$$$-th character is '1', the the passenger that enters the bus on the $$$j$$$-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal $$$n$$$), and for each extrovert there always is a suitable row.

Print $$$2n$$$ integers — the rows the passengers will take. The order of passengers should be the same as in input.

NoteIn the first example the first passenger (introvert) chooses the row $$$2$$$, because it has the seats with smallest width. The second passenger (introvert) chooses the row $$$1$$$, because it is the only empty row now. The third passenger (extrovert) chooses the row $$$1$$$, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row $$$2$$$, because it is the only row with an empty place.

  var n = parseInt(readline());
  var r = readline().split(' ').map((x, i) => [parseInt(x), i + 1]);
  var od = readline().split('').map(x => parseInt(x));

  r = r.sort(function(a, b) { return b[0] - a[0]});

  var e = [];
  var res = [];
  for(var i = 0; i < 2 * n; i += 1) {
    if(od[i] === 0) {
      var w = r.pop();
      res.push(w[1]);
      e.push(w);
    } else {
      var w = e.pop();
      res.push(w[1]);
    }
  }
  print(res.join(' '));


Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.Omkar currently has $$$n$$$ supports arranged in a line, the $$$i$$$-th of which has height $$$a_i$$$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $$$1$$$ operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add $$$1$$$ to each of their heights. Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!An array $$$b$$$ is a subsegment of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.An array $$$b_1, b_2, \dots, b_n$$$ is called nondecreasing if $$$b_i\le b_{i+1}$$$ for every $$$i$$$ from $$$1$$$ to $$$n-1$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of supports Omkar has. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(0 \leq a_{i} \leq 10^9)$$$ — the heights of the supports. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the minimum number of operations Omkar needs to perform to make his supports able to support his waterslide.

NoteThe subarray with which Omkar performs the operation is bolded.In the first test case:First operation:$$$[5, 3, \textbf{2}, 5] \to [5, 3, \textbf{3}, 5]$$$Second operation:$$$[5, \textbf{3}, \textbf{3}, 5] \to [5, \textbf{4}, \textbf{4}, 5]$$$Third operation:$$$[5, \textbf{4}, \textbf{4}, 5] \to [5, \textbf{5}, \textbf{5}, 5]$$$In the third test case, the array is already nondecreasing, so Omkar does $$$0$$$ operations.

const getMinOperations = (nums) => {
  var count = 0;

  for (var i = nums.length - 1; i >= 1; i--) {
    count += Math.max(0, nums[i - 1] - nums[i]);
  }

  return count;
};

const main = () => {
  const T = Number(readline());

  for (var _ = 0; _ < T; _++) {
    readline();
    var nums = readline()
      .split(" ")
      .map((i) => Number(i));

    print(getMinOperations(nums));
  }
};

main();

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

    const store = [];

    for (let i = 0; i < len - 1; i++) {
      if (arr[i] - arr[i + 1] > 0) store.push(arr[i] - arr[i + 1]);
    }

    if (store.length) {
      const sum = store.reduce((total, n) => total + n, 0);
      console.log(sum);
    } else {
      console.log(0);
    }
  }
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
  const t = Number(readLine())
  for (let _ = 0; _ < t; _++) {
	const n = Number(readLine())
    const as = readLine().split(/\s/).map(Number)
    let result = 0
    for (let i = 1; i < n; i++) {
      result += Math.max(0, as[i - 1] - as[i])
    }
    console.log(result)
  }
}

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

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

function main() {
	let t = readLine() >> 0;
	while (t--) {
		let n = readLine() >> 0;
		let arr = readLine()
			.split(' ')
			.map(x => x >> 0);

		let d = [];
		for (let i = 1; i < n; i++) {
			d.push(arr[i] - arr[i - 1]);
		}

		let s = d.reduce((a, c) => (c < 0 ? a + c : a), 0);
		console.log(Math.abs(s));
	}
}

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

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

function main() {
	let t = readLine() >> 0;
	while (t--) {
		let n = readLine() >> 0;
		let arr = readLine()
			.split(' ')
			.map(x => x >> 0);

		let v = 0,
			c = arr[0];
		for (let i = 1; i < n; i++) {
			if (arr[i] < c) {
				v = Math.max(v, c - arr[i]);
			} else {
				c = arr[i];
			}
		}
		console.log(v);
	}
}


Soroush and Keshi each have a labeled and rooted tree on $$$n$$$ vertices. Both of their trees are rooted from vertex $$$1$$$.Soroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial graph on $$$n$$$ vertices.They add an edge between vertices $$$u$$$ and $$$v$$$ in the memorial graph if both of the following conditions hold:   One of $$$u$$$ or $$$v$$$ is the ancestor of the other in Soroush's tree.  Neither of $$$u$$$ or $$$v$$$ is the ancestor of the other in Keshi's tree. Here vertex $$$u$$$ is considered ancestor of vertex $$$v$$$, if $$$u$$$ lies on the path from $$$1$$$ (the root) to the $$$v$$$.Popping out of nowhere, Mashtali tried to find the maximum clique in the memorial graph for no reason. He failed because the graph was too big. Help Mashtali by finding the size of the maximum clique in the memorial graph.As a reminder, clique is a subset of vertices of the graph, each two of which are connected by an edge.

The first line contains an integer $$$t$$$ $$$(1\le t\le 3 \cdot 10^5)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(2\le n\le 3 \cdot 10^5)$$$. The second line of each test case contains $$$n-1$$$ integers $$$a_2, \ldots, a_n$$$ $$$(1 \le a_i < i)$$$, $$$a_i$$$ being the parent of the vertex $$$i$$$ in Soroush's tree. The third line of each test case contains $$$n-1$$$ integers $$$b_2, \ldots, b_n$$$ $$$(1 \le b_i < i)$$$, $$$b_i$$$ being the parent of the vertex $$$i$$$ in Keshi's tree. It is guaranteed that the given graphs are trees. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case print a single integer — the size of the maximum clique in the memorial graph.

NoteIn the first and third test cases, you can pick any vertex.In the second test case, one of the maximum cliques is $$$\{2, 3, 4, 5\}$$$.In the fourth test case, one of the maximum cliques is $$$\{3, 4, 6\}$$$.

const TreeMultiSet = (function () {
var{TreeMultiSet:t}=function(t){
/*! *****************************************************************************
        Copyright (c) Microsoft Corporation.

        Permission to use, copy, modify, and/or distribute this software for any
        purpose with or without fee is hereby granted.

        THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
        REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
        AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
        INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
        LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
        OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
        PERFORMANCE OF THIS SOFTWARE.
        ***************************************************************************** */
var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}function r(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function o(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function i(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}var s,u=function(){function t(t,e){this.it_=t,this.last_=e}return t.prototype.next=function(){if(this.it_.equals(this.last_))return{done:!0,value:void 0};var t=this.it_;return this.it_=this.it_.next(),{done:!1,value:t.value}},t.prototype[Symbol.iterator]=function(){return this},t}(),a=function(){function t(){}return t.prototype.empty=function(){return 0===this.size()},t.prototype.rbegin=function(){return this.end().reverse()},t.prototype.rend=function(){return this.begin().reverse()},t.prototype[Symbol.iterator]=function(){return new u(this.begin(),this.end())},t.prototype.toJSON=function(){var t,e,n=[];try{for(var o=r(this),i=o.next();!i.done;i=o.next()){var s=i.value;n.push(s)}}catch(e){t={error:e}}finally{try{i&&!i.done&&(e=o.return)&&e.call(o)}finally{if(t)throw t.error}}return n},t}(),c=function(){function t(t,e){this.data_=t,this.index_=e}return t.prototype.index=function(){return this.index_},Object.defineProperty(t.prototype,"value",{get:function(){return this.data_[this.index_]},enumerable:!1,configurable:!0}),t.prototype.prev=function(){return--this.index_,this},t.prototype.next=function(){return++this.index_,this},t.prototype.advance=function(t){return this.index_+=t,this},t.prototype.equals=function(t){return this.data_===t.data_&&this.index_===t.index_},t.prototype.swap=function(t){var e,n;e=o([t.data_,this.data_],2),this.data_=e[0],t.data_=e[1],n=o([t.index_,this.index_],2),this.index_=n[0],t.index_=n[1]},t}(),_=function(t){function e(e){var n=t.call(this)||this;return n.data_=e(n),n}return n(e,t),e.prototype.assign=function(t,e){this.clear(),this.insert(t,e)},e.prototype.clear=function(){this.data_.clear()},e.prototype.begin=function(){return this.data_.begin()},e.prototype.end=function(){return this.data_.end()},e.prototype.has=function(t){return!this.find(t).equals(this.end())},e.prototype.size=function(){return this.data_.size()},e.prototype.push=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(0===t.length)return this.size();var n=new c(t,0),r=new c(t,t.length);return this._Insert_by_range(n,r),this.size()},e.prototype.insert=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 1===t.length?this._Insert_by_key(t[0]):t[0].next instanceof Function&&t[1].next instanceof Function?this._Insert_by_range(t[0],t[1]):this._Insert_by_hint(t[0],t[1])},e.prototype.erase=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 1!==t.length||t[0]instanceof this.end().constructor&&t[0].source()===this?1===t.length?this._Erase_by_range(t[0]):this._Erase_by_range(t[0],t[1]):this._Erase_by_val(t[0])},e.prototype._Erase_by_range=function(t,e){void 0===e&&(e=t.next());var n=this.data_.erase(t,e);return this._Handle_erase(t,e),n},e}(a),l=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.insert=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return t.prototype.insert.apply(this,i([],o(e),!1))},e.prototype._Erase_by_val=function(t){var e=this.find(t);if(!0===e.equals(this.end()))return 0;for(var n=e.next(),r=1;!n.equals(this.end())&&this._Key_eq(t,n.value);)n=n.next(),++r;return this._Erase_by_range(e,n),r},e.prototype.merge=function(t){this.insert(t.begin(),t.end()),t.clear()},e}(_);!function(t){t.construct=function(t){for(var e,n,r=[],s=1;s<arguments.length;s++)r[s-1]=arguments[s];return r.length>=1&&r[0]instanceof Array?(e=function(){var e=r[0];t.push.apply(t,i([],o(e),!1))},n=r.slice(1)):r.length>=2&&r[0].next instanceof Function&&r[1].next instanceof Function?(e=function(){var e=r[0],n=r[1];t.assign(e,n)},n=r.slice(2)):(e=null,n=r),{ramda:e,tail:n}}}(s||(s={}));var h=null;function p(){return null===y&&(null===h&&(h="object"==typeof global&&"object"==typeof global.process&&"object"==typeof global.process.versions&&void 0!==global.process.versions.node),void 0===(y=h?global:self).__s_iUID&&(y.__s_iUID=0)),y}var f,y=null;function v(t){if(t instanceof Object){if(!1===t.hasOwnProperty("__get_m_iUID")){var e=++p().__s_iUID;Object.defineProperty(t,"__get_m_iUID",{value:function(){return e}})}return t.__get_m_iUID()}return void 0===t?-1:0}function d(t,e){return t=t?t.valueOf():t,e=e?e.valueOf():e,t instanceof Object&&t.equals instanceof Function?t.equals(e):t===e}function g(t,e){return t=t.valueOf(),e=e.valueOf(),t instanceof Object?t.less instanceof Function?t.less(e):v(t)<v(e):t<e}function b(t,e){return e^=t?1:0,e*=k}function m(t,e){return x(t.toString(),e)}function x(t,e){for(var n=0;n<t.length;++n)e^=t.charCodeAt(n),e*=k;return Math.abs(e)}!function(t){t.construct=function(t,e,n){for(var r=[],u=3;u<arguments.length;u++)r[u-3]=arguments[u];var a=null,c=g;if(1===r.length&&r[0]instanceof e){var _=r[0];c=_.key_comp(),a=function(){var e=_.begin(),n=_.end();t.assign(e,n)}}else{var l=s.construct.apply(s,i([t],o(r),!1));a=l.ramda,l.tail.length>=1&&(c=l.tail[0])}n(c),null!==a&&a()},t.emplacable=function(t,e,n){var r=e.prev(),o=r.equals(t.end())||t.value_comp()(r.value,n);return o=o&&(e.equals(t.end())||t.value_comp()(n,e.value))}}(f||(f={}));var w,I=2166136261,k=16777619,q=function(){function t(t,e){this.first=t,this.second=e}return t.prototype.equals=function(t){return d(this.first,t.first)&&d(this.second,t.second)},t.prototype.less=function(t){return!1===d(this.first,t.first)?g(this.first,t.first):g(this.second,t.second)},t.prototype.hashCode=function(){return function(){for(var t,e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var i=I;try{for(var s=r(n),u=s.next();!u.done;u=s.next()){var a=u.value,c=typeof(a=a?a.valueOf():a);if("boolean"===c)i=b(a,i);else if("number"===c||"bigint"===c)i=m(a,i);else if("string"===c)i=x(a,i);else if(a instanceof Object&&a.hashCode instanceof Function){var _=a.hashCode();if(1===n.length)return _;i^=_,i*=k}else i=m(v(a),i)}}catch(e){t={error:e}}finally{try{u&&!u.done&&(e=s.return)&&e.call(s)}finally{if(t)throw t.error}}return Math.abs(i)}(this.first,this.second)},t}(),E=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.find=function(t){var e=this.lower_bound(t);return!e.equals(this.end())&&this._Key_eq(t,e.value)?e:this.end()},e.prototype.count=function(t){for(var e=this.find(t),n=0;!e.equals(this.end())&&this._Key_eq(e.value,t);e=e.next())++n;return n},e.prototype.equal_range=function(t){return new q(this.lower_bound(t),this.upper_bound(t))},e.prototype.value_comp=function(){return this.key_comp()},e.prototype._Key_eq=function(t,e){return!this.key_comp()(t,e)&&!this.key_comp()(e,t)},e.prototype._Insert_by_key=function(t){var e=this.upper_bound(t);return e=this.data_.insert(e,t),this._Handle_insert(e,e.next()),e},e.prototype._Insert_by_hint=function(t,e){if(f.emplacable(this,t,e)){var n=this.data_.insert(t,e);return this._Handle_insert(n,n.next()),n}return this._Insert_by_key(e)},e.prototype._Insert_by_range=function(t,e){for(var n=t;!n.equals(e);n=n.next())this._Insert_by_key(n.value)},e}(l),O=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e}(function(t){function e(e){var n=this.constructor,r=t.call(this,e)||this,o=n.prototype;return Object.setPrototypeOf?Object.setPrototypeOf(r,o):r.__proto__=o,r}return n(e,t),Object.defineProperty(e.prototype,"name",{get:function(){return this.constructor.name},enumerable:!1,configurable:!0}),e.prototype.what=function(){return this.message},e.prototype.toJSON=function(){return{name:this.name,message:this.message,stack:this.stack}},e}(Error)),F=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e}(O),S=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e}(O);!function(t){function e(t){if("string"==typeof t)return t;var e=t.constructor.name;return t.constructor.__MODULE&&(e=t.constructor.__MODULE+"."+e),"std."+e}t.get_class_name=e,t.empty=function(t,n){return new S("Error on "+e(t)+"."+n+"(): it's empty container.")},t.negative_index=function(t,n,r){return new S("Error on "+e(t)+"."+n+"(): parametric index is negative -> (index = "+r+").")},t.excessive_index=function(t,n,r,o){return new S("Error on "+e(t)+"."+n+"(): parametric index is equal or greater than size -> (index = "+r+", size: "+o+").")},t.not_my_iterator=function(t,n){return new F("Error on "+e(t)+"."+n+"(): parametric iterator is not this container's own.")},t.erased_iterator=function(t,n){return new F("Error on "+e(t)+"."+n+"(): parametric iterator, it already has been erased.")},t.negative_iterator=function(t,n,r){return new S("Error on "+e(t)+"."+n+"(): parametric iterator is directing negative position -> (index = "+r+").")},t.iterator_end_value=function(t,n){void 0===n&&(n="end");var r=e(t);return new S("Error on "+r+".Iterator.value: cannot access to the "+r+"."+n+"().value.")},t.key_nout_found=function(t,n,r){throw new S("Error on "+e(t)+"."+n+"(): unable to find the matched key -> "+r)}}(w||(w={}));var j=function(){function t(t,e,n){this.prev_=t,this.next_=e,this.value_=n}return t._Set_prev=function(t,e){t.prev_=e},t._Set_next=function(t,e){t.next_=e},t.prototype.prev=function(){return this.prev_},t.prototype.next=function(){return this.next_},Object.defineProperty(t.prototype,"value",{get:function(){return this._Try_value(),this.value_},enumerable:!1,configurable:!0}),t.prototype._Try_value=function(){if(void 0===this.value_&&!0===this.equals(this.source().end()))throw w.iterator_end_value(this.source())},t.prototype.equals=function(t){return this===t},t}(),z=function(){function t(t,e){this.index_=t,this.value_=e}return t.prototype.index=function(){return this.index_},Object.defineProperty(t.prototype,"value",{get:function(){return this.value_},enumerable:!1,configurable:!0}),t.prototype.next=function(){return++this.index_,this},t.prototype.equals=function(t){return this.index_===t.index_},t}();var R=function(t){function e(){var e=t.call(this)||this;return e.end_=e._Create_iterator(null,null),e.clear(),e}return n(e,t),e.prototype.assign=function(t,e){this.clear(),this.insert(this.end(),t,e)},e.prototype.clear=function(){j._Set_prev(this.end_,this.end_),j._Set_next(this.end_,this.end_),this.begin_=this.end_,this.size_=0},e.prototype.resize=function(t){var e=t-this.size();e>0?this.insert(this.end(),e,void 0):e<0&&this.erase(function(t,e){if(0===e)return t;if(t.advance instanceof Function)return t.advance(e);var n;if(e<0){if(!(t.prev instanceof Function))throw new F("Error on std.advance(): parametric iterator is not a bi-directional iterator, thus advancing to negative direction is not possible.");n=function(t){return t.prev()},e=-e}else n=function(t){return t.next()};for(;e-- >0;)t=n(t);return t}(this.end(),-e),this.end())},e.prototype.begin=function(){return this.begin_},e.prototype.end=function(){return this.end_},e.prototype.size=function(){return this.size_},e.prototype.push_front=function(t){this.insert(this.begin_,t)},e.prototype.push_back=function(t){this.insert(this.end_,t)},e.prototype.pop_front=function(){if(!0===this.empty())throw w.empty(this.end_.source().constructor.name,"pop_front");this.erase(this.begin_)},e.prototype.pop_back=function(){if(!0===this.empty())throw w.empty(this.end_.source().constructor.name,"pop_back");this.erase(this.end_.prev())},e.prototype.push=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(0===t.length)return this.size();var n=new c(t,0),r=new c(t,t.length);return this._Insert_by_range(this.end(),n,r),this.size()},e.prototype.insert=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t.source()!==this.end_.source())throw w.not_my_iterator(this.end_.source(),"insert");if(!0===t.erased_)throw w.erased_iterator(this.end_.source(),"insert");return 1===e.length?this._Insert_by_repeating_val(t,1,e[0]):2===e.length&&"number"==typeof e[0]?this._Insert_by_repeating_val(t,e[0],e[1]):this._Insert_by_range(t,e[0],e[1])},e.prototype._Insert_by_repeating_val=function(t,e,n){var r=new z(0,n),o=new z(e);return this._Insert_by_range(t,r,o)},e.prototype._Insert_by_range=function(t,e,n){for(var r=t.prev(),o=null,i=0,s=e;!1===s.equals(n);s=s.next()){var u=this._Create_iterator(r,null,s.value);0===i&&(o=u),j._Set_next(r,u),r=u,++i}return!0===t.equals(this.begin())&&(this.begin_=o),j._Set_next(r,t),j._Set_prev(t,r),this.size_+=i,o},e.prototype.erase=function(t,e){return void 0===e&&(e=t.next()),this._Erase_by_range(t,e)},e.prototype._Erase_by_range=function(t,e){if(t.source()!==this.end_.source())throw w.not_my_iterator(this.end_.source(),"insert");if(!0===t.erased_)throw w.erased_iterator(this.end_.source(),"insert");if(t.equals(this.end_))return this.end_;var n=t.prev();j._Set_next(n,e),j._Set_prev(e,n);for(var r=t;!r.equals(e);r=r.next())r.erased_=!0,--this.size_;return t.equals(this.begin_)&&(this.begin_=e),e},e.prototype.swap=function(t){var e,n,r;e=o([t.begin_,this.begin_],2),this.begin_=e[0],t.begin_=e[1],n=o([t.end_,this.end_],2),this.end_=n[0],t.end_=n[1],r=o([t.size_,this.size_],2),this.size_=r[0],t.size_=r[1]},e}(a),P=function(){function t(t){this.base_=t.prev()}return t.prototype.source=function(){return this.base_.source()},t.prototype.base=function(){return this.base_.next()},Object.defineProperty(t.prototype,"value",{get:function(){return this.base_.value},enumerable:!1,configurable:!0}),t.prototype.prev=function(){return this._Create_neighbor(this.base().next())},t.prototype.next=function(){return this._Create_neighbor(this.base_)},t.prototype.equals=function(t){return this.base_.equals(t.base_)},t}(),C=function(t){function e(e){var n=t.call(this)||this;return n.associative_=e,n}return n(e,t),e.prototype._Create_iterator=function(t,n,r){return e.Iterator.create(this,t,n,r)},e._Swap_associative=function(t,e){var n;n=o([e.associative_,t.associative_],2),t.associative_=n[0],e.associative_=n[1]},e.prototype.associative=function(){return this.associative_},e}(R);!function(t){var e=function(t){function e(e,n,r,o){var i=t.call(this,n,r,o)||this;return i.source_=e,i}return n(e,t),e.create=function(t,n,r,o){return new e(t,n,r,o)},e.prototype.reverse=function(){return new r(this)},e.prototype.source=function(){return this.source_.associative()},e}(j);t.Iterator=e;var r=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype._Create_neighbor=function(t){return new e(t)},e}(P);t.ReverseIterator=r}(C||(C={}));var M=function(){function t(t,e){this.value=t,this.color=e,this.parent=null,this.left=null,this.right=null}return Object.defineProperty(t.prototype,"grand",{get:function(){return this.parent.parent},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sibling",{get:function(){return this===this.parent.left?this.parent.right:this.parent.left},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uncle",{get:function(){return this.parent.sibling},enumerable:!1,configurable:!0}),t}(),D=function(t){function e(e,n){return t.call(this,e,n,(function(t,e){var r=n(t.value,e.value);return r||n(e.value,t.value)?r:v(t)<v(e)}))||this}return n(e,t),e.prototype.insert=function(e){v(e),t.prototype.insert.call(this,e)},e.prototype._Nearest_by_key=function(t,e){if(null===this.root_)return null;for(var n=this.root_,r=null;;){var o=n.value,i=null;if(this.key_comp()(t,o.value)?i=n.left:this.key_comp()(o.value,t)?i=n.right:(r=n,i=e(n)),null===i)break;n=i}return null!==r?r:n},e.prototype.nearest_by_key=function(t){return this._Nearest_by_key(t,(function(t){return t.left}))},e.prototype.upper_bound=function(t){var e=this._Nearest_by_key(t,(function(t){return t.right}));if(null===e)return this.source().end();var n=e.value;return this.key_comp()(t,n.value)?n:n.next()},e}(function(t){function e(e,n,r){var o=t.call(this,r)||this;return o.source_=e,o.key_comp_=n,o.key_eq_=function(t,e){return!n(t,e)&&!n(e,t)},o}return n(e,t),e._Swap_source=function(t,e){var n;n=o([e.source_,t.source_],2),t.source_=n[0],e.source_=n[1]},e.prototype.get_by_key=function(t){var e=this.nearest_by_key(t);return null!==e&&this.key_eq_(t,e.value.value)?e:null},e.prototype.lower_bound=function(t){var e=this.nearest_by_key(t);return null===e?this.source_.end():this.key_comp_(e.value.value,t)?e.value.next():e.value},e.prototype.equal_range=function(t){return new q(this.lower_bound(t),this.upper_bound(t))},e.prototype.source=function(){return this.source_},e.prototype.key_comp=function(){return this.key_comp_},e.prototype.key_eq=function(){return this.key_eq_},e.prototype.value_comp=function(){return this.key_comp_},e}(function(){function t(t){this.root_=null,this.comp_=t,this.equal_=function(e,n){return!t(e,n)&&!t(n,e)}}return t.prototype.clear=function(){this.root_=null},t.prototype.root=function(){return this.root_},t.prototype.get=function(t){var e=this.nearest(t);return null!==e&&this.equal_(t,e.value)?e:null},t.prototype.nearest=function(t){if(null===this.root_)return null;for(var e=this.root_;;){var n=null;if(this.comp_(t,e.value))n=e.left;else{if(!this.comp_(e.value,t))return e;n=e.right}if(null===n)break;e=n}return e},t.prototype._Fetch_maximum=function(t){for(;null!==t.right;)t=t.right;return t},t.prototype.insert=function(t){var e=this.nearest(t),n=new M(t,1);null===e?this.root_=n:(n.parent=e,this.comp_(n.value,e.value)?e.left=n:e.right=n),this._Insert_case1(n)},t.prototype._Insert_case1=function(t){null===t.parent?t.color=0:this._Insert_case2(t)},t.prototype._Insert_case2=function(t){0!==this._Fetch_color(t.parent)&&this._Insert_case3(t)},t.prototype._Insert_case3=function(t){1===this._Fetch_color(t.uncle)?(t.parent.color=0,t.uncle.color=0,t.grand.color=1,this._Insert_case1(t.grand)):this._Insert_case4(t)},t.prototype._Insert_case4=function(t){t===t.parent.right&&t.parent===t.grand.left?(this._Rotate_left(t.parent),t=t.left):t===t.parent.left&&t.parent===t.grand.right&&(this._Rotate_right(t.parent),t=t.right),this._Insert_case5(t)},t.prototype._Insert_case5=function(t){t.parent.color=0,t.grand.color=1,t===t.parent.left&&t.parent===t.grand.left?this._Rotate_right(t.grand):this._Rotate_left(t.grand)},t.prototype.erase=function(t){var e=this.get(t);if(null!==e){if(null!==e.left&&null!==e.right){var n=this._Fetch_maximum(e.left);e.value=n.value,e=n}var r=null===e.right?e.left:e.right;0===this._Fetch_color(e)&&(e.color=this._Fetch_color(r),this._Erase_case1(e)),this._Replace_node(e,r),1===this._Fetch_color(this.root_)&&(this.root_.color=0)}},t.prototype._Erase_case1=function(t){null!==t.parent&&this._Erase_case2(t)},t.prototype._Erase_case2=function(t){1===this._Fetch_color(t.sibling)&&(t.parent.color=1,t.sibling.color=0,t===t.parent.left?this._Rotate_left(t.parent):this._Rotate_right(t.parent)),this._Erase_case3(t)},t.prototype._Erase_case3=function(t){0===this._Fetch_color(t.parent)&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,this._Erase_case1(t.parent)):this._Erase_case4(t)},t.prototype._Erase_case4=function(t){1===this._Fetch_color(t.parent)&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,t.parent.color=0):this._Erase_case5(t)},t.prototype._Erase_case5=function(t){t===t.parent.left&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&1===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,t.sibling.left.color=0,this._Rotate_right(t.sibling)):t===t.parent.right&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&1===this._Fetch_color(t.sibling.right)&&(t.sibling.color=1,t.sibling.right.color=0,this._Rotate_left(t.sibling)),this._Erase_case6(t)},t.prototype._Erase_case6=function(t){t.sibling.color=this._Fetch_color(t.parent),t.parent.color=0,t===t.parent.left?(t.sibling.right.color=0,this._Rotate_left(t.parent)):(t.sibling.left.color=0,this._Rotate_right(t.parent))},t.prototype._Rotate_left=function(t){var e=t.right;this._Replace_node(t,e),t.right=e.left,null!==e.left&&(e.left.parent=t),e.left=t,t.parent=e},t.prototype._Rotate_right=function(t){var e=t.left;this._Replace_node(t,e),t.left=e.right,null!==e.right&&(e.right.parent=t),e.right=t,t.parent=e},t.prototype._Replace_node=function(t,e){null===t.parent?this.root_=e:t===t.parent.left?t.parent.left=e:t.parent.right=e,null!==e&&(e.parent=t.parent)},t.prototype._Fetch_color=function(t){return null===t?0:t.color},t}()));return t.TreeMultiSet=function(t){function e(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var s=t.call(this,(function(t){return new C(t)}))||this;return f.construct.apply(f,i([s,e,function(t){s.tree_=new D(s,t)}],o(n),!1)),s}return n(e,t),e.prototype.clear=function(){t.prototype.clear.call(this),this.tree_.clear()},e.prototype.swap=function(t){var e,n;e=o([t.data_,this.data_],2),this.data_=e[0],t.data_=e[1],C._Swap_associative(this.data_,t.data_),D._Swap_source(this.tree_,t.tree_),n=o([t.tree_,this.tree_],2),this.tree_=n[0],t.tree_=n[1]},e.prototype.key_comp=function(){return this.tree_.key_comp()},e.prototype.lower_bound=function(t){return this.tree_.lower_bound(t)},e.prototype.upper_bound=function(t){return this.tree_.upper_bound(t)},e.prototype._Handle_insert=function(t,e){for(;!t.equals(e);t=t.next())this.tree_.insert(t)},e.prototype._Handle_erase=function(t,e){for(;!t.equals(e);t=t.next())this.tree_.erase(t)},e}(E),function(t){t.Iterator=C.Iterator,t.ReverseIterator=C.ReverseIterator}(t.TreeMultiSet||(t.TreeMultiSet={})),Object.defineProperty(t,"__esModule",{value:!0}),t}({});

return t
})();

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 l = 0;
    var t = +lines[l++];
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        var t1 = lines[l++].split(' ').map(Number)
        var t2 = lines[l++].split(' ').map(Number)
        console.log(solve(n, t1, t2))
    }
});

let TIMER, L, R
let SET, ANS
function solve(n, t1, t2) {
    // load 2 trees
    const adj1 = {}
    t1.forEach((p, i) => {
        adj1[p] = adj1[p] || []
        adj1[p].push(i + 2)
    })
    const adj2 = {}
    t2.forEach((p, i) => {
        adj2[p] = adj2[p] || []
        adj2[p].push(i + 2)
    })

    // dfs 2
    TIMER = 0
    L = []
    R = []
    dfs2(adj2, 1)

    // dfs 1
    SET = new TreeMultiSet((a, b) => L[a] < L[b]) // [[L[u], u]], means the dfs path
    ANS = 0
    try {
    dfs1(adj1, 1)
    } catch (e) {
        return e.stack
    }
    return ANS
}

function print() {
    let iter = SET.begin()
    const ans = []
    while (iter !== SET.end()) {
        ans.push(iter.value)
        iter = iter.next()
    }
    console.log(ans.join(' '))
}

function dfs1(adj, r) {
    const stack = [[r, 0, -1]]
    const befores = []
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            // lower bound, the first >= L[u]
            const iter = SET.lower_bound(u)
            const before = iter.prev()
            // exists someone after u
            const hasChild = iter !== SET.end() && isAncestor(u, iter.value)
            // exists someone before u, check
            // don't worry about the earier ones, they must be safe with each other
            const hasAncestor = iter !== SET.begin() && isAncestor(before.value, u)

            if (!hasChild) {
                // add self
                add(u)
            }
            if (hasAncestor) {
                // erease the ancestor
                erase(before.value)
                befores[u] = before
            }
            ANS = Math.max(ANS, SET.size());
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            stack.pop()

            const before = befores[u]
            // recover the path
            erase(u)
            if (before) {
                add(before.value)
            }
        }
    }
}
function dfs2(adj, r) {
    const stack = [[r, 0, -1]]
    while (stack.length) {
        const [u, i, p] = stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            L[u] = TIMER++
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            stack.pop()
            R[u] = TIMER
        }
    }
}
function isAncestor(u, v) { // u is the ancestor of v
    return L[u] <= L[v] && R[v] <= R[u]
}

function add(u) {
    SET.insert(u)
    // const idx = binarySearch(0, SET.length - 1, x => SET[x][0] < L[u])
    // SET.splice(idx + 1, 0, [L[u], u])
}
function erase(u) {
    SET.erase(u)
    // const idx = binarySearch(0, SET.length - 1, x => SET[x][0] <= L[u])
    // SET.splice(idx, 1)
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

const TreeMultiSet = (function () {
var{TreeMultiSet:t}=function(t){
/*! *****************************************************************************
        Copyright (c) Microsoft Corporation.

        Permission to use, copy, modify, and/or distribute this software for any
        purpose with or without fee is hereby granted.

        THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
        REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
        AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
        INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
        LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
        OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
        PERFORMANCE OF THIS SOFTWARE.
        ***************************************************************************** */
var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}function r(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function o(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,o,i=n.call(t),s=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(t){o={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function i(t,e,n){if(n||2===arguments.length)for(var r,o=0,i=e.length;o<i;o++)!r&&o in e||(r||(r=Array.prototype.slice.call(e,0,o)),r[o]=e[o]);return t.concat(r||Array.prototype.slice.call(e))}var s,u=function(){function t(t,e){this.it_=t,this.last_=e}return t.prototype.next=function(){if(this.it_.equals(this.last_))return{done:!0,value:void 0};var t=this.it_;return this.it_=this.it_.next(),{done:!1,value:t.value}},t.prototype[Symbol.iterator]=function(){return this},t}(),a=function(){function t(){}return t.prototype.empty=function(){return 0===this.size()},t.prototype.rbegin=function(){return this.end().reverse()},t.prototype.rend=function(){return this.begin().reverse()},t.prototype[Symbol.iterator]=function(){return new u(this.begin(),this.end())},t.prototype.toJSON=function(){var t,e,n=[];try{for(var o=r(this),i=o.next();!i.done;i=o.next()){var s=i.value;n.push(s)}}catch(e){t={error:e}}finally{try{i&&!i.done&&(e=o.return)&&e.call(o)}finally{if(t)throw t.error}}return n},t}(),c=function(){function t(t,e){this.data_=t,this.index_=e}return t.prototype.index=function(){return this.index_},Object.defineProperty(t.prototype,"value",{get:function(){return this.data_[this.index_]},enumerable:!1,configurable:!0}),t.prototype.prev=function(){return--this.index_,this},t.prototype.next=function(){return++this.index_,this},t.prototype.advance=function(t){return this.index_+=t,this},t.prototype.equals=function(t){return this.data_===t.data_&&this.index_===t.index_},t.prototype.swap=function(t){var e,n;e=o([t.data_,this.data_],2),this.data_=e[0],t.data_=e[1],n=o([t.index_,this.index_],2),this.index_=n[0],t.index_=n[1]},t}(),_=function(t){function e(e){var n=t.call(this)||this;return n.data_=e(n),n}return n(e,t),e.prototype.assign=function(t,e){this.clear(),this.insert(t,e)},e.prototype.clear=function(){this.data_.clear()},e.prototype.begin=function(){return this.data_.begin()},e.prototype.end=function(){return this.data_.end()},e.prototype.has=function(t){return!this.find(t).equals(this.end())},e.prototype.size=function(){return this.data_.size()},e.prototype.push=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(0===t.length)return this.size();var n=new c(t,0),r=new c(t,t.length);return this._Insert_by_range(n,r),this.size()},e.prototype.insert=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 1===t.length?this._Insert_by_key(t[0]):t[0].next instanceof Function&&t[1].next instanceof Function?this._Insert_by_range(t[0],t[1]):this._Insert_by_hint(t[0],t[1])},e.prototype.erase=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return 1!==t.length||t[0]instanceof this.end().constructor&&t[0].source()===this?1===t.length?this._Erase_by_range(t[0]):this._Erase_by_range(t[0],t[1]):this._Erase_by_val(t[0])},e.prototype._Erase_by_range=function(t,e){void 0===e&&(e=t.next());var n=this.data_.erase(t,e);return this._Handle_erase(t,e),n},e}(a),l=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.insert=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return t.prototype.insert.apply(this,i([],o(e),!1))},e.prototype._Erase_by_val=function(t){var e=this.find(t);if(!0===e.equals(this.end()))return 0;for(var n=e.next(),r=1;!n.equals(this.end())&&this._Key_eq(t,n.value);)n=n.next(),++r;return this._Erase_by_range(e,n),r},e.prototype.merge=function(t){this.insert(t.begin(),t.end()),t.clear()},e}(_);!function(t){t.construct=function(t){for(var e,n,r=[],s=1;s<arguments.length;s++)r[s-1]=arguments[s];return r.length>=1&&r[0]instanceof Array?(e=function(){var e=r[0];t.push.apply(t,i([],o(e),!1))},n=r.slice(1)):r.length>=2&&r[0].next instanceof Function&&r[1].next instanceof Function?(e=function(){var e=r[0],n=r[1];t.assign(e,n)},n=r.slice(2)):(e=null,n=r),{ramda:e,tail:n}}}(s||(s={}));var h=null;function p(){return null===y&&(null===h&&(h="object"==typeof global&&"object"==typeof global.process&&"object"==typeof global.process.versions&&void 0!==global.process.versions.node),void 0===(y=h?global:self).__s_iUID&&(y.__s_iUID=0)),y}var f,y=null;function v(t){if(t instanceof Object){if(!1===t.hasOwnProperty("__get_m_iUID")){var e=++p().__s_iUID;Object.defineProperty(t,"__get_m_iUID",{value:function(){return e}})}return t.__get_m_iUID()}return void 0===t?-1:0}function d(t,e){return t=t?t.valueOf():t,e=e?e.valueOf():e,t instanceof Object&&t.equals instanceof Function?t.equals(e):t===e}function g(t,e){return t=t.valueOf(),e=e.valueOf(),t instanceof Object?t.less instanceof Function?t.less(e):v(t)<v(e):t<e}function b(t,e){return e^=t?1:0,e*=k}function m(t,e){return x(t.toString(),e)}function x(t,e){for(var n=0;n<t.length;++n)e^=t.charCodeAt(n),e*=k;return Math.abs(e)}!function(t){t.construct=function(t,e,n){for(var r=[],u=3;u<arguments.length;u++)r[u-3]=arguments[u];var a=null,c=g;if(1===r.length&&r[0]instanceof e){var _=r[0];c=_.key_comp(),a=function(){var e=_.begin(),n=_.end();t.assign(e,n)}}else{var l=s.construct.apply(s,i([t],o(r),!1));a=l.ramda,l.tail.length>=1&&(c=l.tail[0])}n(c),null!==a&&a()},t.emplacable=function(t,e,n){var r=e.prev(),o=r.equals(t.end())||t.value_comp()(r.value,n);return o=o&&(e.equals(t.end())||t.value_comp()(n,e.value))}}(f||(f={}));var w,I=2166136261,k=16777619,q=function(){function t(t,e){this.first=t,this.second=e}return t.prototype.equals=function(t){return d(this.first,t.first)&&d(this.second,t.second)},t.prototype.less=function(t){return!1===d(this.first,t.first)?g(this.first,t.first):g(this.second,t.second)},t.prototype.hashCode=function(){return function(){for(var t,e,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var i=I;try{for(var s=r(n),u=s.next();!u.done;u=s.next()){var a=u.value,c=typeof(a=a?a.valueOf():a);if("boolean"===c)i=b(a,i);else if("number"===c||"bigint"===c)i=m(a,i);else if("string"===c)i=x(a,i);else if(a instanceof Object&&a.hashCode instanceof Function){var _=a.hashCode();if(1===n.length)return _;i^=_,i*=k}else i=m(v(a),i)}}catch(e){t={error:e}}finally{try{u&&!u.done&&(e=s.return)&&e.call(s)}finally{if(t)throw t.error}}return Math.abs(i)}(this.first,this.second)},t}(),E=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.find=function(t){var e=this.lower_bound(t);return!e.equals(this.end())&&this._Key_eq(t,e.value)?e:this.end()},e.prototype.count=function(t){for(var e=this.find(t),n=0;!e.equals(this.end())&&this._Key_eq(e.value,t);e=e.next())++n;return n},e.prototype.equal_range=function(t){return new q(this.lower_bound(t),this.upper_bound(t))},e.prototype.value_comp=function(){return this.key_comp()},e.prototype._Key_eq=function(t,e){return!this.key_comp()(t,e)&&!this.key_comp()(e,t)},e.prototype._Insert_by_key=function(t){var e=this.upper_bound(t);return e=this.data_.insert(e,t),this._Handle_insert(e,e.next()),e},e.prototype._Insert_by_hint=function(t,e){if(f.emplacable(this,t,e)){var n=this.data_.insert(t,e);return this._Handle_insert(n,n.next()),n}return this._Insert_by_key(e)},e.prototype._Insert_by_range=function(t,e){for(var n=t;!n.equals(e);n=n.next())this._Insert_by_key(n.value)},e}(l),O=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e}(function(t){function e(e){var n=this.constructor,r=t.call(this,e)||this,o=n.prototype;return Object.setPrototypeOf?Object.setPrototypeOf(r,o):r.__proto__=o,r}return n(e,t),Object.defineProperty(e.prototype,"name",{get:function(){return this.constructor.name},enumerable:!1,configurable:!0}),e.prototype.what=function(){return this.message},e.prototype.toJSON=function(){return{name:this.name,message:this.message,stack:this.stack}},e}(Error)),F=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e}(O),S=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e}(O);!function(t){function e(t){if("string"==typeof t)return t;var e=t.constructor.name;return t.constructor.__MODULE&&(e=t.constructor.__MODULE+"."+e),"std."+e}t.get_class_name=e,t.empty=function(t,n){return new S("Error on "+e(t)+"."+n+"(): it's empty container.")},t.negative_index=function(t,n,r){return new S("Error on "+e(t)+"."+n+"(): parametric index is negative -> (index = "+r+").")},t.excessive_index=function(t,n,r,o){return new S("Error on "+e(t)+"."+n+"(): parametric index is equal or greater than size -> (index = "+r+", size: "+o+").")},t.not_my_iterator=function(t,n){return new F("Error on "+e(t)+"."+n+"(): parametric iterator is not this container's own.")},t.erased_iterator=function(t,n){return new F("Error on "+e(t)+"."+n+"(): parametric iterator, it already has been erased.")},t.negative_iterator=function(t,n,r){return new S("Error on "+e(t)+"."+n+"(): parametric iterator is directing negative position -> (index = "+r+").")},t.iterator_end_value=function(t,n){void 0===n&&(n="end");var r=e(t);return new S("Error on "+r+".Iterator.value: cannot access to the "+r+"."+n+"().value.")},t.key_nout_found=function(t,n,r){throw new S("Error on "+e(t)+"."+n+"(): unable to find the matched key -> "+r)}}(w||(w={}));var j=function(){function t(t,e,n){this.prev_=t,this.next_=e,this.value_=n}return t._Set_prev=function(t,e){t.prev_=e},t._Set_next=function(t,e){t.next_=e},t.prototype.prev=function(){return this.prev_},t.prototype.next=function(){return this.next_},Object.defineProperty(t.prototype,"value",{get:function(){return this._Try_value(),this.value_},enumerable:!1,configurable:!0}),t.prototype._Try_value=function(){if(void 0===this.value_&&!0===this.equals(this.source().end()))throw w.iterator_end_value(this.source())},t.prototype.equals=function(t){return this===t},t}(),z=function(){function t(t,e){this.index_=t,this.value_=e}return t.prototype.index=function(){return this.index_},Object.defineProperty(t.prototype,"value",{get:function(){return this.value_},enumerable:!1,configurable:!0}),t.prototype.next=function(){return++this.index_,this},t.prototype.equals=function(t){return this.index_===t.index_},t}();var R=function(t){function e(){var e=t.call(this)||this;return e.end_=e._Create_iterator(null,null),e.clear(),e}return n(e,t),e.prototype.assign=function(t,e){this.clear(),this.insert(this.end(),t,e)},e.prototype.clear=function(){j._Set_prev(this.end_,this.end_),j._Set_next(this.end_,this.end_),this.begin_=this.end_,this.size_=0},e.prototype.resize=function(t){var e=t-this.size();e>0?this.insert(this.end(),e,void 0):e<0&&this.erase(function(t,e){if(0===e)return t;if(t.advance instanceof Function)return t.advance(e);var n;if(e<0){if(!(t.prev instanceof Function))throw new F("Error on std.advance(): parametric iterator is not a bi-directional iterator, thus advancing to negative direction is not possible.");n=function(t){return t.prev()},e=-e}else n=function(t){return t.next()};for(;e-- >0;)t=n(t);return t}(this.end(),-e),this.end())},e.prototype.begin=function(){return this.begin_},e.prototype.end=function(){return this.end_},e.prototype.size=function(){return this.size_},e.prototype.push_front=function(t){this.insert(this.begin_,t)},e.prototype.push_back=function(t){this.insert(this.end_,t)},e.prototype.pop_front=function(){if(!0===this.empty())throw w.empty(this.end_.source().constructor.name,"pop_front");this.erase(this.begin_)},e.prototype.pop_back=function(){if(!0===this.empty())throw w.empty(this.end_.source().constructor.name,"pop_back");this.erase(this.end_.prev())},e.prototype.push=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(0===t.length)return this.size();var n=new c(t,0),r=new c(t,t.length);return this._Insert_by_range(this.end(),n,r),this.size()},e.prototype.insert=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t.source()!==this.end_.source())throw w.not_my_iterator(this.end_.source(),"insert");if(!0===t.erased_)throw w.erased_iterator(this.end_.source(),"insert");return 1===e.length?this._Insert_by_repeating_val(t,1,e[0]):2===e.length&&"number"==typeof e[0]?this._Insert_by_repeating_val(t,e[0],e[1]):this._Insert_by_range(t,e[0],e[1])},e.prototype._Insert_by_repeating_val=function(t,e,n){var r=new z(0,n),o=new z(e);return this._Insert_by_range(t,r,o)},e.prototype._Insert_by_range=function(t,e,n){for(var r=t.prev(),o=null,i=0,s=e;!1===s.equals(n);s=s.next()){var u=this._Create_iterator(r,null,s.value);0===i&&(o=u),j._Set_next(r,u),r=u,++i}return!0===t.equals(this.begin())&&(this.begin_=o),j._Set_next(r,t),j._Set_prev(t,r),this.size_+=i,o},e.prototype.erase=function(t,e){return void 0===e&&(e=t.next()),this._Erase_by_range(t,e)},e.prototype._Erase_by_range=function(t,e){if(t.source()!==this.end_.source())throw w.not_my_iterator(this.end_.source(),"insert");if(!0===t.erased_)throw w.erased_iterator(this.end_.source(),"insert");if(t.equals(this.end_))return this.end_;var n=t.prev();j._Set_next(n,e),j._Set_prev(e,n);for(var r=t;!r.equals(e);r=r.next())r.erased_=!0,--this.size_;return t.equals(this.begin_)&&(this.begin_=e),e},e.prototype.swap=function(t){var e,n,r;e=o([t.begin_,this.begin_],2),this.begin_=e[0],t.begin_=e[1],n=o([t.end_,this.end_],2),this.end_=n[0],t.end_=n[1],r=o([t.size_,this.size_],2),this.size_=r[0],t.size_=r[1]},e}(a),P=function(){function t(t){this.base_=t.prev()}return t.prototype.source=function(){return this.base_.source()},t.prototype.base=function(){return this.base_.next()},Object.defineProperty(t.prototype,"value",{get:function(){return this.base_.value},enumerable:!1,configurable:!0}),t.prototype.prev=function(){return this._Create_neighbor(this.base().next())},t.prototype.next=function(){return this._Create_neighbor(this.base_)},t.prototype.equals=function(t){return this.base_.equals(t.base_)},t}(),C=function(t){function e(e){var n=t.call(this)||this;return n.associative_=e,n}return n(e,t),e.prototype._Create_iterator=function(t,n,r){return e.Iterator.create(this,t,n,r)},e._Swap_associative=function(t,e){var n;n=o([e.associative_,t.associative_],2),t.associative_=n[0],e.associative_=n[1]},e.prototype.associative=function(){return this.associative_},e}(R);!function(t){var e=function(t){function e(e,n,r,o){var i=t.call(this,n,r,o)||this;return i.source_=e,i}return n(e,t),e.create=function(t,n,r,o){return new e(t,n,r,o)},e.prototype.reverse=function(){return new r(this)},e.prototype.source=function(){return this.source_.associative()},e}(j);t.Iterator=e;var r=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype._Create_neighbor=function(t){return new e(t)},e}(P);t.ReverseIterator=r}(C||(C={}));var M=function(){function t(t,e){this.value=t,this.color=e,this.parent=null,this.left=null,this.right=null}return Object.defineProperty(t.prototype,"grand",{get:function(){return this.parent.parent},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"sibling",{get:function(){return this===this.parent.left?this.parent.right:this.parent.left},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"uncle",{get:function(){return this.parent.sibling},enumerable:!1,configurable:!0}),t}(),D=function(t){function e(e,n){return t.call(this,e,n,(function(t,e){var r=n(t.value,e.value);return r||n(e.value,t.value)?r:v(t)<v(e)}))||this}return n(e,t),e.prototype.insert=function(e){v(e),t.prototype.insert.call(this,e)},e.prototype._Nearest_by_key=function(t,e){if(null===this.root_)return null;for(var n=this.root_,r=null;;){var o=n.value,i=null;if(this.key_comp()(t,o.value)?i=n.left:this.key_comp()(o.value,t)?i=n.right:(r=n,i=e(n)),null===i)break;n=i}return null!==r?r:n},e.prototype.nearest_by_key=function(t){return this._Nearest_by_key(t,(function(t){return t.left}))},e.prototype.upper_bound=function(t){var e=this._Nearest_by_key(t,(function(t){return t.right}));if(null===e)return this.source().end();var n=e.value;return this.key_comp()(t,n.value)?n:n.next()},e}(function(t){function e(e,n,r){var o=t.call(this,r)||this;return o.source_=e,o.key_comp_=n,o.key_eq_=function(t,e){return!n(t,e)&&!n(e,t)},o}return n(e,t),e._Swap_source=function(t,e){var n;n=o([e.source_,t.source_],2),t.source_=n[0],e.source_=n[1]},e.prototype.get_by_key=function(t){var e=this.nearest_by_key(t);return null!==e&&this.key_eq_(t,e.value.value)?e:null},e.prototype.lower_bound=function(t){var e=this.nearest_by_key(t);return null===e?this.source_.end():this.key_comp_(e.value.value,t)?e.value.next():e.value},e.prototype.equal_range=function(t){return new q(this.lower_bound(t),this.upper_bound(t))},e.prototype.source=function(){return this.source_},e.prototype.key_comp=function(){return this.key_comp_},e.prototype.key_eq=function(){return this.key_eq_},e.prototype.value_comp=function(){return this.key_comp_},e}(function(){function t(t){this.root_=null,this.comp_=t,this.equal_=function(e,n){return!t(e,n)&&!t(n,e)}}return t.prototype.clear=function(){this.root_=null},t.prototype.root=function(){return this.root_},t.prototype.get=function(t){var e=this.nearest(t);return null!==e&&this.equal_(t,e.value)?e:null},t.prototype.nearest=function(t){if(null===this.root_)return null;for(var e=this.root_;;){var n=null;if(this.comp_(t,e.value))n=e.left;else{if(!this.comp_(e.value,t))return e;n=e.right}if(null===n)break;e=n}return e},t.prototype._Fetch_maximum=function(t){for(;null!==t.right;)t=t.right;return t},t.prototype.insert=function(t){var e=this.nearest(t),n=new M(t,1);null===e?this.root_=n:(n.parent=e,this.comp_(n.value,e.value)?e.left=n:e.right=n),this._Insert_case1(n)},t.prototype._Insert_case1=function(t){null===t.parent?t.color=0:this._Insert_case2(t)},t.prototype._Insert_case2=function(t){0!==this._Fetch_color(t.parent)&&this._Insert_case3(t)},t.prototype._Insert_case3=function(t){1===this._Fetch_color(t.uncle)?(t.parent.color=0,t.uncle.color=0,t.grand.color=1,this._Insert_case1(t.grand)):this._Insert_case4(t)},t.prototype._Insert_case4=function(t){t===t.parent.right&&t.parent===t.grand.left?(this._Rotate_left(t.parent),t=t.left):t===t.parent.left&&t.parent===t.grand.right&&(this._Rotate_right(t.parent),t=t.right),this._Insert_case5(t)},t.prototype._Insert_case5=function(t){t.parent.color=0,t.grand.color=1,t===t.parent.left&&t.parent===t.grand.left?this._Rotate_right(t.grand):this._Rotate_left(t.grand)},t.prototype.erase=function(t){var e=this.get(t);if(null!==e){if(null!==e.left&&null!==e.right){var n=this._Fetch_maximum(e.left);e.value=n.value,e=n}var r=null===e.right?e.left:e.right;0===this._Fetch_color(e)&&(e.color=this._Fetch_color(r),this._Erase_case1(e)),this._Replace_node(e,r),1===this._Fetch_color(this.root_)&&(this.root_.color=0)}},t.prototype._Erase_case1=function(t){null!==t.parent&&this._Erase_case2(t)},t.prototype._Erase_case2=function(t){1===this._Fetch_color(t.sibling)&&(t.parent.color=1,t.sibling.color=0,t===t.parent.left?this._Rotate_left(t.parent):this._Rotate_right(t.parent)),this._Erase_case3(t)},t.prototype._Erase_case3=function(t){0===this._Fetch_color(t.parent)&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,this._Erase_case1(t.parent)):this._Erase_case4(t)},t.prototype._Erase_case4=function(t){1===this._Fetch_color(t.parent)&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,t.parent.color=0):this._Erase_case5(t)},t.prototype._Erase_case5=function(t){t===t.parent.left&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&1===this._Fetch_color(t.sibling.left)&&0===this._Fetch_color(t.sibling.right)?(t.sibling.color=1,t.sibling.left.color=0,this._Rotate_right(t.sibling)):t===t.parent.right&&null!==t.sibling&&0===this._Fetch_color(t.sibling)&&0===this._Fetch_color(t.sibling.left)&&1===this._Fetch_color(t.sibling.right)&&(t.sibling.color=1,t.sibling.right.color=0,this._Rotate_left(t.sibling)),this._Erase_case6(t)},t.prototype._Erase_case6=function(t){t.sibling.color=this._Fetch_color(t.parent),t.parent.color=0,t===t.parent.left?(t.sibling.right.color=0,this._Rotate_left(t.parent)):(t.sibling.left.color=0,this._Rotate_right(t.parent))},t.prototype._Rotate_left=function(t){var e=t.right;this._Replace_node(t,e),t.right=e.left,null!==e.left&&(e.left.parent=t),e.left=t,t.parent=e},t.prototype._Rotate_right=function(t){var e=t.left;this._Replace_node(t,e),t.left=e.right,null!==e.right&&(e.right.parent=t),e.right=t,t.parent=e},t.prototype._Replace_node=function(t,e){null===t.parent?this.root_=e:t===t.parent.left?t.parent.left=e:t.parent.right=e,null!==e&&(e.parent=t.parent)},t.prototype._Fetch_color=function(t){return null===t?0:t.color},t}()));return t.TreeMultiSet=function(t){function e(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var s=t.call(this,(function(t){return new C(t)}))||this;return f.construct.apply(f,i([s,e,function(t){s.tree_=new D(s,t)}],o(n),!1)),s}return n(e,t),e.prototype.clear=function(){t.prototype.clear.call(this),this.tree_.clear()},e.prototype.swap=function(t){var e,n;e=o([t.data_,this.data_],2),this.data_=e[0],t.data_=e[1],C._Swap_associative(this.data_,t.data_),D._Swap_source(this.tree_,t.tree_),n=o([t.tree_,this.tree_],2),this.tree_=n[0],t.tree_=n[1]},e.prototype.key_comp=function(){return this.tree_.key_comp()},e.prototype.lower_bound=function(t){return this.tree_.lower_bound(t)},e.prototype.upper_bound=function(t){return this.tree_.upper_bound(t)},e.prototype._Handle_insert=function(t,e){for(;!t.equals(e);t=t.next())this.tree_.insert(t)},e.prototype._Handle_erase=function(t,e){for(;!t.equals(e);t=t.next())this.tree_.erase(t)},e}(E),function(t){t.Iterator=C.Iterator,t.ReverseIterator=C.ReverseIterator}(t.TreeMultiSet||(t.TreeMultiSet={})),Object.defineProperty(t,"__esModule",{value:!0}),t}({});

return t
})();

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 l = 0;
    var t = +lines[l++];
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        var t1 = lines[l++].split(' ').map(Number)
        var t2 = lines[l++].split(' ').map(Number)
        console.log(solve(n, t1, t2))
    }
});

let TIMER, L, R
let SET, ANS
function solve(n, t1, t2) {
    // load 2 trees
    const adj1 = {}
    t1.forEach((p, i) => {
        adj1[p] = adj1[p] || []
        adj1[p].push(i + 2)
    })
    const adj2 = {}
    t2.forEach((p, i) => {
        adj2[p] = adj2[p] || []
        adj2[p].push(i + 2)
    })

    // dfs 2
    TIMER = 0
    L = []
    R = []
    dfs2(adj2, 1)

    // dfs 1
    SET = new TreeMultiSet((a, b) => L[a] < L[b]) // [[L[u], u]], means the dfs path
    ANS = 0
    try {
    dfs1(adj1, 1)
    } catch (e) {
        return e.stack
    }
    return ANS
}

function print() {
    let iter = SET.begin()
    const ans = []
    while (iter !== SET.end()) {
        ans.push(iter.value)
        iter = iter.next()
    }
    console.log(ans.join(' '))
}

function dfs1(adj, u) {
    // lower bound, the first >= L[u]
    // const idx = binarySearch(0, SET.length - 1, x => SET[x][0] < L[u]) + 1
    // const before = SET[idx - 1]
    // const after = SET[idx]
    // console.log(SET.begin() === SET.end().prev(), SET.size())
    const iter = SET.lower_bound(u)
    const before = iter.prev()
    // const after = iter
    // exists someone after u
    const hasChild = iter !== SET.end() && isAncestor(u, iter.value)
    // const hasChild = idx !== SET.length && isAncestor(u, after[1])

    // exists someone before u, check
    // don't worry about the earier ones, they must be safe with each other
    const hasAncestor = iter !== SET.begin() && isAncestor(before.value, u)
    // const hasAncestor = idx > 0 && isAncestor(before[1], u)
    if (!hasChild) {
        // add self
        add(u)
    }
    if (hasAncestor) {
        // erease the ancestor
        erase(before.value)
    }
    ANS = Math.max(ANS, SET.size());

    // recursion
    (adj[u] || []).forEach(v => {
        dfs1(adj, v)
    })

    // recover the path
    erase(u)
    if (hasAncestor) {
        add(before.value)
    }
}
function dfs2(adj, u) {
    L[u] = TIMER++
    (adj[u] || []).forEach(v => {
        dfs2(adj, v)
    })
    R[u] = TIMER
}
function isAncestor(u, v) { // u is the ancestor of v
    return L[u] <= L[v] && R[v] <= R[u]
}

function add(u) {
    SET.insert(u)
    // const idx = binarySearch(0, SET.length - 1, x => SET[x][0] < L[u])
    // SET.splice(idx + 1, 0, [L[u], u])
}
function erase(u) {
    SET.erase(u)
    // const idx = binarySearch(0, SET.length - 1, x => SET[x][0] <= L[u])
    // SET.splice(idx, 1)
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}


You have an axis-aligned rectangle room with width $$$W$$$ and height $$$H$$$, so the lower left corner is in point $$$(0, 0)$$$ and the upper right corner is in $$$(W, H)$$$.There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in $$$(x_1, y_1)$$$, and the upper right corner in $$$(x_2, y_2)$$$.You want to place another rectangular table in this room with width $$$w$$$ and height $$$h$$$ with the width of the table parallel to the width of the room.The problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though).You can't rotate any of the tables, but you can move the first table inside the room.   Example of how you may move the first table. What is the minimum distance you should move the first table to free enough space for the second one?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of the test cases. The first line of each test case contains two integers $$$W$$$ and $$$H$$$ ($$$1 \le W, H \le 10^8$$$) — the width and the height of the room. The second line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$0 \le x_1 < x_2 \le W$$$; $$$0 \le y_1 < y_2 \le H$$$) — the coordinates of the corners of the first table. The third line contains two integers $$$w$$$ and $$$h$$$ ($$$1 \le w \le W$$$; $$$1 \le h \le H$$$) — the width and the height of the second table.

For each test case, print the minimum distance you should move the first table, or $$$-1$$$ if there is no way to free enough space for the second table. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.

NoteThe configuration of the first test case is shown in the picture. But the movement of the first table is not optimal. One of the optimal movement, for example, is to move the table by $$$(0, -1)$$$, so the lower left corner will move from $$$(2, 1)$$$ to $$$(2, 0)$$$. Then you can place the second table at $$$(0, 3)-(4, 5)$$$.In the second test case, there is no way to fit both tables in the room without intersecting.In the third test case, you can move the first table by $$$(0, 2)$$$, so the lower left corner will move from $$$(0, 3)$$$ to $$$(0, 5)$$$.

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let [rw, rh] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseFloat(cur));
    let [x1, y1, x2, y2] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseFloat(cur));
    let u = rh - y2,
      r = rw - x2,
      l = x1,
      d = y1;
    let [tw, th] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseFloat(cur));
    let ans = Infinity;
    if (l >= tw) ans = 0;
    if (r >= tw - l && tw - l >= 0) ans = Math.min(ans, tw - l);
    if (r >= tw) ans = 0;
    if (l >= tw - r && tw - r >= 0) ans = Math.min(ans, tw - r);
    if (u >= th) ans = 0;
    if (d >= th - u && th - u >= 0) ans = Math.min(ans, th - u);
    if (d >= th) ans = 0;
    if (u >= th - d && th - d >= 0) ans = Math.min(ans, th - d);
    if (ans === Infinity) ans = -1;
    console.log(ans);
  }
};
solve();

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

let INF = 2e8;
function main () {
	let t = rn();
	while (t--) {
		let [W, H] = rna();
		let [x1, y1, x2, y2] = rna();
		let [w, h] = rna();

		hmx = Math.max(H - y2, y1);
		wmx = Math.max(x1, W - x2);

		if (w < wmx || h < hmx)
			console.log(0);
		else {
			let ans1 = ans2 = INF;
			if (h + (y2 - y1) <= H) {
				ans1 = h - hmx;
			}

			if (w + (x2 - x1) <= W) {
				ans2 = w - wmx;
			}

			console.log((ans1 & ans2) == INF ? -1 : Math.min(ans1, ans2));
		}
	}
}

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 [W, H] = lines[l++].split(' ').map(Number)
        var [x1, y1, x2, y2] = lines[l++].split(' ').map(Number)
        var [w, h] = lines[l++].split(' ').map(Number)
        console.log(solve(W, H, x1, y1, x2, y2, w, h))
    }
});

function solve(W, H, x1, y1, x2, y2, w, h) {
    const l = x1
    const r = W - x2
    const t = H - y2
    const b = y1
    // console.log(l, r, t, b)
    let d1 = -1
    let d2 = -1
    if (l + r >= w) {
        d1 = h > H ? -1 : Math.max(0, w - Math.max(l, r))
    }
    if (t + b >= h) {
        d2 = w > W ? -1 : Math.max(0, h - Math.max(t, b))
    }

    if (d1 >= 0 && d2 >= 0) {
        return Math.min(d1, d2)
    } else if (d1 >= 0) {
        return d1
    } else if (d2 >= 0) {
        return d2
    }
    return -1
}

'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(e)
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(n => {
      stdin.on('data', n => e.push(n)),
        stdin.on('end', function () {
          const t = e.join('').split(os.EOL)
          n(t)
        })
    })
  }
}
async function __main__(e) {
  const n = new InputAndOutput()
  await n.init(), e(n)
}
function solve(e, n, t, i, s, r, u, d) {
  if (u > e || d > n) return -1
  if (u + (s - t) > e && d + (r - i) > n) return -1
  if (u <= t || u + s <= e) return 0
  if (d <= i || d + r <= n) return 0
  let o = Number.MAX_SAFE_INTEGER
  return (
    u + (s - t) <= e && (o = Math.min(o, u - t, u + s - e)),
    d + (r - i) <= n && (o = Math.min(o, d - i, d + r - n)),
    o
  )
}
__main__(function (e) {
  const n = Number(e.readLine())
  for (let t = 1; t <= n; ++t) {
    const [n, t] = e.readIntegersOfLine(),
      [i, s, r, u] = e.readIntegersOfLine(),
      [d, o] = e.readIntegersOfLine(),
      a = solve(n, t, i, s, r, u, d, o)
    e.print(a + '\n')
  }
})

const setTable = (rWH, t1P, t2WH ) => {
    var rW = rWH[0];
    var rH = rWH[1];

    var t1X1 = t1P[0];
    var t1Y1 = t1P[1];
    var t1X2 = t1P[2];
    var t1Y2 = t1P[3];
    var t1W = t1X2 - t1X1;
    var t1H = t1Y2 - t1Y1;

    var t2W = t2WH[0];
    var t2H = t2WH[1];

    if((t1W + t2W > rW) && (t1H + t2H > rH)) {
        return -1;
    }

    var fSW = Math.max(t1X1, rW - t1X2);
    var fSH = Math.max(t1Y1, rH - t1Y2);

    var shift = Math.min(
        t1W + t2W > rW ? Infinity : t2W - fSW,
        t1H + t2H > rH ? Infinity : t2H - fSH
    );

    return shift >= 0 ? shift : 0;
};

const n = +readline();

var roomWH;
var table1Points;
var table2WH;

for(var i = 0; i < n; i++) {
    roomWH = readline().split(" ").map(i => +i);
    table1Points = readline().split(" ").map(i => +i);
    table2WH = readline().split(" ").map(i => +i);
    print(setTable(roomWH, table1Points, table2WH));
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let [rw, rh] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseFloat(cur));
    let [x1, y1, x2, y2] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseFloat(cur));
    let u = rh - y2,
      r = rw - x2,
      l = x1,
      d = y1;
    let [tw, th] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseFloat(cur));
    let ans = Infinity;
    if (l >= tw) ans = 0;
    if (r >= tw - l) ans = Math.min(ans, tw - l);
    if (r >= tw) ans = 0;
    if (l >= tw - r) ans = Math.min(ans, tw - r);
    if (u >= th) ans = 0;
    if (d >= th - u) ans = Math.min(ans, th - u);
    if (d >= th) ans = 0;
    if (u >= th - d) ans = Math.min(ans, th - d);
    if (ans === Infinity) ans = -1;
    console.log(ans);
  }
};
solve();

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 [W, H] = lines[l++].split(' ').map(Number)
        var [x1, y1, x2, y2] = lines[l++].split(' ').map(Number)
        var [w, h] = lines[l++].split(' ').map(Number)
        console.log(solve(W, H, x1, y1, x2, y2, w, h))
    }
});

function solve(W, H, x1, y1, x2, y2, w, h) {
    const l = x1
    const r = W - x2
    const t = H - y2
    const b = y1
    // console.log(l, r, t, b)
    if (l + r >= w) {
        return h > H ? -1 : Math.max(0, w - Math.max(l, r))
    }
    if (t + b >= h) {
        return w > W ? -1 : Math.max(0, h - Math.max(t, b))
    }
    return -1
}

'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(e)
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(n => {
      stdin.on('data', n => e.push(n)),
        stdin.on('end', function () {
          const t = e.join('').split(os.EOL)
          n(t)
        })
    })
  }
}
async function __main__(e) {
  const n = new InputAndOutput()
  await n.init(), e(n)
}
const MAX_N = 100010,
  sum1 = new Array(MAX_N)
function solve(e, n, t) {
  if (e <= 1) return 0
  sum1[0] = n[0]
  for (let t = 1; t < e; ++t) sum1[t] = sum1[t - 1] + n[t]
  const s = e - 1
  let i = sum1[s] - n[0]
  for (let n = 1, r = t[0]; n < e; ++n) {
    const e = Math.max(sum1[s] - sum1[n], r)
    ;(r += t[n]), i > e && (i = e)
  }
  return i
}
__main__(function (e) {
  const n = Number(e.readLine())
  for (let t = 1; t <= n; ++t) {
    const n = solve(
      Number(e.readLine()),
      e.readIntegersOfLine(),
      e.readIntegersOfLine(),
    )
    e.print(n + '\n')
  }
})