You are given an array $$$a_1, a_2, \dots , a_n$$$ consisting of integers from $$$0$$$ to $$$9$$$. A subarray $$$a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r$$$ is good if the sum of elements of this subarray is equal to the length of this subarray ($$$\sum\limits_{i=l}^{r} a_i = r - l + 1$$$).For example, if $$$a = [1, 2, 0]$$$, then there are $$$3$$$ good subarrays: $$$a_{1 \dots 1} = [1], a_{2 \dots 3} = [2, 0]$$$ and $$$a_{1 \dots 3} = [1, 2, 0]$$$.Calculate the number of good subarrays of the array $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains a string consisting of $$$n$$$ decimal digits, where the $$$i$$$-th digit is equal to the value of $$$a_i$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the number of good subarrays of the array $$$a$$$.

NoteThe first test case is considered in the statement.In the second test case, there are $$$6$$$ good subarrays: $$$a_{1 \dots 1}$$$, $$$a_{2 \dots 2}$$$, $$$a_{1 \dots 2}$$$, $$$a_{4 \dots 4}$$$, $$$a_{5 \dots 5}$$$ and $$$a_{4 \dots 5}$$$. In the third test case there is only one good subarray: $$$a_{2 \dots 6}$$$.

T = readline();
while (T--) {
  n = readline()
  a = readline()
  m = new Map()
  m.set(0, 1)
  ans = 0
  sum = 0
  for (i = 0; i < n; i++) {
    sum += +a[i]
    x = sum - i - 1
    if (!m.has(x))
      m.set(x, 0)
    m.set(x, m.get(x) + 1)
    ans += m.get(x) - 1
  }
  print(ans)
}

T = readline()
while (T--) {
  n = readline(); a = readline()
  m = new Map([[0, 1]])
  ans = 0; sum = 0
  for (i = 0; i < n; i++) {
    sum += +a[i]
    x = sum - i - 1
    if (!m.has(x))
      m.set(x, 0)
    v = m.get(x)
    m.set(x, v + 1)
    ans += v
  }
  print(ans)
}

T = readline();
while (T--) {
  n = readline()
  a = readline()
  m = new Map()
  m.set(0, 1)
  ans = 0
  sum = 0
  for (i = 0; i < n; i++) {
    sum += +a[i]
    x = sum - i - 1
    if (!m.has(x))
      m.set(x, 0)
    v = m.get(x)
    m.set(x, v + 1)
    ans += v
  }
  print(ans)
}

var readline=require('readline');
var rl=readline.createInterface({
    input:process.stdin,
    output:process.stdout
});
var arr=[];
rl.on('line',function(inp){
    arr.push(inp);
    var len=arr.length;
    if(len%2===1&&len>1){
        var n=parseInt(arr[arr.length-2]),
            a=arr[arr.length-1].split(''),
            sum=0,ans=0,obj={};
        for(var i=0;i<n;i++){
            a[i]=parseInt(a[i]);
            sum+=a[i];
            var t=sum-i-1;
            if(sum===i+1) ans++;
            if(!(t in obj)) obj[t]=1;
            else{
                ans+=obj[t];
                obj[t]++;
            }
        }
        console.log(ans);
    }
    if(len===parseInt(arr[0])*2+1) process.exit(0);
});

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

function readDOM() {
    return stdinReadAll();
}

let CONFIG = {
    // getStringFunc: readDOM
};

stdioCPPattern(CONFIG, ({ readNum, readStr, writeLine }) => {
    // your code goes here
    let tc_count = readNum();

    const specVal = Array(1e5 + 9);
    const tracer = Array(1e6).fill(0);
    let n, counter, curPreSum, digitString, digit, sp;

    specVal[0] = 0;

    while (tc_count--) {

        n = readNum();

        const addendum = n;
        counter = 0;
        tracer[addendum] = 1;
        curPreSum = 0;

        digitString = readStr(n);

        for (let i = 1; i <= n; i++) {
            digit = digitString.codePointAt(i - 1) - 48;
            curPreSum += digit;

            sp = specVal[i] = curPreSum - i + addendum;
            counter += tracer[sp];
            tracer[sp]++;
        }
        writeLine(counter);
        // reset tracer
        tracer[addendum] = 0;
        for (let i = 1; i <= n; i++) {
            sp = specVal[i];
            tracer[sp] = 0;
        }
    }
});

/**
 * @author flynn
 */
function stdinReadAll() {
    const fs = require("fs");
    return fs.readFileSync(0).toString();
}

function stdioCPPattern({
    getStringFunc = stdinReadAll
}, callbackfn) {
    const aStr = getStringFunc() + "\n";

    let cur = 0;
    const resultList = [];// Array(numberOfLine);
    const seperator = /\s/;

    callbackfn({
        log: console.log,
        readNum() {
            let x = 0, ch = aStr.charCodeAt(cur) - 48;
            while (ch < 0 || 9 < ch) ch = aStr.charCodeAt(++cur) - 48;
            while (0 <= ch && ch <= 9) {
                x = x * 10 + ch;
                ch = aStr.charCodeAt(++cur) - 48;
            }
            return x;
        },
        writeLine(data) {
            resultList.push(`${data}`);
        },
        readStr(len = 1e6) {
            const chArr = Array(len);
            let ch = aStr[cur], i = 0;
            while (seperator.test(ch)) ch = aStr[++cur];
            while (!seperator.test(ch)) {
                chArr[i++] = ch;
                ch = aStr[++cur];
            }
            return chArr.join("");
        }
    });
    let prompt = resultList.join("\n");
    if (prompt) console.log(prompt);
}

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();
    const arr = readLine()
      .split("")
      .map((n) => parseInt(n - 1));
    const map = { 0: 1 };
    let [sum, count] = [0, 0];

    arr.forEach((num) => {
      sum += num;
      if (map[sum]) {
        count += map[sum];
        map[sum]++;
      } else {
        map[sum] = 1;
      }
    });
    console.log(count);
  }
}

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 _i = 0; _i < t; _i++) {
	const n = Number(readLine())
    const arr = Array.from(readLine()).map(s => Number(s) - 1)
    const nums = {}
    nums[0] = 1
    let total = 0
    for (let i = 0; i < n; i++) {
      total += arr[i]
      if (!nums[total]) {
        nums[total] = 0
      }
      nums[total] += 1
    }
    console.log(Object.values(nums).reduce((acc, curr) => acc + curr * (curr - 1) / 2, 0))
  }
}

'use strict';

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

let inputString = '';
let inputArray = [];
let currentLine = 0;

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

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

  main();
});

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

function main() {
  const t = parseInt(readline());
  for (let i=0; i<t; i++) {
    const n = parseInt(readline());
    const a = readline().split("").map(x => parseInt(x));

    let good = 0;
    let sum = 0;
    let m = new Map();
    m.set(0,1);
    for (let j=0; j<n; j++) {
      sum += a[j];
      let x = sum - j - 1;
      m.set(x, (m.get(x)|0) + 1);
    }

    for (let [k,v] of m) {
      good += v * (v-1) / 2;
    }
    console.log(good);
  }
}

const solution = (string) => {
    const nums = string.split('').map(Number)
    let sum = 0
    const grid = nums.map((n, i) => {
        sum += n
        return sum - (i + 1)
    })
    grid.push(0)
    const freq = {}
    for (const num of grid) {
        freq[num] =
            1 +
            (freq[num] || 0)
    }

    let result = 0
    for (const count of Object.values(freq)) {
        result += count * (count - 1) / 2
    }

    return result
}

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

    // every other line, without the first line
    for (let i = 2; i < lines.length; i += 2) {
        console.log(solution(lines[i]))
    }
})

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

    C();
});

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

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

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

    return a;
}

function C(){
    let t = pi(readline());
    while(t){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(''));
        let s = res = 0;
        let map = {0:1};
        for(let i = 0; i < n; i++){
            s += a[i];
            let x = s-i-1;
            if(map[x] === undefined){
                map[x] = 0;
            }
            map[x] += 1;
            res += map[x]-1;
        }
        console.log(res);
    }
}

T = readline()
while (T--) {
  n = readline(); a = readline()
  m = new Map([[0, 1]])
  ans = 0; sum = 0
  for (i = 0; i < n; i++) {
    sum += +a[i]
    const x = sum - i - 1
    if (!m.has(x))
      m.set(x, 0)
    const v = m.get(x)
    m.set(x, v + 1)
    ans += v
  }
  print(ans)
}

T = readline()
while (T--) {
  n = readline(); a = readline()
  m = new Map()
  m.set(0, 1)
  ans = 0; sum = 0
  for (i = 0; i < n; i++) {
    sum += +a[i]
    const x = sum - i - 1
    if (!m.has(x))
      m.set(x, 0)
    const v = m.get(x)
    m.set(x, v + 1)
    ans += v
  }
  print(ans)
}

'use strict';

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

let inputString = '';
let inputArray = [];
let currentLine = 0;

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

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

  main();
});

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

function main() {
  const t = parseInt(readline());
  for (let i=0; i<t; i++) {
    const n = parseInt(readline());
    const a = readline().split("").map(x => parseInt(x));

    let good = 0;
    let sum = 0;
    let m = new Map();
    m.set(0,1);
    for (let j=0; j<n; j++) {
      sum += a[j];
      let x = sum - j - 1;
      m.set(x, (m.get(x)|0) + 1);
    }

    for (let [k,v] of m) {
      console.log(k,v);
      good += v * (v-1) / 2;
    }
    console.log(good);
  }
}


Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:  there wouldn't be a pair of any side-adjacent cards with zeroes in a row;  there wouldn't be a group of three consecutive cards containing numbers one. Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.

The first line contains two integers: n (1 ≤ n ≤ 106) — the number of cards containing number 0; m (1 ≤ m ≤ 106) — the number of cards containing number 1.

In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1.

print(function(m, n) {
	var max = (m + 1) * 2;
	var min = m - 1;
	if (n < min || n > max)
		return -1;

	var ans=[];
	if(n===min){
		for(var i=0;i<min;i++)
			ans.push('01');
		ans.push('0');
	}else if(n===m){
		for(var i=0;i<m;i++)
			ans.push('01');
	}else if(n===m+1){
		for(var i=0;i<m;i++)
			ans.push('10');
		ans.push('1');
	}else{
		var x=n%(m+1)||max;
		for(var i=0;i<m;i++){
			ans.push(i<x?'11':'1');
			ans.push('0');
		}
		ans.push(n===max?'11':'1');
	}
	return ans.join('');

}.apply(0, readline().split(' ').map(Number)));

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var zero = integers[0], one = integers[1];

	if (one < zero-1 || one > 2*zero + 2) {
		print(-1);
		return;
	}

	var solution = [];
	function push(s) {
		solution.push(s);
	}

	while (one > 2*zero) {
		push("1");
		one -= 1;
	}
	while (one > zero) {
		push("011");
		one -= 2;
		zero -= 1;
	}
	while (one > 0) {
		push("01");
		one -= 1;
		zero -= 1;
	}
	if (zero == 1) {
		push("0");
	}

	print(solution.join(""));
}

main();

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var zero = integers[0], one = integers[1];

	var solution = [];
	function push(s, k) {
		if (k === undefined) {
			solution.push(s);
			return;
		}
		for (var i = 0; i < k; ++i) {
			solution.push(s);
		}
	}

	if (2*zero == one) {
		push("011", zero);
	}

	else if (2*zero == one-1) {
		push("1");
		push("011", zero);
	}
	else if (2*zero == one-2) {
		push("11");
		push("011", zero);
	}

	else if (2*(zero-1) == one-1) {
		push("1");
		push("011", zero-1);
		push("0");
	}
	else if (2*(zero-1) == one-2) {
		push("11");
		push("011", zero-1);
		push("0");
	}

	else if (2*(zero-1) == one-3) {
		push("11");
		push("011", zero-1);
		push("01");
	}

	else if (2*(zero-1) == one) {
		push("011", zero-1);
		push("0");
	}

	else {
		print(-1);
		return;
	}

	print(solution.join(""));
}

main();


Byteland is a beautiful land known because of its beautiful trees.Misha has found a binary tree with $$$n$$$ vertices, numbered from $$$1$$$ to $$$n$$$. A binary tree is an acyclic connected bidirectional graph containing $$$n$$$ vertices and $$$n - 1$$$ edges. Each vertex has a degree at most $$$3$$$, whereas the root is the vertex with the number $$$1$$$ and it has a degree at most $$$2$$$.Unfortunately, the root got infected.The following process happens $$$n$$$ times:  Misha either chooses a non-infected (and not deleted) vertex and deletes it with all edges which have an end in this vertex or just does nothing.  Then, the infection spreads to each vertex that is connected by an edge to an already infected vertex (all already infected vertices remain infected). As Misha does not have much time to think, please tell him what is the maximum number of vertices he can save from the infection (note that deleted vertices are not counted as saved).

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 5000$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2\leq n\leq 3\cdot 10^5$$$) — the number of vertices of the tree.  The $$$i$$$-th of the following $$$n-1$$$ lines in the test case contains two positive integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), meaning that there exists an edge between them in the graph.  It is guaranteed that the graph is a binary tree rooted at $$$1$$$. It is also guaranteed that the sum of $$$n$$$ over all test cases won't exceed $$$3\cdot 10^5$$$.

For each test case, output the maximum number of vertices Misha can save.

NoteIn the first test case, the only possible action is to delete vertex $$$2$$$, after which we save $$$0$$$ vertices in total.In the second test case, if we delete vertex $$$2$$$, we can save vertices $$$3$$$ and $$$4$$$.

'use strict';

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  const add = (i, j) => {
    g[i].push(j);
  };
  for (let [i, j] of a) {
    add(i - 1, j - 1);
    add(j - 1, i - 1);
  }
  g[0].push(-1);
  const st = new Array(n).fill(0);
  const cache = Array.from({
    length: n
  }, () => [-1, -1]);
  const dfs1 = RTI((i, state) => {
    if (st[i] !== 0) return [() => [], () => 0];
    if (cache[i][state] !== -1) return [() => [], () => cache[i][state]];
    st[i] = 1;
    let res = 0;
    if (state === 1) {
      const inside = () => {
        let calls = [];
        for (let j of g[i]) {
          calls.push([j, 1]);
        }
        return calls;
      };
      const after = (...args) => {
        res = args.reduce((a, b) => a + b, 1);
        st[i] = 0;
        cache[i][state] = res;
        return res;
      };
      return [inside, after];
    } else {
      if (g[i].length === 2) {
        const inside = () => [[g[i].filter(j => !st[j])[0], 1]];
        const after = (...args) => {
          res = args[0] - 1;
          st[i] = 0;
          cache[i][state] = res;
          return res;
        };
        return [inside, after];
      } else if (g[i].length > 2) {
        const [a, b] = g[i].filter(j => !st[j]);
        const inside = () => {
          return [[a, 0], [b, 1], [a, 1], [b, 0]];
        };
        const after = (...args) => {
          const [a, b, c, d] = args;
          res = Math.max(a + b - 1, c - 1 + d);
          st[i] = 0;
          cache[i][state] = res;
          return res;
        };
        return [inside, after];
      } else {
        const inside = () => {
          return [];
        };
        const after = () => {
          st[i] = 0;
          cache[i][state] = res;
          return res;
        };
        return [inside, after];
      }
    }
  });
  let res = dfs1(0, 0);
  return res;
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = result => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, ...curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

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

'use strict';

async function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  const add = (i, j) => {
    g[i].push(j);
  };
  for (let [i, j] of a) {
    add(i - 1, j - 1);
    add(j - 1, i - 1);
  }
  g[0].push(-1);
  const st = new Array(n).fill(0);
  const cache = Array.from({
    length: n
  }, () => [-1, -1]);
  const dfs1 = RTI((i, state) => {
    if (st[i] !== 0) return [() => [], () => 0];
    if (cache[i][state] !== -1) return [() => [], () => cache[i][state]];
    st[i] = 1;
    let res = 0;
    if (state === 1) {
      const inside = () => {
        let calls = [];
        for (let j of g[i]) {
          calls.push([j, 1]);
        }
        return calls;
      };
      const after = (...args) => {
        res = args.reduce((a, b) => a + b, 1);
        st[i] = 0;
        cache[i][state] = res;
        return res;
      };
      return [inside, after];
    } else {
      if (g[i].length === 2) {
        const inside = () => [[g[i].filter(j => !st[j])[0], 1]];
        const after = (...args) => {
          res = args[0] - 1;
          st[i] = 0;
          cache[i][state] = res;
          return res;
        };
        return [inside, after];
      } else if (g[i].length > 2) {
        const [a, b] = g[i].filter(j => !st[j]);
        const inside = () => {
          return [[a, 0], [b, 1], [a, 1], [b, 0]];
        };
        const after = (...args) => {
          const [a, b, c, d] = args;
          res = Math.max(a + b - 1, c - 1 + d);
          st[i] = 0;
          cache[i][state] = res;
          return res;
        };
        return [inside, after];
      } else {
        const inside = () => {
          return [];
        };
        const after = () => {
          st[i] = 0;
          cache[i][state] = res;
          return res;
        };
        return [inside, after];
      }
    }
  });
  let res = dfs1(0, 0);
  return res;
}
function RTI(fn) {
  let res;
  const createNode = args => {
    return {
      args,
      result: [],
      curIndex: 0
    };
  };
  const dfs = (...args) => {
    const root = createNode([args]);
    root.cb = result => res = result;
    const callStack = [root];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (curCall && curCall.args.length === curCall.curIndex) {
        var _curCall$cb, _curCall;
        const res = (_curCall$cb = (_curCall = curCall).cb) === null || _curCall$cb === void 0 ? void 0 : _curCall$cb.call(_curCall, ...curCall.result);
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall) curCall.result[curCall.curIndex++] = res;
      }
      if (!curCall) break;
      const {
        args,
        curIndex
      } = curCall;
      {
        const res = fn(...args[curIndex]);
        const [inside, after] = res;
        let nextCall = inside();
        const node = createNode(nextCall);
        node.cb = after;
        callStack.push(node);
      }
    }
    return res;
  };
  return dfs;
}

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

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

'use strict';

var worker_threads = require('worker_threads');

async function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  const add = (i, j) => {
    g[i].push(j);
  };
  for (let [i, j] of a) {
    add(i - 1, j - 1);
    add(j - 1, i - 1);
  }
  g[0].push(-1);
  const st = new Array(n).fill(0);
  const cache = Array.from({
    length: n
  }, () => [-1, -1]);
  const dfs = async (i, state) => {
    if (st[i] !== 0) return 0;
    if (cache[i][state] !== -1) return cache[i][state];
    st[i] = 1;
    let res = 0;
    if (state === 1) {
      res = 1;
      for (let j of g[i]) {
        res += await dfs(j, 1);
      }
    } else {
      if (g[i].length === 2) {
        res = (await dfs(g[i].filter(j => !st[j])[0], 1)) - 1;
      } else if (g[i].length > 2) {
        const [a, b] = g[i].filter(j => !st[j]);
        res = Math.max((await dfs(a, 0)) + (await dfs(b, 1)) - 1, (await dfs(a, 1)) - 1 + (await dfs(b, 0)));
      }
    }
    st[i] = 0;
    cache[i][state] = res;
    return res;
  };
  return dfs(0, 0);
}

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

let str = '';
function exec(script, data) {
  return new Promise((resolve, reject) => {
    const worker = new worker_threads.Worker(script, {
      workerData: data,
      eval: true
    });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', code => {
      if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  str.split('\n').values();
  const script =
  `
const { workerData } = require('worker_threads')
const inputs = workerData.split('\\n').values()
function read() {
  return inputs.next().value.trim()
}
${solve.toString()}
${main.toString()}

void async function () {
  const output = await main(read)
  console.log(output)
}()
`;
  exec(script, str);
});

'use strict';

async function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  const add = (i, j) => {
    g[i].push(j);
  };
  for (let [i, j] of a) {
    add(i - 1, j - 1);
    add(j - 1, i - 1);
  }
  g[0].push(-1);
  const st = new Array(n).fill(0);
  const cache = Array.from({
    length: n
  }, () => [-1, -1]);
  const dfs = async (i, state) => {
    if (st[i] !== 0) return 0;
    if (cache[i][state] !== -1) return cache[i][state];
    st[i] = 1;
    let res = 0;
    if (state === 1) {
      res = 1;
      for (let j of g[i]) {
        res += await dfs(j, 1);
      }
    } else {
      if (g[i].length === 2) {
        res = (await dfs(g[i].filter(j => !st[j])[0], 1)) - 1;
      } else if (g[i].length > 2) {
        const [a, b] = g[i].filter(j => !st[j]);
        res = Math.max((await dfs(a, 0)) + (await dfs(b, 1)) - 1, (await dfs(a, 1)) - 1 + (await dfs(b, 0)));
      }
    }
    st[i] = 0;
    cache[i][state] = res;
    return res;
  };
  return dfs(0, 0);
}

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

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

'use strict';

function solve(n, a) {
  const topo = () => {
    const g = Array.from({
      length: n
    }, () => []);
    const add = (i, j) => g[i].push(j);
    for (let [i, j] of a) {
      add(i - 1, j - 1);
      add(j - 1, i - 1);
    }
    const query = [0];
    const g1 = Array.from({
      length: n
    }, () => []),
          d = new Array(n).fill(0);
    const add1 = (i, j) => {
      g1[i].push(j);
      d[j]++;
    };
    const st = [];
    for (let u of query) {
      st[u] = 1;
      for (let v of g[u]) {
        if (st[v]) continue;
        add1(v, u);
        query.push(v);
      }
    }
    return [g1, d];
  };
  const [g, d] = topo();
  const dp = Array.from({
    length: n
  }, () => [0, 1]);
  const temp = Array.from({
    length: n
  }, () => []);
  const query = [];
  for (let [i, di] of d.entries()) if (di === 0) query.push(i);
  for (let u of query) {
    for (let v of g[u]) {
      d[v]--;
      dp[v][1] += dp[u][1];
      temp[v].push(u);
      if (d[v] === 0) {
        query.push(v);
        let s0 = temp[v].reduce((a, b) => a + dp[b][0], 0);
        let max = 0;
        for (let i of temp[v]) {
          max = Math.max(max, s0 - dp[i][0] + dp[i][1] - 1);
        }
        dp[v][0] = max;
      }
    }
  }
  return dp[0][0];
}

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

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

'use strict';

function solve(n, a) {
  const topo = () => {
    const g = Array.from({
      length: n
    }, () => []);
    const add = (i, j) => g[i].push(j);
    for (let [i, j] of a) {
      add(i - 1, j - 1);
      add(j - 1, i - 1);
    }
    const query = [0];
    const g1 = Array.from({
      length: n
    }, () => []),
          d = new Array(n).fill(0);
    const add1 = (i, j) => {
      g1[i].push(j);
      d[j]++;
    };
    const st = [];
    for (let u of query) {
      st[u] = 1;
      for (let v of g[u]) {
        if (st[v]) continue;
        add1(v, u);
        query.push(v);
      }
    }
    return [g1, d];
  };
  const [g, d] = topo();
  const dp = Array.from({
    length: n
  }, () => [0, 0, 1]);
  const temp = Array.from({
    length: n
  }, () => []);
  const query = [];
  for (let [i, di] of d.entries()) if (di === 0) query.push(i);
  for (let u of query) {
    for (let v of g[u]) {
      d[v]--;
      dp[v][2] += dp[u][2];
      dp[v][0] += dp[u][2];
      temp[v].push(u);
      if (d[v] === 0) {
        query.push(v);
        let s0 = temp[v].reduce((a, b) => a + dp[b][1], 0);
        let max = 0;
        for (let i of temp[v]) {
          max = Math.max(max, s0 - dp[i][1] + dp[i][0]);
        }
        dp[v][1] = max;
      }
    }
  }
  return dp[0][1];
}

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

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

'use strict';

var worker_threads = require('worker_threads');

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  const add = (i, j) => {
    g[i].push(j);
  };
  for (let [i, j] of a) {
    add(i - 1, j - 1);
    add(j - 1, i - 1);
  }
  g[0].push(-1);
  const st = new Array(n).fill(0);
  const cache = Array.from({
    length: n
  }, () => [-1, -1]);
  const dfs = (i, state) => {
    if (st[i] !== 0) return 0;
    if (cache[i][state] !== -1) return cache[i][state];
    st[i] = 1;
    let res = 0;
    if (state === 1) {
      res = 1;
      for (let j of g[i]) {
        res += dfs(j, 1);
      }
    } else {
      if (g[i].length === 2) {
        res = dfs(g[i].filter(j => !st[j])[0], 1) - 1;
      } else if (g[i].length > 2) {
        const [a, b] = g[i].filter(j => !st[j]);
        res = Math.max(dfs(a, 0) + dfs(b, 1) - 1, dfs(a, 1) - 1 + dfs(b, 0));
      }
    }
    st[i] = 0;
    cache[i][state] = res;
    return res;
  };
  return dfs(0, 0);
}

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

let str = '';
function exec(script, data) {
  return new Promise((resolve, reject) => {
    const worker = new worker_threads.Worker(script, {
      workerData: data,
      eval: true
    });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', code => {
      if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  str.split('\n').values();
  const script =
  `
const { workerData } = require('worker_threads')
const inputs = workerData.split('\\n').values()
function read() {
  return inputs.next().value.trim()
}
${solve.toString()}
${main.toString()}

void async function () {
  const output = await main(read)
  console.log(output)
}()
`;
  exec(script, str);
});

'use strict';

var worker_threads = require('worker_threads');

async function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  const add = (i, j) => {
    g[i].push(j);
  };
  for (let [i, j] of a) {
    add(i - 1, j - 1);
    add(j - 1, i - 1);
  }
  g[0].push(-1);
  const st = new Array(n).fill(0);
  const cache = Array.from({
    length: n
  }, () => [-1, -1]);
  const dfs = async (i, state) => {
    if (st[i] !== 0) return 0;
    if (cache[i][state] !== -1) return cache[i][state];
    st[i] = 1;
    let res = 0;
    if (state === 1) {
      res = 1;
      for (let j of g[i]) {
        res += await dfs(j, 1);
      }
    } else {
      if (g[i].length === 2) {
        res = (await dfs(g[i].filter(j => !st[j])[0], 1)) - 1;
      } else if (g[i].length > 2) {
        const [a, b] = g[i].filter(j => !st[j]);
        res = Math.max((await dfs(a, 0)) + (await dfs(b, 1)) - 1, (await dfs(a, 1)) - 1 + (await dfs(b, 0)));
      }
    }
    st[i] = 0;
    cache[i][state] = res;
    return res;
  };
  return dfs(0, 0);
}

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

let inputs,
    str = '';
function exec(script, data) {
  return new Promise((resolve, reject) => {
    const worker = new worker_threads.Worker(script, {
      workerData: data,
      eval: true
    });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', code => {
      if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const script =
  `
const { workerData } = require('worker_threads')
let idx = 0
function read() {
  return workerData[idx++]
}
${main.toString()}

void async function () {
  const output = main(read)
  console.log(output)
}
`;
  exec(script, inputs);
});

'use strict';

const {
  Worker, isMainThread, parentPort, workerData
} = require('worker_threads');

function parseJSAsync(script, workerData) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(script, { eval: true, workerData });
    worker.on('message', resolve);
    worker.on('error', reject);
    worker.on('exit', (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });
};

var readline = require('readline');

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

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

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    const b = (await read()).split(' ').map(Number);
    const d = (await read()).split(' ').map(Number);
    // res.push(await solve(n, a, b, d));
    const ans = await parseJSAsync(`
        const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
        parentPort.postMessage(solve(...workerData))
        function solve(n, a, b, d) {
          const MOD = BigInt(10 ** 9 + 7);
          const set = new Set();
          {
            const g = Array.from({
              length: n + 1
            }, () => [0, 0]);
            for (let i = 0; i < n; i++) {
              g[a[i]][0] = i;
              g[b[i]][1] = i;
            }
            for (let i = 0; i < n; i++) {
              if (d[i] !== 0) {
                const queue = [a[i], b[i]];
                for (let j of queue) {
                  set.add(j);
                  for (let k of [b[g[j][0]], a[g[j][1]]]) {
                    if (set.has(k)) continue;
                    queue.push(k);
                  }
                }
              } else if (a[i] === b[i]) {
                set.add(a[i]);
              }
            }
          }
          const g = Array.from({
            length: n + 1
          }, () => new Set());
          for (let i = 0; i < n; i++) {
            if (d[i] === 0) {
              const u = a[i],
                v = b[i];
              if (set.has(u) || set.has(v)) continue;
              g[u].add(v);
              g[v].add(u);
            }
          }
          const tarjan = () => {
            const dfn = [],
              low = [],
              stack = [],
              set = new Set(),
              map = new Map();
            let time = 1,
              idx = 0;
            const dfs = u => {
              dfn[u] = low[u] = time++;
              stack.push(u);
              set.add(u);
              for (let v of g[u]) {
                if (!dfn[v]) {
                  dfs(v);
                  low[u] = Math.min(low[u], low[v]);
                } else if (set.has(v)) {
                  low[u] = Math.min(low[u], dfn[v]);
                }
              }
              if (dfn[u] === low[u]) {
                while (true) {
                  const j = stack.pop();
                  set.delete(j);
                  map.set(j, idx);
                  if (j === u) break;
                }
                idx++;
              }
            };
            for (let i = 1; i <= n; i++) {
              if (!dfn[i] && g[i].size) dfs(i);
            }
            return BigInt(2) ** BigInt(idx) % MOD;
          };
          return tarjan();
        }
    `, [n, a, b, d])
    res.push(ans)
  }
  console.log(res.map(num => num.toString()).join('\n'));
}

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

'use strict';

var readline = require('readline');

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

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

async function solve(n, a, b, d) {
  const MOD = BigInt(10 ** 9 + 7);
  const set = new Set();
  {
    const g = Array.from({
      length: n + 1
    }, () => [0, 0]);
    for (let i = 0; i < n; i++) {
      g[a[i]][0] = i;
      g[b[i]][1] = i;
    }
    for (let i = 0; i < n; i++) {
      if (d[i] !== 0) {
        const queue = [a[i], b[i]];
        for (let j of queue) {
          set.add(j);
          for (let k of [b[g[j][0]], a[g[j][1]]]) {
            if (set.has(k)) continue;
            queue.push(k);
          }
        }
      } else if (a[i] === b[i]) {
        set.add(a[i]);
      }
    }
  }
  const g = Array.from({
    length: n + 1
  }, () => new Set());
  for (let i = 0; i < n; i++) {
    if (d[i] === 0) {
      const u = a[i],
            v = b[i];
      if (set.has(u) || set.has(v)) continue;
      g[u].add(v);
      g[v].add(u);
    }
  }
  const tarjan = async () => {
    const dfn = [],
          low = [],
          stack = [],
          set = new Set(),
          map = new Map();
    let time = 1,
        idx = 0;
    const dfs = RTI((u, p) => {
      const before = () => {
        dfn[u] = low[u] = time++;
        stack.push(u);
        set.add(u);
      };
      const inside = () => {
        let res = [];
        for (let v of g[u]) {
          if (!dfn[v]) {
            res.push([v, u]);
          } else if (set.has(v)) {
            low[u] = Math.min(low[u], dfn[v]);
          }
        }
        return res;
      };
      const after = () => {
        if (dfn[u] === low[u]) {
          while (true) {
            const j = stack.pop();
            set.delete(j);
            map.set(j, idx);
            if (j === u) break;
          }
          idx++;
        }
        if (p !== -1) low[p] = Math.min(low[p], low[u]);
      };
      return [before, inside, after];
    });
    for (let i = 1; i <= n; i++) {
      if (!dfn[i] && g[i].size) dfs(i, -1);
    }
    return BigInt(2) ** BigInt(idx) % MOD;
  };
  return tarjan();
}
function RTI(fn) {
  const done = () => {};
  const dfs = (...args) => {
    const callStack = [[done, args]];
    while (callStack.length) {
      let curCall = callStack[callStack.length - 1];
      while (((_curCall = curCall) === null || _curCall === void 0 ? void 0 : _curCall.length) === 1) {
        var _curCall;
        const after = curCall.pop();
        after();
        callStack.pop();
        curCall = callStack[callStack.length - 1];
        if (curCall && curCall.length > 1) curCall.pop();
      }
      if (!curCall) break;
      const args = curCall[curCall.length - 1];
      const [before, inside, after] = fn(...args);
      before();
      let nextCall = inside();
      callStack.push([after, ...nextCall]);
    }
  };
  return dfs;
}

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

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

'use strict';

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  const add = (i, j) => {
    g[i].push(j);
  };
  for (let [i, j] of a) {
    add(i - 1, j - 1);
    add(j - 1, i - 1);
  }
  g[0].push(-1);
  const st = new Array(n).fill(0);
  const cache = Array.from({
    length: n
  }, () => [-1, -1]);
  const dfs = (i, state) => {
    if (st[i] !== 0) return 0;
    if (cache[i][state] !== -1) return cache[i][state];
    st[i] = 1;
    let res = 0;
    if (state === 1) {
      res = 1;
      for (let j of g[i]) {
        res += dfs(j, 1);
      }
    } else {
      if (g[i].length === 2) {
        res = dfs(g[i].filter(j => !st[j])[0], 1) - 1;
      } else if (g[i].length > 2) {
        const [a, b] = g[i].filter(j => !st[j]);
        res = Math.max(dfs(a, 0) + dfs(b, 1) - 1, dfs(a, 1) - 1 + dfs(b, 0));
      }
    }
    st[i] = 0;
    cache[i][state] = res;
    return res;
  };
  return dfs(0, 0);
}

async function main(read) {

    let res = [];
    let t = Number(await read());
    while (t--) {
      const n = Number(await read());
      const a = [];
      let tmp = n - 1;
      while (tmp--) {
        a.push((await read()).split(' ').map(Number));
      }
      res.push(solve(n, a));
    }
    return res.join('\n');
}

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

'use strict';

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  const add = (i, j) => {
    g[i].push(j);
  };
  for (let [i, j] of a) {
    add(i - 1, j - 1);
    add(j - 1, i - 1);
  }
  g[0].push(-1);
  const st = new Array(n).fill(0);
  const cache = Array.from({
    length: n
  }, () => [-1, -1]);
  const dfs = (i, state) => {
    if (st[i] !== 0) return 0;
    if (cache[i][state] !== -1) return cache[i][state];
    st[i] = 1;
    let res = 0;
    if (state === 1) {
      res = 1;
      for (let j of g[i]) {
        res += dfs(j, 1);
      }
    } else {
      if (g[i].length === 2) {
        res = dfs(g[i].filter(j => !st[j])[0], 1) - 1;
      } else if (g[i].length > 2) {
        const [a, b] = g[i].filter(j => !st[j]);
        res = Math.max(dfs(a, 0) + dfs(b, 1) - 1, dfs(a, 1) - 1 + dfs(b, 0));
      }
    }
    st[i] = 0;
    cache[i][state] = res;
    return res;
  };
  return dfs(0, 0);
}

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

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

'use strict';

function solve(n, a) {
  const g = Array.from({
    length: n
  }, () => []);
  const add = (i, j) => {
    g[i].push(j);
  };
  for (let [i, j] of a) {
    add(i - 1, j - 1);
    add(j - 1, i - 1);
  }
  g[0].push(-1);
  const st = new Array(n).fill(0);
  const dfs = (i, state) => {
    if (st[i] !== 0) return 0;
    st[i] = 1;
    let res = 0;
    if (state === 1) {
      res = 1;
      for (let j of g[i]) {
        res += dfs(j, 1);
      }
    } else {
      if (g[i].length === 2) {
        res = dfs(g[i].filter(j => !st[j])[0], 1) - 1;
      } else if (g[i].length > 2) {
        const [a, b] = g[i].filter(j => !st[j]);
        res = Math.max(dfs(a, 0) + dfs(b, 1) - 1, dfs(a, 1) - 1 + dfs(b, 0));
      }
    }
    st[i] = 0;
    return res;
  };
  return dfs(0, 0);
}

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

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


ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of rows of seats in the bus. Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row.  Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details.

If it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output). If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line. If there are multiple solutions, you may print any of them.

NoteNote that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.O+|+XXO|XXOX|OOXX|OXOO|OOOO|XX

// https://codeforces.com/problemset/problem/711/A

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

    console.log(main());
});

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

const main = () => {
  const inputs = [];
  let isFound = false;
  let result = "";
  const inputCount = readline();

  for (let i = 0; i < inputCount; i+= 1) {
    let input = readline();

    if (!isFound && input.indexOf("OO") >= 0) {
      isFound = true

      input = input.replace("OO", "++")
    }

    if (i + 1 === inputCount) {
      result += input
    } else {
      result += input + '\n'
    }
  }

  if (!isFound) {
    return "NO";
  }

  return "YES\n" + result;
}

function main() {
    // write code here:
    const n = Number(stdin[0]);
    var say;
    var reg = /OO/;
    for (let i = 1; i <= n; i++) {
        if (reg.test(stdin[i])) {
            stdin[0] = 'YES';
            stdin[i] = stdin[i].replace(reg, '++');
            break;
        } else {
            stdin[0] = 'NO';
        }
    }
    if (stdin[0] === 'YES') {
        for (let j = 0; j <= n; j++) {
            console.log(stdin[j]);
        }
    } else {
        console.log(stdin[0]);
    }
}

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

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

let input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  let _res = 'NO'
  let finish = false
  let count = 0
  let places = [...input.slice(1)]
  while (!finish) {
    if (count < places.length) {
      const el = places[count]
      if (el.match(/(OO)/g)) {
        places[count] = places[count].replace('OO', '++')
        _res = 'YES'
        finish = true
      }
    } else {
      finish = true
    }
    count++
  }
  if (_res === 'YES')
    console.log(_res + '\n' + places.join('\n'))
  else
    console.log(_res)
})

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

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var list = new Array(N);
  var isOK = false;
  for(var i = 0; i < N; i++){
    var tmp = next();
    if(!isOK && tmp.indexOf("OO") != -1){
      isOK = true;
      tmp = tmp.replace("OO", "++");
    }
    list[i] = tmp;
  }
  if(isOK){
    myout("YES");
    myout(myconv(list, 9));
  }else{
    myout("No");
  }
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
let ans = 'NO';
const arr = [];

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

  if (d.includes('OO') && ans === 'NO') {
    ans = 'YES';
    arr.push(d.replace('OO', '++'));
  }
  else {
    arr.push(d);
  }

  c++;
});

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

  if (ans === 'YES') {
    for (let i = 0; i < arr.length; i++) {
      console.log(arr[i]);
    }
  }
});

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

const input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  const [n] = input[0].split(' ').map(x => parseInt(x));

  const answer = []; let find = false;
  input.forEach((x, i) => {
    if (i === 0) return;

    let line = x.split('|');

    if (line[0][0] === 'O' && line[0][1] === 'O' && !find) {
      answer.push(`++|${line[1]}`); find = true;
    } else  if (line[1][0] === 'O' && line[1][1] === 'O' && !find) {
      answer.push(`${line[0]}|++`); find = true;
    } else {
      answer.push(`${line[0]}|${line[1]}`);
    }
  });

  if (!find) {
    console.log('NO');
  } else {
    console.log('YES');
    answer.forEach(x => console.log(x));
  }
});

function findAndCaptureSeats(config) {
    let regex = new RegExp('OO');
    let spaced = config.join(' ');
    if (regex.test(spaced)) {
        let seated = spaced.replace(regex, '++');
        seated = 'YES ' + seated;
        return seated.split(' ');
    }
    return ['NO'];
}

function processData(input) {
    let arr = input.split('\n');
    arr = arr.slice(1, arr.length);
    let config = findAndCaptureSeats(arr);
    for (let index = 0; index < config.length; index++) {
        console.log(config[index]);
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

var res = sol(readline());
print(res);

function sol(line1) {
    var input1 = line1.split(" ").map((x) => Number(x));

    var n = input1[0];

    var result = "NO";
    var seat = [];
    var isSeated = false;

    for (var i = 0; i < n; i++) {
        var row = readline();

        if (!isSeated && row.toString().indexOf("OO") > -1) {
            result = "YES";
            row = row.toString().replace("OO", "++", 1);
            seat.push(row);
            isSeated = true;
        }else{
            seat.push(row);
        }
    }

    if(result == "YES") {
        return result + "\n" + seat.join("\n");
    }else{
        return result;
    }
}

var rowNum = readline(),
    rows = [],
    hasSeat = false;

for (var i = 0; i < rowNum; i++) {
    rows[i] = readline().split('');
    if (rows[i][0] === rows[i][1] && rows[i][0] === 'O' && !hasSeat) {
        hasSeat = true;
        rows[i][0] = '+';
        rows[i][1] = '+';
    }
    if (rows[i][3] === rows[i][4] && rows[i][3] === 'O' && !hasSeat) {
        hasSeat = true;
        rows[i][3] = '+';
        rows[i][4] = '+';
    }
}

if (hasSeat === false) {
    print('NO');
} else {
    print('YES');
    for (var i = 0; i < rowNum; i++) {
        print(rows[i].join(''));
    }
}

var n = +readline();
var obj = {}, str, b = false, res = "";

for(var i = 0; i < n; i++) {
    str = readline();
    if (!b) {
        str = str.replace("OO", "++");
        if ( str.indexOf("++") != -1 )
            b = true;
    }
    res += str + '\n';
}

if (b) {
    print("YES");
    print(res);
} else
    print("NO");
//print(res);

var n = parseInt(readline());
var is_possible = false;
var seat_config = [];

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

    var tokens = readline().split("|");
    for(var j = 0; j <= 1; j++) {

        if(tokens[j] == "OO") {

            if(!is_possible) {
                is_possible = true;
                tokens[j] = "++";
            }
        }
    }

    seat_config[i] = tokens[0] + "|" + tokens[1];
}

print(is_possible ? 'YES' : 'NO');
if(is_possible)
    print(seat_config.join("\n"));

var n;
var arr=[];

n = readline();
for(var i = 0;i<n;++i){
    arr.push(readline())
}

var flag=false;
for(i=0;i<n;i++){
    var pos = arr[i].indexOf('OO');
    if(pos!=-1){
        flag=true;
        if(pos==0){
            arr[i]='++'+arr[i].slice(2);
        }else{
            arr[i]=arr[i].slice(0,3)+'++';
        }
        break;
    }
}

if(flag){
    print('YES');
    arr.forEach(function(item){
        print(item);
    });
}else{
    print('NO');
}

var n = readline();
var reg = /OO/
var str = "";

for (var i=0; i<n; i++){
		str+= readline()+"\n";
}

if (reg.test(str))
{
 print("YES")
 print(str.replace(reg, "++"));
}
else print("NO");

var n =  Number(readline());
var bus = [];
var checkPlace = false;

for (var i=0; i<n; i++) {
    var s = readline();
    if (!checkPlace && s.match(/OO/)) {
        s = s.replace(/OO/, '++');
        checkPlace = true;
    }
    bus.push(s);
}

if (checkPlace) {
    print( "YES" );
    print( bus.join( "\n" ) );
} else {
    print( "NO" );
}

var n = readline();
var totInput = "";
for (var i = 0 ; i < n ; i ++)
{
    totInput += '\n' + readline();
}
var ans = totInput.replace('OO','++')
write(ans !== totInput ? ("YES" + ans) : "NO")

"use strict";

var n = +readline();

var input = ''
for (var i = 0; i < n; ++i) {
   input += '\n' + readline();
}

var result = input.replace('OO', '++');

write(result !== input ? ('YES' + result) : 'NO');

if (!readline) {
    var _i = 0;
    var readline = function() {
        _i ++;

        switch (_i) {
            case 1: return '6';
            case 2: return 'OO|OX';
            case 3: return 'XO|XX';
            case 4: return 'OX|OO';
            case 5: return 'XX|OX';
            case 6: return 'OO|OO';
            case 7: return 'OO|XX';
        }
    }

    var write = console.log;
}

var n = +readline();
var a = [];
var yes = false;

for (var i = 0; i < n; i ++) {
    var s = readline();

    if (!yes) {
        if (s[0] == 'O' && s[1] == 'O') {
            yes = true;
            s = '++' + s.substr(2, 3);
        } else if (s[3] == 'O' && s[4] == 'O') {
            yes = true;
            s = s.substr(0, 3) + '++';
        }
    }

    a.push(s);
}

if (yes) {
    write('YES\n');
    write(a.join('\n'));
} else {
    write('NO');
}

var n = parseInt(readline());
var pattern = /OO/;
var rows = [];
var found = false;
for ( var i = 0; i < n; ++i ) {
    var row = readline();
    if ( !found && row.match( pattern ) ) {
        row = row.replace( pattern, "++" );
        found = true;

    }
    rows.push( row );
}

if (found) {
    print( "YES" );
    print( rows.join( "\n" ) );
} else {
    print( "NO" );
}

var n = parseInt(readline());

var bus = [];
var seatAvailable = false;

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

    var seats = readline().split("|");

    if (!seatAvailable && seats.includes('OO')) {

        var index = seats.indexOf('OO');

        seats[index] = '++';

        seatAvailable = true;
    }

    bus.push(seats.join('|'));
}

if (seatAvailable) {
    print('YES');

    for (var j = 0; j < n; j++) {
        print(bus[j]);
    }

} else {
    print('NO');
}

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

    console.log(main());
});

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

const main = () => {
  const inputs = [];
  let isFound = false;
  let result = "";
  const inputCount = readline();

  for (let i = 0; i < inputCount; i+= 1) {
    let input = readline();

    if (!isFound && input.indexOf("OO") >= 0) {
      isFound = true

      input = input.replace("OO", "++")
    }

    if (i + 1 === inputCount) { // To remove last new line
      result += input
    }

    result += input + '\n'
  }

  if (!isFound) {
    return "NO\n" + result;
  }

  return "YES\n" + result;
}

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

    console.log(main());
});

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

function main() {
  const inputs = [];
  let isFound = false;
  let result = "";
  const inputCount = readline();

  for (let i = 0; i < inputCount; i+= 1) {
    let input = readline();

    if (!isFound && input.indexOf("OO") >= 0) {
      isFound = true

      input = input.replace("OO", "++")
    }

    result += input + '\n'
  }

  if (!isFound) {
    return "NO\n" + result;
  }

  return "YES\n" + result;
}

function main() {
    // write code here:
    const n = Number(stdin[0]);
    var say;
    var reg = /OO/g;
    for (let i = 1; i <= n; i++) {
        if (reg.test(stdin[i])) {
            stdin[0] = 'YES';
            stdin[i] = stdin[i].replace(reg, '++');
            break;
        } else {
            stdin[0] = 'NO';
        }
    }
    for(let j=0;j<=n;j++){
        console.log(stdin[j]);
    }
}

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() {
    // write code here:
    const n = Number(stdin[0]);
    var say;
    var reg = /OO/g;
    for (let i = 1; i <= n; i++) {
        if (reg.test(stdin[i])) {
            stdin[0] = 'YES';
            stdin[i] = stdin[i].replace(reg, '++');
            break;
        } else {
            stdin[0] = 'NO';
        }
    }
    if (stdin[0] === 'YES') {
        for (let j = 0; j <= n; j++) {
            console.log(stdin[j]);
        }
    } else {
        console.log(stdin[0]);
    }
}

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

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

let input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  let _res = 'NO'
  let finish = false
  let count = 0
  let places = [...input.slice(1)]
  while (!finish) {
    if (count < places.length) {
      const el = places[count]
      if (el.match(/(OO)/g)) {
        places[count] = places[count].replace(/(OO)/g, '++')
        _res = 'YES'
        finish = true
      }
    } else {
      finish = true
    }
    count++
  }
  if (_res === 'YES')
    console.log(_res + '\n' + places.join('\n'))
  else
    console.log(_res)
})

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

let input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  let _res = 'NO'
  let finish = false
  let count = 0
  let places = [...input.slice(1)]
  while (!finish) {
    if (count < places.length) {
      const el = places[count]
      if (el.match(/(OO)/g)) {
        places[count] = places[count].replace(/(OO)/g, '++')
        _res = 'YES'
        finish = true
      }
    } else {
      finish = true
    }
    count++
  }
  console.log(_res + '\n' + places.join('\n'))
})

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;
let ans = 'NO';
const arr = [];

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

  if (d.includes('OO') && ans === 'NO') {
    ans = 'YES';
    arr.push(d.replace('OO', '++'));
  }
  else {
    arr.push(d);
  }

  c++;
});

rl.on('close', () => {
  console.log(ans);
  for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
  }
});

function findAndCaptureSeats(config) {
    console.log(config);
    let regex = new RegExp('OO');
    let spaced = config.join(' ');
    let seated = spaced.replace(regex, '++');
    return seated.split(' ');
}

function processData(input) {
    let arr = input.split('\n');
    arr = arr.slice(1, arr.length);
    let config = findAndCaptureSeats(arr);
    for (let index = 0; index < config.length; index++) {
        console.log(config[index]);
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

function findAndCaptureSeats(config) {
    console.log(config);
    let regex = new RegExp('OO');
    let spaced = config.join(' ');
    if (regex.test(spaced)) {
        let seated = spaced.replace(regex, '++');
        seated = 'YES ' + seated;
        return seated.split(' ');
    }
    return ['NO'];
}

function processData(input) {
    let arr = input.split('\n');
    arr = arr.slice(1, arr.length);
    let config = findAndCaptureSeats(arr);
    for (let index = 0; index < config.length; index++) {
        console.log(config[index]);
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

var res = sol(readline());
print(res);

function sol(line1) {
    var input1 = line1.split(" ").map((x) => Number(x));

    var n = input1[0];

    var result = "NO";
    var seat = [];
    var isSeated = false;

    for (var i = 0; i < n; i++) {
        var row = readline();

        if (!isSeated && row.toString().indexOf("OO") > -1) {
            result = "YES";
            row = row.toString().replace("OO", "++", 1);
            seat.push(row);
            isSeated = true;
        }else{
            seat.push(row);
        }
    }

    return result + "\n" + seat.join("\n");
}

var rowNum = readline(),
    rows = [],
    hasSeat = false;

for (var i = 0; i < rowNum; i++) {
    rows[i] = readline().split('');
    if (hasSeat) continue;
    hasSeat = true;
    if (rows[i][0] === rows[i][1] && rows[i][0] === 'O') {
        rows[i][0] = '+';
        rows[i][1] = '+';
    }

    if (rows[i][3] === rows[i][4] && rows[i][3] === 'O') {
        rows[i][3] = '+';
        rows[i][4] = '+';
    }
}

if (hasSeat === false) {
    print('NO');
} else {
    print('YES');
    for (var i = 0; i < rowNum; i++) {
        print(rows[i].join(''));
    }
}

var rowNum = readline(),
    rows = [],
    hasSeat = false;

for (var i = 0; i < rowNum; i++) {
    rows[i] = readline().split('');
    if (hasSeat) continue;
    hasSeat = true;
    if (rows[i][0] === rows[i][1] && rows[i][0] === 'O') {
        rows[i][0] = '+';
        rows[i][1] = '+';
    }

    if (rows[i][3] === rows[i][4] && rows[i][0] === 'O') {
        rows[i][3] = '+';
        rows[i][4] = '+';
    }
}

if (hasSeat === false) {
    print('NO');
} else {
    print('YES');
    for (var i = 0; i < rowNum; i++) {
        print(rows[i].join(''));
    }
}

var rowNum = readline(),
    rows = [],
    hasSeat = false;

for (var i = 0; i < rowNum; i++) {
    rows[i] = readline().split('');
    if (hasSeat) continue;
    if (rows[i][0] === rows[i][1] && rows[i][0] === 'O') {
        hasSeat = true;
        rows[i][0] = '+';
        rows[i][1] = '+';
    }

    if (rows[i][3] === rows[i][4] && rows[i][0] === 'O') {
        hasSeat = true;
        rows[i][3] = '+';
        rows[i][4] = '+';
    }
}

if (hasSeat === false) {
    print('NO');
} else {
    print('YES');
    for (var i = 0; i < rowNum; i++) {
        print(rows[i].join(''));
    }
}

var rowNum = readline(),
    rows = [],
    hasSeat = false;

for (var i = 0; i < rowNum; i++) {
    rows[i] = readline().split('');
    if (hasSeat) continue;
    if (rows[i][0] === rows[i][1] && rows[i][0] === 'O') {
        hasSeat = true;
        rows[i][0] = '+';
        rows[i][1] = '+';
    }

    if (rows[i][3] === rows[i][4] && rows[i][3] === 'O') {
        hasSeat = true;
        rows[i][3] = '+';
        rows[i][4] = '+';
    }
}

if (hasSeat === false) {
    print('NO');
} else {
    print('YES');
    for (var i = 0; i < rowNum; i++) {
        print(rows[i].join(''));
    }
}

var n = parseInt(readline());
var is_possible = false;
var seat_config = [];

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

    var tokens = readline().split("|");
    for(var j = 0; j <= 1; j++) {

        if(tokens[j] == "OO") {

            if(!is_possible) {
                is_possible = true;
                tokens[j] = "++";
            }
        }
    }

    seat_config[i] = tokens[0] + "|" + tokens[1];
}

print(is_possible ? 'YES' : 'NO');
print(seat_config.join("\n"));

var n = readline();
var reg = /OO/
var str = "";

for (var i=0; i<n; i++){
		str+= readline();
}

if (reg.test(str))
{
 print("YES")
 print(str.replace(reg, "++"));
}
else print("NO");

n=Number(readline())
ss=new Array(n)
yes=false
for (i=0;i<n;++i){
    s=readline().split('|')
    if (!yes && (s[0]=='OO' || s[1]=='OO')) {
        yes = true
        s[0] = s[0].replace('OO', '++')
        s[1] = s[1].replace('OO', '++')
    }

    ss.push(s.join('|'))
}

if (yes) {
    print('YES')
    ss.forEach(s => print(s))
} else
    print('NO')

if (!readline) {
    var _i = 0;
    var readline = function() {
        _i ++;

        switch (_i) {
            case 1: return '6';
            case 2: return 'OO|OX';
            case 3: return 'XO|XX';
            case 4: return 'OX|OO';
            case 5: return 'XX|OX';
            case 6: return 'OO|OO';
            case 7: return 'OO|XX';
        }
    }

    var write = console.log;
}

var n = +readline();
var a = [];
var yes = false;

for (var i = 0; i < n; i ++) {
    var s = readline();

    if (!yes) {
        if (s[0] == 'O' && s[1] == 'O') {
            yes = true;
            s = '++' + s.substr(2, 3);
        } else if (s[3] == 'O' && s[4] == 'O') {
            yes = true;
            s = s.substr(0, 3) + '++';
        }
    }

    a.push(s);
}

if (yes) {
    write('YES');
    write(a.join('\n'));
} else {
    write('NO');
}


You are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of points on the line. The second line contains n integers xi ( - 109 ≤ xi ≤ 109) — the coordinates of the given n points.

Print the only integer x — the position of the optimal point on the line. If there are several optimal points print the position of the leftmost one. It is guaranteed that the answer is always the integer.

var n=readline();
var arr = readline().split(" ").map(x=>{return parseInt(x)});

arr.sort((a, b) => {
    return a-b;
});

if (arr.length % 2 === 0) {
    print(arr.splice(arr.length / 2 - 1, 1));
} else {
    print(arr.splice(arr.length / 2, 1));
}

var n= readline();
var arr = readline().split(" ").map(x=>{return parseInt(x)});

positiveArr = arr.filter(elem => {
    return elem >= 0;
});

if (positiveArr.length == arr.length) {
    if (arr.length % 2 === 0)
        print(parseInt(arr.length / 2));
    else
        print(parseInt(arr.length / 2) + 1);

} else {
    print(arr.indexOf(Math.min(...arr))+1);
}

var n= readline();
var arr = readline().split(" ").map(x=>{return parseInt(x)});

positiveArr = arr.filter(elem => {
    return elem >= 0;
});
negativeArr = arr.filter(elem => {
    return elem < 0;
});

negativeArr.sort((a, b) => {
    return b - a;
});
positiveArr.sort((a, b) => {
    return a - b;
});

arr = [...negativeArr, ...positiveArr];

if (arr.length % 2 === 0) {
    print(arr.splice(arr.length / 2 - 1, 1));
} else {
    print(arr.splice(arr.length / 2, 1));
}


A sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Given two integers $$$n$$$ and $$$k$$$, construct a permutation $$$a$$$ of numbers from $$$1$$$ to $$$n$$$ which has exactly $$$k$$$ peaks. An index $$$i$$$ of an array $$$a$$$ of size $$$n$$$ is said to be a peak if $$$1 < i < n$$$ and $$$a_i \gt a_{i-1}$$$ and $$$a_i \gt a_{i+1}$$$. If such permutation is not possible, then print $$$-1$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ lines follow, each containing two space-separated integers $$$n$$$ ($$$1 \leq n \leq 100$$$) and $$$k$$$ ($$$0 \leq k \leq n$$$) — the length of an array and the required number of peaks.

Output $$$t$$$ lines. For each test case, if there is no permutation with given length and number of peaks, then print $$$-1$$$. Otherwise print a line containing $$$n$$$ space-separated integers which forms a permutation of numbers from $$$1$$$ to $$$n$$$ and contains exactly $$$k$$$ peaks.  If there are multiple answers, print any.

NoteIn the second test case of the example, we have array $$$a = [2,4,1,5,3]$$$. Here, indices $$$i=2$$$ and $$$i=4$$$ are the peaks of the array. This is because $$$(a_{2} \gt a_{1} $$$, $$$a_{2} \gt a_{3})$$$ and $$$(a_{4} \gt a_{3}$$$, $$$a_{4} \gt a_{5})$$$.

'use-strict'

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

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

        let testCases = parseInt(readLine());
        while(testCases--)
        {
            let [n, k] = get_ints();
            let a = [];
            let b = new Array(n);
            let flag = true;
            if(n/k <= 2)
            {
                print(-1);
                continue;
            }
            for(let i = 1 ; i <= n; i++)
            {
                a.push(i);
            }
            for(let i = 0 ; i < n; i++)
            {
                b[i] = a.shift();
                if(k !== 0 )
                {
                    i++;
                  b[i] = a.pop();
                  k--;
                }
            }
            if(flag) print(b.join(' '));
        }

});

function print(c){
    return console.log(c);
}

function get_ints() {
    return readLine().split(' ').map(Number)
}

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

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

//Don't have to see. end------------------------------------------

function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var K = nextInt();
		if(K * 2 + 1 > N){
			myout(-1);
			continue;
		}
		var output = new Array(N);
		for(var j = 0; j < K; j++){
			output[j * 2 + 1] = N - j;
		}
		var now = 1;
		for(var j = 0; j < N; j++){
			if(output[j] == null){
				output[j] = now;
				now++;
			}
		}
		myout(myconv(output, 8));
	}
}

process.stdin.setEncoding('utf-8')
const readline = require('readline')

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

let count = -1
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        inputArr = inputArr.map(i => i.split(' ').map(j => +j))
        main()
        process.exit(0)
    }
})

function solve([n, k]) {
    let arr = [...Array(n).keys()].map(i => i + 1)
    if (k + 1 > Math.floor((n + 1) / 2) || n < 3 && k > 0) {
        console.log('-1')
        return
    }
    if (k === 0) {
        console.log(arr.join(' '))
        return
    }
    let arr2 = [], flag = false
    arr2.push(1)
    for (let i = 2; i <= n; ++i) {
        if (k > 0 && i % 2 === 0) {
            arr2.push(i + 1)
            k--
        } else {
            if (k > 0) arr2.push(i - 1)
            else {
                if (flag) arr2.push(i)
                else {
                    arr2.push(i - 1)
                    flag = true
                }
            }
        }
    }
    console.log(arr2.join(' '))
}

function main() {
    for (let i = 0; i < inputArr.length; i++) solve(inputArr[i])
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

var maxN = 21
var mod = 1000000007

// Make a Snippet for the code above this and then write your logic in main();

function main() {
  const xx = readline();

  Array(Number(xx)).fill(1).map((t, i) => {
    // var n = parseInt(readline());
    var [n, k] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })

    if( n % 2===1 && k> Math.floor(n/2)) return console.log(-1)
    if( n % 2===0 && k>= Math.floor(n/2)) return console.log(-1)

    var ans = new Array(n)
    for (let j = 0; j < n; j++) {
      if(j % 2 ===1 && k >0){
        ans[j] = j+1
        ans[j+1] = j
        j++
        k--
        continue
      }
      ans[j] = j
    }

    console.log(ans.map(x=>x+1).join(' '))

  })
}

const t = readline();

for (var i = 0; i < parseInt(t); i++) {
  var input = readline().split(' ').map(d => parseInt(d));
  var n = input[0];
  var k = input[1];
  if (k >= parseInt((n + 1) / 2))
    print(-1);
  else {
    var a = [];
    var j = 1;
    var p = 0;
    var pk = 0;
    while (p < (n % 2? n - 1: n)) {
      a.push(j);
      p++;
      if (pk < k) {
        a.push(n - j + 1);
        p++;
        pk++;
      }
      j++;
    }
    if (n % 2)
      a.push(j);
    a.forEach((num) => write(num + ' '));
    write('\n');
  }
}

'use-strict'

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

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

        let testCases = parseInt(readLine());
        while(testCases--)
        {
            let [n, k] = get_ints();
            let a = [];
            let b = new Array(n);
            let flag = true;
            if(n/k <= 2)
            {
                print(-1);
                continue;
            }
            for(let i = 1 ; i <= n; i++)
            {
                a.push(i);
            }
            for(let i = 0 ; i < n; i++)
            {
                if(k !== 0 )
                {
                    if(isNaN(a[i+2])){
                        b[i] = a[i+1];
                        b[i+1] = a[i];
                        k--;
                        break;
                    }
                    b[i] = a[i];
                    b[i + 1] = a[i+2];
                    b[i + 2] = a[i+1];
                    i+=2;
                    k--;
                }
                else
                {
                    b[i] = a[i];
                }
            }
            if(flag && k === 0) print(b.join(' '))
            else print(-1)
        }

});

function print(c){
    return console.log(c);
}

function get_ints() {
    return readLine().split(' ').map(Number)
}

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

const t = readline();

for (var i = 0; i < parseInt(t); i++) {
  var input = readline().split(' ').map(d => parseInt(d));
  var n = input[0];
  var k = input[1];
  if (k >= parseInt((n + 1) / 2))
    print(-1);
  else {
    var a = [];
    var j = 1;
    var kp = 0;
    while (j <= parseInt(n / 2)) {
      a.push(j);
      if (kp < k) {
        a.push(n - j + 1);
        kp++;
        j++;
      } else {
        a.push(j + 1);
        j += 2;
      }
    }
    if (n % 2)
      a.push(j);
    a.forEach((num) => write(num + ' '));
    write('\n');
  }
}

const t = readline();

for (var i = 0; i < parseInt(t); i++) {
  var input = readline().split(' ').map(d => parseInt(d));
  var n = input[0];
  var k = input[1];
  if (k >= parseInt((n + 1) / 2))
    print(-1);
  else {
    var a = [];
    var j = 1;
    while (j <= parseInt(n / 2)) {
      a.push(j);
      a.push(n - j + 1);
      j++;
    }
    if (n % 2)
      a.push(j);
    a.forEach((num) => write(num + ' '));
    print('\n');
  }
}

const t = readline();

for (var i = 0; i < parseInt(t); i++) {
  var input = readline().split(' ').map(d => parseInt(d));
  var n = input[0];
  var k = input[1];
  if (k >= parseInt((n + 1) / 2))
    write(-1);
  else {
    var a = [];
    var j = 1;
    while (j <= parseInt(n / 2)) {
      a.push(j);
      a.push(n - j + 1);
      j++;
    }
    if (n % 2)
      a.push(j);
    a.forEach((num) => write(num + ' '));
  }
}

const t = readline();

for (var i = 0; i < t; i++) {
  const input = readline().split(' ').map(d => parseInt(d));
  const n = input[0];
  const k = input[1];
  if (k >= parseInt((n + 1) / 2))
    write(-1);
  else {
    var a = [];
    var j = 1;
    while (j <= parseInt(n / 2)) {
      a.push(j);
      a.push(n - j + 1);
      j++;
    }
    if (n % 2)
      a.push(j);
    a.forEach((num) => write(num + ' '));
  }
}

//const t = readline().split(' ').map((d) => parseInt(d));
const t = readline();

for (var i = 0; i < t; i++) {
  const n = readline();
  const k = readline();
  if (k >= parseInt((n + 1) / 2))
    print(-1);
  else {
    var a = [];
    var j = 1;
    for ( ; j <= parseInt(n / 2); j++) {
      a.push(j);
      a.push(n - j + 1);
    }
    if (n % 2)
      a.push(j);
    a.forEach(num => print(num));
  }
}


For the multiset of positive integers $$$s=\{s_1,s_2,\dots,s_k\}$$$, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of $$$s$$$ as follow: $$$\gcd(s)$$$ is the maximum positive integer $$$x$$$, such that all integers in $$$s$$$ are divisible on $$$x$$$. $$$\textrm{lcm}(s)$$$ is the minimum positive integer $$$x$$$, that divisible on all integers from $$$s$$$.For example, $$$\gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6$$$ and $$$\textrm{lcm}(\{4,6\})=12$$$. Note that for any positive integer $$$x$$$, $$$\gcd(\{x\})=\textrm{lcm}(\{x\})=x$$$.Orac has a sequence $$$a$$$ with length $$$n$$$. He come up with the multiset $$$t=\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\}$$$, and asked you to find the value of $$$\gcd(t)$$$ for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence.

The first line contains one integer $$$n\ (2\le n\le 100\,000)$$$. The second line contains $$$n$$$ integers, $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 200\,000$$$).

Print one integer: $$$\gcd(\{\textrm{lcm}(\{a_i,a_j\})\ |\ i<j\})$$$.

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
/**
    4
    10 24 40 80
**/

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

function main() {
    //let range = readline();

    // for(let r=0;r<range;r++) {
    //     let n = parseInt(readline());
    //     let a = readline().split(" ").map(Number);
    //     a.unshift(1);
    //     const dp = new Array(n+1).fill(1);

    //     for(let i=1;i<=n;i++) {
    //         for(let j=i-1;j>=1;j--) {
    //             if(i % j=== 0) {
    //                 let index = i / j;
    //                 if(a[j] < a[i]) {
    //                     dp[i] = Math.max(dp[i], dp[index] + 1);
    //                     break;
    //                 }
    //             }
    //         }
    //     }
    //     console.log(Math.max(...dp));
    // }

    let n = parseInt(readline());
    let a = readline().split(" ").map(Number);
    let dp = [];
    let number = 0;
    for(let i=n - 1;i>=0;i--) {
        number = gcd(a[i], number);
        dp[i] = number;
    }

    number = dp[0];
    for(let i=1;i<n;i++) {
        dp[i] = (a[i-1] * dp[i]) /(gcd(a[i-1], dp[i]));
    }

    let i = 0;
    for(i=2;i<n;i++) {
        dp[i] = gcd(dp[i-1], dp[i]);
    }
    console.log(dp[i-1]);

}