Stanley and Megan decided to shop in the "Crossmarket" grocery store, which can be represented as a matrix with $$$n$$$ rows and $$$m$$$ columns. Stanley and Megan can move to an adjacent cell using $$$1$$$ unit of power. Two cells are considered adjacent if they share an edge. To speed up the shopping process, Megan brought her portals with her, and she leaves one in each cell she visits (if there is no portal yet). If a person (Stanley or Megan) is in a cell with a portal, that person can use $$$1$$$ unit of power to teleport to any other cell with a portal, including Megan's starting cell.They decided to split up: Stanley will go from the upper-left cell (cell with coordinates $$$(1, 1)$$$) to the lower-right cell (cell with coordinates $$$(n, m)$$$), whilst Megan needs to get from the lower-left cell (cell with coordinates $$$(n, 1)$$$) to the upper-right cell (cell with coordinates $$$(1, m)$$$).What is the minimum total energy needed for them both to do that?Note that they can choose the time they move. Time does not affect energy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The only line in the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$).

For each test case print a single integer on a new line – the answer.

Note  In the first test case they can stick to the following plan:   Megan (red circle) moves to the cell $$$(7, 3)$$$. Then she goes to the cell $$$(1, 3)$$$, and Stanley (blue circle) does the same.  Stanley uses the portal in that cell (cells with portals are grey) to get to the cell $$$(7, 3)$$$. Then he moves to his destination — cell $$$(7, 5)$$$.  Megan also finishes her route and goes to the cell $$$(1, 5)$$$. The total energy spent is $$$(2 + 6) + (2 + 1 + 2) + (2)= 15$$$, which is our final answer.

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseArray = readline().split(" ");
    var rows = parseInt(caseArray[0]) - 1;
    var columns = parseInt(caseArray[1]) - 1;
    if (rows > 0 || columns > 0)
    {
        var lower = Math.min(rows, columns);
        var higher = Math.max(rows, columns);
        var result = (2 * lower) + higher + 1;
        print(result);
    }
    else print(0);
}

var tests = parseInt(readline());
    var n, m;
    for (var t=0; t < tests; t++) {
        var nm = readline().split(' ').map(x=>parseInt(x));
        n = nm[0];
        m = nm[1];
        if (n == 1 && m == 1) {
            print(0);
            continue;
        }
        var ans = 0;
        ans += n + m - 2;
        ans += Math.min(n, m);
        print(ans);
    }

T = readline()

while(T--){
  str = readline().split(' ').map(el => +el)
  n =str[0]
  m =str[1]

  if(n==1 && m ==1){
    print(0)
  }
  else{
    if(n>=m){
    print(m+m+n-2)
  }
  else{
    print((n-1) + m +n-1)
  }
  }

}

function convertNumberArray(str){ // '  12   43 123 4 ' >> [12, 43, 123, 4]
    return str.replace(/ +/g, " ").trim().split(' ').map(string => Number(string));
}

const process = require('process');
const {EOL} = require('os');
const { mainModule } = require('process');

let data = '';
process.stdin.on('data', string=>data+=string);
process.stdin.on('end', () => {
    const dataLines = data.split(EOL);
    A1715(dataLines);
});

const A1715 = (input)=>{
    // console.debug('DEBUGGGGGASDKJLADJSLJASDLJASD', input);
    let result = '';
    const tests = Number(input[0]);
    for(let i=1; i<=tests; i++){
        const [n, m] = convertNumberArray(input[i]);
        // console.log(solve(n, m));
        process.stdout.write(solve(n, m) + '\n');
        result+=solve(n, m) + '\n'
        // console.debug('DEBUGGGGGASDKJLADJSLJASDLJASD', result);
    }
    return result;
}
function solve(n, m){
    if(n==1 && m==1) return 0;
    else return Math.min(n,m) + Math.min(n,m)-1 + Math.max(n,m)-1;
}

// module.exports = {A1715};

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {

    result = i.split('\n').slice(1, -1)
        .map(l => l.split(" ").map(t => parseInt(t)))
        .map(l => l[0] + l[1] - 2 + Math.min(l[0], l[1]))
        .map(l => (l === 1) ? 0 : l)
        .join('\n')

    console.log(result)
})

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let i=1;i<=t;i++)
    {
        let [n,m]=line[i].split(' ').map(x=>{return parseInt(x)});
        let ans=n+m-2;
        ans+=Math.min(n,m);
        if(n==1&&m==1) ans=0;
        console.log(ans);
    }
})

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var M = nextInt();
		var min = Math.min(N, M);
		var max = Math.max(N, M);
		if(min == 1 && max == 1){
			myout(0);
			continue;
		}
		myout(min * 2 + max - 2);
	}
}

function solve(a, b) {
    // For she # of energy would be a - 1 + b - 1
    const herEnergy = a - 1 + b - 1;
    // For he # of energy would be min(a, b)
    const hisEnergy = a === 1 && b === 1 ? 0 : Math.min(a, b);
    return herEnergy + hisEnergy;
}

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

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

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

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    for(i = 1; i <= t; i++){
        var k = lines[i].split(' ').map(Number);
        var n = k[0], m = k[1];
        var ans = n + m - 2;
        ans += Math.min(n, m);
    console.log(n == 1 && m == 1 ? 0 : ans);
    }
});

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function isPossible(n, x, heights) {
    heights.sort();
    heights.sort(function(a, b) {
        return a - b;
      });
    // //console.log(heights)

    let front = []
    let back = []

    for (let i = 0; i < heights.length; i++) {
        if (i < n) {
            front.push(heights[i])
        } else {
            back.push(heights[i])
        }
    }

    // //console.log(front)
    // //console.log(back)
    for (let j = 0; j < front.length; j++) {
        if (back[j] - front[j] < x) {
            // //console.log(back[j] + " " + front[j])
            return "NO";
        }
    }

    return "YES";
}

function calc(a, m) {
    let s = "";
    for (let index = 0; index < m; index++) {
        s += "B"
    }

   for (let index = 0; index < a.length; index++) {
        let ai = a[index];

        if (ai < (m + 1 - ai)) {
            let _s = s.replaceAt(ai - 1, "A");
            if (compare(_s, s) < 0) {
                s = _s;
                continue;
            } else if (compare(_s, s) >= 0) {
                    let __ss = s.replaceAt(m + 1 - ai - 1, "A");
                    if (compare(__ss, s) < 0) {
                        s = __ss;
                        continue;
                    }
            }
         }  else {
            let _s = s.replaceAt(m + 1 - ai - 1, "A");
            if (compare(_s, s) < 0) {
                s = _s;
                continue;
            }  if (compare(_s, s) >= 0) {
                    let __ss = s.replaceAt(ai - 1, "A");
                    if (compare(__ss, s) < 0) {
                        s = __ss;
                        continue;
                    }
            }
    }
}

   return s;
}

function compare(s1, s2) {
    return s1.localeCompare(s2)
}

String.prototype.replaceAt = function(index, replacement) {
    return this.substring(0, index) + replacement + this.substring(index + replacement.length);
}

function main() {
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
        // const n = parseInt(readLine().trim(), 10);
        const arr = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));

        const m = arr[0]
        const n = arr[1]

        if (m == 1 && n == 1) console.log(0)
        else if (m == 1 || n == 1) {
            let x = m > n ? m : n;
            console.log(x)
        } else {
            let s = 0;
            if (m > n)
                s = m + (n -1)*2
            else
                s = n + (m-1)*2
            console.log(s);
        }

    }

    // ws.end();
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let [n, m] = readline().split(' ').map(Number);
        if (n === 1 && m === 1) {
            output(0);
        } else if (n === 1 || m === 1) {
            output(Math.max(n, m));
        } else {
            let bigger = Math.max(n, m);
            let smaller = Math.min(n, m);
            output(bigger + ((smaller - 1) * 2));
        }
    }
}

const fs = require("fs");

const input = fs.readFileSync(0, "utf8").trim().split("\n");

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const [n, m] = input[index].split(" ").map((item) => parseInt(item));

    const testCase = {
      n,
      m,
    };

    testCases.push(testCase);
  }
}

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

  console.log(
    n -
      1 +
      m -
      1 +
      (Math.max(n - 1, m - 1) > 0 ? 1 : 0) +
      Math.min(n - 1, m - 1)
  );
}

parseInput();

testCases.forEach(solution);

function convertNumberArray(str){ // '  12   43 123 4 ' >> [12, 43, 123, 4]
    return str.replace(/ +/g, " ").trim().split(' ').map(string => Number(string));
}

const process = require('process');
const {EOL} = require('os');
const { mainModule } = require('process');

let data = '';
process.stdin.on('data', string=>data+=string);
process.stdin.on('end', () => {
    const dataLines = data.split(EOL);
    A1715(dataLines);
});

const A1715 = (input)=>{
    console.debug('DEBUGGGGGASDKJLADJSLJASDLJASD', input);
    let result = '';
    const tests = Number(input[0]);
    for(let i=1; i<=tests; i++){
        const [n, m] = convertNumberArray(input[i]);
        // console.log(solve(n, m));
        process.stdout.write(solve(n, m) + '\n');
        result+=solve(n, m) + '\n'
        console.debug('DEBUGGGGGASDKJLADJSLJASDLJASD', result);
    }
    return result;
}
function solve(n, m){
    if(n==1 && m==1) return 0;
    else return Math.min(n,m) + Math.min(n,m)-1 + Math.max(n,m)-1;
}

// module.exports = {A1715};

function convertNumberArray(str){ // '  12   43 123 4 ' >> [12, 43, 123, 4]
    return str.replace(/ +/g, " ").trim().split(' ').map(string => Number(string));
}

const process = require('process');
const {EOL} = require('os');
const { mainModule } = require('process');

let data = '';
process.stdin.on('data', string=>data+=string);
process.stdin.on('end', () => {
    const dataLines = data.split(EOL);
    A1715(dataLines);
});

const A1715 = (input)=>{
    console.log('DEBUGGGGGASDKJLADJSLJASDLJASD', input);
    let result = '';
    const tests = Number(input[0]);
    for(let i=1; i<=tests; i++){
        const [n, m] = convertNumberArray(input[i]);
        // console.log(solve(n, m));
        process.stdout.write(solve(n, m) + '\n');
        result+=solve(n, m) + '\n'
        console.log('DEBUGGGGGASDKJLADJSLJASDLJASD', result);
    }
    return result;
}
function solve(n, m){
    if(n==1 && m==1) return 0;
    else return Math.min(n,m) + Math.min(n,m)-1 + Math.max(n,m)-1;
}

// module.exports = {A1715};

function convertNumberArray(str){ // '  12   43 123 4 ' >> [12, 43, 123, 4]
    return str.replace(/ +/g, " ").trim().split(' ').map(string => Number(string));
}

const process = require('process');
const {EOL} = require('os');
const { mainModule } = require('process');

let data = '';
process.stdin.on('data', string=>data+=string);
process.stdin.on('end', () => {
    const dataLines = data.split(EOL);
    A1715(dataLines);
});

function A1715(input) {
    const tests = Number(input[0]);
    for(let i=0; i<tests; i++){
        const [n, m] = convertNumberArray(input[i]);
        // console.log(solve(n, m));
        process.stdout.write(solve(n, m) + '\n');
    }
}

function solve(n, m){
    if(n==1 && m==1) return 0;
    else return Math.min(n,m) + Math.min(n,m)-1 + Math.max(n,m)-1;
}

function convertNumberArray(str){ // '  12   43 123 4 ' >> [12, 43, 123, 4]
    return str.replace(/ +/g, " ").trim().split(' ').map(string => Number(string));
}

const process = require('process');
const {EOL} = require('os');
const { mainModule } = require('process');

let data = '';
process.stdin.on('data', string=>data+=string);
process.stdin.on('end', () => {
    const dataLines = data.split(EOL);
    A1715(dataLines);
});

function A1715(input) {
    const tests = Number(input[0]);
    for(let i=0; i<tests; i++){
        const [n, m] = convertNumberArray(input[i]);
        console.log(solve(n, m));
    }
}

function solve(n, m){
    if(n==1 && m==1) return 0;
    else return Math.min(n,m) + Math.min(n,m)-1 + Math.max(n,m)-1;
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {

    let result = i.split('\n').slice(1)
        .map(l => l.split(" ").map(t => parseInt(t)))
        .map(l => l[0] + l[1] - 2 + Math.min(l[0], l[1]))
        .map(l => (l === 1) ? 0 : l)
        .join('\n')

    console.log(result)
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    let result = i.split('\n').slice(1)
        .map(l => l.split(" ").map(t => parseInt(t)))
        .map(l => l[0] + l[1] - 2 + Math.min(l[0], l[1]))
        .map(l => (l === 1) ? 0 : l)
        .reduce((l1, l2) => l1 + '' + l2, '')

    console.log(result)
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    let result = i.split('\n').slice(1)
        .map(l => l.split(" ").map(t => parseInt(t)))
        .map(l => l[0] + l[1] - 2 + Math.min(l[0], l[1]))
        .map(l => (l === 1) ? 0 : l)
        .reduce((l1, l2) => l1 + '\n' + l2, '')

    console.log(result)
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL)

    let result = lines.slice(1)
        .map(l => l.split(" ").map(t => parseInt(t)))
        .map(l => l[0] + l[1] - 2 + Math.min(l[0], l[1]))
        .map(l => (l === 1) ? 0 : l)

    console.log(result)
})

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let i=1;i<=t;i++)
    {
        let [n,m]=line[i].split(' ').map(x=>{return parseInt(x)});
        let ans=n+m-2;
        ans+=Math.min(n,m);
        console.log(ans);
    }
})


Let's call a string good if its length is at least $$$2$$$ and all of its characters are $$$\texttt{A}$$$ except for the last character which is $$$\texttt{B}$$$. The good strings are $$$\texttt{AB},\texttt{AAB},\texttt{AAAB},\ldots$$$. Note that $$$\texttt{B}$$$ is not a good string.You are given an initially empty string $$$s_1$$$.You can perform the following operation any number of times:   Choose any position of $$$s_1$$$ and insert some good string in that position. Given a string $$$s_2$$$, can we turn $$$s_1$$$ into $$$s_2$$$ after some number of operations?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single string $$$s_2$$$ ($$$1 \leq |s_2| \leq 2 \cdot 10^5$$$). It is guaranteed that $$$s_2$$$ consists of only the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$. It is guaranteed that the sum of $$$|s_2|$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print "YES" (without quotes) if we can turn $$$s_1$$$ into $$$s_2$$$ after some number of operations, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we transform $$$s_1$$$ as such: $$$\varnothing \to \color{red}{\texttt{AAB}} \to \texttt{A}\color{red}{\texttt{AB}}\texttt{AB}$$$.In the third test case, we transform $$$s_1$$$ as such: $$$\varnothing \to \color{red}{\texttt{AAAAAAAAB}}$$$.In the second and fourth test case, it can be shown that it is impossible to turn $$$s_1$$$ into $$$s_2$$$.

T = readline()
while(T--){
   x = readline()
   ans = 'YES'
   if(x.length < 2 || x[x.length - 1] != 'B' || x[0] != 'A')
      ans = 'NO'
   allB = 0
   allA = 0
   for(i=0; i< x.length; i++){
      if(x[i]==='B')
         allB ++
      else
         allA ++
      if(allB > allA){
         ans = 'NO'
         break
      }

   }

   print(ans)
}

var t = readline();

for (var i = 0; i < t; i++) {
  var s = readline().split('');
  var n = s.length;
  var cur = 0;
  var f = s[n - 1] === 'B';

  for (var j = 0; j < n; j++) {
    cur += s[j] == 'A' ? 1 : -1;
    if (cur < 0) f = false;
  }

  if (f) print('YES');
  else print('NO');
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        const s2 = readline();
        let s1 = '';
        if (s2[0] === 'B' || s2[s2.length - 1] === 'A') {
            output('NO');
            continue;
        }

        let a = 0;
        let b = 0;

        let no = false;
        for (let i = 0; i < s2.length; i++) {
           if (s2[i] === 'A') { a++ } else { b++ };
           if (b>a) {
                no = true;
                break;
           }
        }

        output(no ? 'NO' : 'YES');

    }
}

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

let ls = [];

function solve() {
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let i = 0; i < t; i++){
        const s = ls[l++];
        let chrz = 0;
        let ans = true;
        let hasB = false;
        for (let j = 0; j < s.length; j++){
            if (s[j] == 'A'){
                chrz++;
            }
            else{
                chrz--;
                hasB = true;
            }
            ans &= (chrz >= 0);
        }

        let lastB = s[s.length - 1] == 'B';
        console.log(ans && hasB && lastB ? 'YES' : 'NO');
    }
}

rl.on('line', (l) => ls.push(l));
rl.on('close', () => solve());

'use strict';

var readline = require('readline');

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

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

function solve(s2) {
  if (s2[s2.length - 1] !== 'B') {
    console.log('NO');
    return;
  }
  let prea = 0,
      preb = 0;
  for (let char of s2) {
    if (char === 'A') prea++;else preb++;
    if (preb > prea) {
      console.log('NO');
      return;
    }
  }
  console.log('YES');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const s2 = await read();
    solve(s2);
  }
}

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

T = readline()
while(T--){
   x = readline()
   ans = 'YES'
   if(x.length < 2 || x[x.length - 1] != 'B' || x[0] != 'A')
      ans = 'NO'
   allB = 0
   allA = 0
   for(i=0; i< x.length; i++){
      if(x[i]==='B')
         allB ++
      else
         allA ++
   }
   if(allB>allA)
      ans = 'NO'
   print(ans)
}

T = readline()
while(T--){
   x = readline()
   ans = 'YES'
   if(x.length < 2 || x[x.length] != 'B' || x[0] != 'A')
      ans = 'NO'
   for(i=0; i < x.length - 1; i++){
      if(x[i] === x[i+1] && x[i] === 'B'){
         ans = 'NO'
         break
      }
   }
   print(ans)
}

T = readline()
while(T--){
   x = readline()
   ans = 'YES'
   if(x.length < 2 || x[x.length - 1] != 'B' || x[0] != 'A')
      ans = 'NO'
   for(i=0; i < x.length - 2; i++){
      if(x[i] === x[i+1] && x[i] === 'B'){
         ans = 'NO'
         break
      }
   }
   print(ans)
}

T = readline()
while(T--){
   x = readline()
   ans = 'YES'
   if(x.length < 2 || x[x.length - 1] != 'B' || x[0] != 'A')
      ans = 'NO'
   for(i=0; i < x.length - 1; i++){
      if(x[i] === x[i+1] && x[i] === 'B'){
         ans = 'NO'
         break
      }
   }
   print(ans)
}

T = readline()
while(T--){
   x = readline()
   ans = 'YES'
   if(x.length < 2 || x[x.length - 1] != 'B')
      ans = 'NO'
   for(i=0; i < x.length - 1; i++){
      if(x[i] === x[i+1] && x[i] === 'B'){
         ans = 'NO'
         break
      }
   }
   print(ans)
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        const s2 = readline();
        let s1 = '';
        if (s2[0] === 'B') {
            output('NO');
            continue;
        } else if (s2 === 'A') {
            output('NO');
            continue;
        } else if (s2[s2.length - 1] === 'A') {
            output('NO');
            continue;
        }

        let no = false;
        for (let i = 1; i < s2.length; i++) {
            if (s2[i] === 'B' && s2[i - 1] === 'B') {
                no = true;
                break;
            }
        }

        output(no ? 'NO' : 'YES');

    }
}

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

let ls = [];

function solve() {
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let i = 0; i < t; i++){
        const s = ls[l++];
        let chrz = 0;
        let ans = true;
        let hasB = false;
        for (let j = 0; j < s.length; j++){
            if (s[j] == 'A'){
                chrz++;
            }
            else{
                chrz--;
                hasB = true;
            }
            ans &= (chrz >= 0);
        }
        console.log(ans && hasB ? 'YES' : 'NO');
    }
}

rl.on('line', (l) => ls.push(l));
rl.on('close', () => solve());


Vlad and Nastya live in a city consisting of $$$n$$$ houses and $$$n-1$$$ road. From each house, you can get to the other by moving only along the roads. That is, the city is a tree.Vlad lives in a house with index $$$x$$$, and Nastya lives in a house with index $$$y$$$. Vlad decided to visit Nastya. However, he remembered that he had postponed for later $$$k$$$ things that he has to do before coming to Nastya. To do the $$$i$$$-th thing, he needs to come to the $$$a_i$$$-th house, things can be done in any order. In $$$1$$$ minute, he can walk from one house to another if they are connected by a road.Vlad does not really like walking, so he is interested what is the minimum number of minutes he has to spend on the road to do all things and then come to Nastya. Houses $$$a_1, a_2, \dots, a_k$$$ he can visit in any order. He can visit any house multiple times (if he wants).

The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. There is an empty line before each test case. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot 10^5$$$) — the number of houses and things, respectively. The second line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$) — indices of the houses where Vlad and Nastya live, respectively. The third line of each test case contains $$$k$$$ integers $$$a_1, a_2, \dots, a_k$$$ ($$$1 \le a_i \le n$$$) — indices of houses Vlad need to come to do things. The following $$$n-1$$$ lines contain description of city, each line contains two integers $$$v_j$$$ and $$$u_j$$$ ($$$1 \le u_j, v_j \le n$$$) — indices of houses connected by road $$$j$$$. It is guaranteed that the sum of $$$n$$$ for all cases does not exceed $$$2\cdot10^5$$$.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer output single integer — the minimum number of minutes Vlad needs on the road to do all the things and come to Nastya.

NoteTree and best path for the first test case:  $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$ Tree and best path for the second test case:  $$$3 \rightarrow 1 \rightarrow 3 \rightarrow 5 \rightarrow 2 \rightarrow 5 \rightarrow 6 \rightarrow 5$$$ Tree and best path for the third test case:  $$$3 \rightarrow 5 \rightarrow 2$$$

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

let stackRecursion = (fn, init_state)=>{
  let stack = [];
  let rec = (cb, a0, a1, a2)=>{
    let state = Object.assign({}, init_state);
    stack.push([state, cb, a0, a1, a2]);
  };
  return (cb, a0, a1, a2)=>{
    rec(cb, a0, a1, a2);
    while (stack.length){
      let [state, cb, a0, a1, a2] = stack[stack.length-1];
      let added = false;
      fn((cb, a0, a1, a2)=>{
        added = true;
        rec(cb, a0, a1, a2);
      }, state, a0, a1, a2);
      if (!added){
        cb(state);
        stack.pop();
      }
    }
  };
};

class Graph {
  constructor(){
    this.g = {};
  }
  getAns(x, y, A){
    let G = this.g;
    let dfs = stackRecursion((rec, state, v, avoid1, avoid2)=>{
      let children = G[v]||[];
      if (A.has(v))
        state.itemsCollected++;
      while (state.i<children.length){
        let to = children[state.i++];
        if (to===avoid1 || to===avoid2)
          continue;
        rec(childState=>{
          if (childState.itemsCollected){
            state.itemsCollected += childState.itemsCollected;
            state.timeSpent += 2+childState.timeSpent;
          }
        }, to, v);
        return;
      }
    }, {i: 0, itemsCollected: 0, timeSpent: 0});
    let queue = [], qi = 0;
    queue.push([x, -1]);
    let parent = {};
    let visited = new Set([x]);
    while (qi<queue.length){
      let [v, p] = queue[qi++];
      let children = this.g[v]||[];
      for (let i=0; i<children.length; i++){
        let to = children[i]
        if (to==p || visited.has(to))
          continue;
        parent[to] = v;
        visited.add(to);
        queue.push([to, v]);
      }
    }
    let Y = y;
    let pathXY = [];
    L('Parents', parent)
    while (Y!=x){
      pathXY.push(Y);
      Y = parent[Y];
    }
    pathXY.push(x);
    L('PATH', pathXY, {x, y})
    let minutes = pathXY.length-1;
    for (let i=0; i<pathXY.length; i++){
      dfs(({timeSpent})=>{
        minutes += timeSpent;
      }, pathXY[i], pathXY[i-1], pathXY[i+1]);
    }
    return minutes;
  }
  add(v, u){
    if (!this.g[v])
      this.g[v] = [];
    this.g[v].push(u);
  }
}

const calc = ()=>{
  // READING:
  readline();
  let [n, k] = ra();
  let [x, y] = ra();
  x--; y--;
  let A = new Set(readline().split(' ').map(a=>a-1));
  let G = new Graph();
  for (let i=0; i<n-1; i++){
    let [u, v] = ra();
    u--; v--;
    G.add(u, v)
    G.add(v, u)
  }
  LT({G, A});
  // PROCESSING:
  return G.getAns(x, y, A);
};

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

let wrap = (fn, init_state)=>{
  let stack = [];
  let rec = (cb, a0, a1, a2)=>{
    let state = Object.assign({}, init_state);
    stack.push([state, cb, a0, a1, a2]);
  };
  return (cb, a0, a1, a2)=>{
    rec(cb, a0, a1, a2);
    while (stack.length){
      let [state, cb, a0, a1, a2] = stack[stack.length-1];
      let added = false;
      fn((cb, a0, a1, a2)=>{
        added = true;
        rec(cb, a0, a1, a2);
      }, state, a0, a1, a2);
      if (!added){
        cb(state);
        stack.pop();
      }
    }
  };
};

class Graph {
  constructor(){
    this.g = {};
  }
  getAns(x, y, A){
    let G = this.g;
    let dfs = wrap((rec, state, v, avoid1, avoid2)=>{
      let children = G[v]||[];
      if (A.has(v))
        state.itemsCollected++;
      while (state.i<children.length){
        let to = children[state.i++];
        if (to===avoid1 || to===avoid2)
          continue;
        rec(childState=>{
          if (childState.itemsCollected){
            state.itemsCollected += childState.itemsCollected;
            state.timeSpent += 2+childState.timeSpent;
          }
        }, to, v);
      }
    }, {i: 0, itemsCollected: 0, timeSpent: 0});
    let queue = [], qi = 0;
    queue.push([x, -1]);
    let parent = {};
    let visited = new Set([x]);
    while (qi<queue.length){
      let [v, p] = queue[qi++];
      let children = this.g[v]||[];
      for (let i=0; i<children.length; i++){
        let to = children[i]
        if (to==p || visited.has(to))
          continue;
        parent[to] = v;
        visited.add(to);
        queue.push([to, v]);
      }
    }
    let Y = y;
    let pathXY = [];
    L('Parents', parent)
    while (Y!=x){
      pathXY.push(Y);
      Y = parent[Y];
    }
    pathXY.push(x);
    L('PATH', pathXY, {x, y})
    let minutes = pathXY.length-1;
    for (let i=0; i<pathXY.length; i++){
      dfs(({timeSpent})=>{
        minutes += timeSpent;
      }, pathXY[i], pathXY[i-1], pathXY[i+1]);
    }
    return minutes;
  }
  add(v, u){
    if (!this.g[v])
      this.g[v] = [];
    this.g[v].push(u);
  }
}

const calc = ()=>{
  // READING:
  readline();
  let [n, k] = ra();
  let [x, y] = ra();
  x--; y--;
  let A = new Set(readline().split(' ').map(a=>a-1));
  let G = new Graph();
  for (let i=0; i<n-1; i++){
    let [u, v] = ra();
    u--; v--;
    G.add(u, v)
    G.add(v, u)
  }
  LT({G, A});
  // PROCESSING:
  return G.getAns(x, y, A);
};

'use strict';

var readline = require('readline');

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

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

function solve(n, k, x, y, a, b) {
  x--;
  y--;
  a = a.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of b) {
    g[u].push(v);
    g[v].push(u);
  }
  const p = [];
  let res = 0;
  {
    const queue = [x],
          st = [];
    p[x] = -1;
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j]) continue;
        queue.push(j);
        p[j] = i;
      }
    }
  }
  const set = new Set();
  set.add(x);
  set.add(y);
  {
    const queue = [y];
    for (let i of queue) {
      set.add(i);
      if (p[i] !== -1) {
        res++;
        queue.push(p[i]);
      }
    }
  }
  const dist = [],
        seta = new Set(a);
  {
    const queue = [...set],
          st = [],
          p = [];
    for (let i of set) {
      seta.delete(i);
      dist[i] = 0;
      p[i] = -1;
    }
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j] || set.has(j)) continue;
        dist[j] = dist[i] + 1;
        p[j] = i;
        queue.push(j);
      }
    }
    {
      const queue = [];
      for (let i of seta) {
        res += 2 * dist[i];
        if (p[i] === -1) continue;
        queue.push(p[i]);
      }
      for (let i of queue) {
        if (seta.has(i)) {
          res -= 2 * dist[i];
        } else {
          seta.add(i);
          if (p[i] !== -1 && p[i] !== undefined) queue.push(p[i]);
        }
      }
    }
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    await read();
    const [n, k] = (await read()).split(' ').map(Number);
    const [x, y] = (await read()).split(' ').map(Number);
    const a = (await read()).split(' ').map(Number);
    const b = [];
    let tmp = n - 1;
    while (tmp--) {
      b.push((await read()).split(' ').filter(str => str !== '').map(s => Number(s) - 1));
    }
    solve(n, k, x, y, a, b);
  }
}

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

const readline = require('readline')

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

class Queue {
    constructor() {
        this.map = {}
        this.first = 0
        this.last = -1
    }
    push(...args) {
        let i = 0
        if (!this.length) {
            this.first = this.last = 0
            this.map[this.first] = args[i++]
        }
        for (; i < args.length; i++) {
            this.map[++this.last] = args[i]
        }
    }
    unshift(...args) {
        let i = 0
        if (!this.length) {
            this.first = this.last = 0
            this.map[this.first] = args[i++]
        }
        for (; i < args.length; i++) {
            this.map[--this.first] = args[i]
        }
    }
    pop() {
        const r = this.map[this.last]
        delete this.map[this.last]
        this.last--
        return r
    }
    shift() {
        const r = this.map[this.first]
        delete this.map[this.first]
        this.first++
        return r
    }
    get length() {
        if (this.first > this.last) return 0
        return this.last - this.first + 1
    }
    getLast() {
        return this.map[this.last]
    }
}

function solve(n, x, y, arr, edges) {
    const map = arr.reduce((o, u) => {
        o[u] = 1
        return o
    }, {})
    map[y] = 1
// console.log(arr)
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })

    return dfs(adj, x, y, map)
}
function dfs(adj, r, y, map) {
    // const stack = [[r, 0, -1]]
    const stack = new Queue()
    stack.push([r, 0, -1])
    const dp = []
    let dy
    while (stack.length) {
        const [u, i, p] = stack.getLast()// stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            if (u === y) dy = stack.length - 1
        }
        if (i < nb.length) {
            // stack[stack.length - 1]
            stack.getLast()[1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            stack.pop()
            dp[u] = 0
            adj[u].forEach(v => {
                if (v === p) return
                if (dp[v] || map[v]) {
                    dp[u] += dp[v] + 2
                }
            })
        }
    }
// console.log(dp, dy)
    return dp[r] - dy
}

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

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

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

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

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

const calc = (n, k, x, y, things, g)=>{
    x--; y--;
    let p = new Array(n).fill(-1);

    let visited = new Array(n).fill(false);
    let q = [x];
    while (q.length > 0) {
        let newq = [];
        for (let v of q) {
            if (visited[v]) continue;
            visited[v] = true;
            for (let u of g[v]) {
                if (visited[u]) continue;
                p[u] = v;
                newq.push(u);
            }
        }
        q = newq;
    }

    visited = new Array(n).fill(false);
    visited[x] = true;

    let result = 0;

    if (!visited[y]) {
        let cur = y;
        let count = 0;
        while (!visited[cur]) {
            count++;
            visited[cur] = true;
            cur = p[cur];
        }
        result += count;
    }

    for (let thing of things) {
        thing--;
        if (visited[thing]) continue;

        let cur = thing;
        let count = 0;
        while (!visited[cur]) {
            count++;
            visited[cur] = true;
            cur = p[cur];
        }
        result += 2 * count;
    }

    return result;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        readline();
        // let n = +readline();
        let [n, k] = ra();
        let [x, y] = ra();
        let things = ra();
        let g = new Array(n).fill(0).map(() => new Array());
        for (let i = 0; i < n - 1; i++) {
            let [a, b] = ra();
            g[a - 1].push(b - 1);
            g[b - 1].push(a - 1);
        }
        console.log(`${calc(n, k, x, y, things, g)}`);
    }
}

'use strict';

var readline = require('readline');

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

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

function solve(n, k, x, y, a, b) {
  x--;
  y--;
  a = a.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of b) {
    g[u].push(v);
    g[v].push(u);
  }
  const p = [];
  let res = 0;
  {
    const queue = [x],
          st = [];
    p[x] = -1;
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j]) continue;
        queue.push(j);
        p[j] = i;
      }
    }
  }
  const set = new Set();
  set.add(x);
  set.add(y);
  {
    const queue = [y];
    for (let i of queue) {
      set.add(i);
      if (p[i] !== -1) {
        res++;
        queue.push(p[i]);
      }
    }
  }
  const dist = [],
        seta = new Set(a);
  {
    const queue = [...set].map(num => [num, 0]),
          st = [],
          p = [];
    for (let i of set) {
      seta.delete(i);
      dist[i] = 0;
      p[i] = -1;
    }
    for (let [i, dis] of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j] || set.has(j)) continue;
        dist[j] = dist[i] + 1;
        p[j] = i;
        queue.push([j, dist[j]]);
      }
    }
    {
      const queue = [];
      for (let i of seta) {
        queue.push(p[i]);
        res += 2 * dist[i];
      }
      for (let i of queue) {
        if (seta.has(i)) {
          res -= 2 * dist[i];
        } else if (p[i] !== -1 && p[i] !== undefined) queue.push(p[i]);
      }
    }
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    await read();
    const [n, k] = (await read()).split(' ').map(Number);
    const [x, y] = (await read()).split(' ').map(Number);
    const a = (await read()).split(' ').map(Number);
    const b = [];
    let tmp = n - 1;
    while (tmp--) {
      b.push((await read()).split(' ').filter(str => str !== '').map(s => Number(s) - 1));
    }
    solve(n, k, x, y, a, b);
  }
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, k, x, y, a, b) {
  x--;
  y--;
  a = a.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of b) {
    g[u].push(v);
    g[v].push(u);
  }
  const p = [];
  let res = 0;
  {
    const queue = [x],
          st = [];
    p[x] = -1;
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j]) continue;
        queue.push(j);
        p[j] = i;
      }
    }
  }
  const set = new Set();
  set.add(x);
  set.add(y);
  {
    const queue = [y];
    for (let i of queue) {
      set.add(i);
      if (p[i] !== -1) {
        res++;
        queue.push(p[i]);
      }
    }
  }
  const dist = [],
        seta = new Set(a);
  {
    const queue = [...set].map(num => [num, 0]),
          st = [],
          p = [];
    for (let i of set) {
      seta.delete(i);
      dist[i] = 0;
      p[i] = -1;
    }
    for (let [i, dis] of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j] || set.has(j)) continue;
        dist[j] = dist[i] + 1;
        p[j] = i;
        queue.push([j, dist[j]]);
      }
    }
    {
      const queue = [];
      for (let i of seta) {
        queue.push(p[i]);
        res += 2 * dist[i];
      }
      for (let i of queue) {
        if (seta.has(i)) {
          res -= 2 * dist[i];
        }
        if (p[i] !== -1 && p[i] !== undefined) queue.push(p[i]);
      }
    }
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    await read();
    const [n, k] = (await read()).split(' ').map(Number);
    const [x, y] = (await read()).split(' ').map(Number);
    const a = (await read()).split(' ').map(Number);
    const b = [];
    let tmp = n - 1;
    while (tmp--) {
      b.push((await read()).split(' ').filter(str => str !== '').map(s => Number(s) - 1));
    }
    solve(n, k, x, y, a, b);
  }
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, k, x, y, a, b) {
  x--;
  y--;
  a = a.map(num => num - 1);
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of b) {
    g[u].push(v);
    g[v].push(u);
  }
  const p = [];
  let res = 0;
  {
    const queue = [x],
          st = [];
    p[x] = -1;
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j]) continue;
        queue.push(j);
        p[j] = i;
      }
    }
  }
  const set = new Set();
  set.add(x);
  set.add(y);
  {
    const queue = [y];
    for (let i of queue) {
      set.add(i);
      if (p[i] !== -1) {
        res++;
        queue.push(p[i]);
      }
    }
  }
  const seta = new Set(a);
  {
    const st = [];
    const dfs = i => {
      st[i] = 1;
      let res = 0;
      for (let j of g[i]) {
        if (st[j]) continue;
        res += dfs(j);
      }
      if (!set.has(i)) {
        if (res === 0 && seta.has(i)) return 1;
        if (res > 0) return res + 1;
      }
      return res;
    };
    res += dfs(x) * 2;
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    await read();
    const [n, k] = (await read()).split(' ').map(Number);
    const [x, y] = (await read()).split(' ').map(Number);
    const a = (await read()).split(' ').map(Number);
    const b = [];
    let tmp = n - 1;
    while (tmp--) {
      b.push((await read()).split(' ').filter(str => str !== '').map(s => Number(s) - 1));
    }
    solve(n, k, x, y, a, b);
  }
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, k, x, y, a, b) {
  x--;
  y--;
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of b) {
    g[u].push(v);
    g[v].push(u);
  }
  const p = [];
  let res = 0;
  {
    const queue = [x],
          st = [];
    p[x] = -1;
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j]) continue;
        queue.push(j);
        p[j] = i;
      }
    }
  }
  const set = new Set();
  set.add(x);
  set.add(y);
  {
    const queue = [y];
    for (let i of queue) {
      set.add(i);
      if (p[i] !== -1) {
        res++;
        queue.push(p[i]);
      }
    }
  }
  const dist = [],
        seta = new Set(a.map(num => num - 1));
  {
    const queue = [...set].map(num => [num, 0]),
          st = [],
          p = [];
    for (let i of set) {
      seta.delete(i);
      dist[i] = 0;
      p[i] = -1;
    }
    for (let [i, dis] of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j] || set.has(j)) continue;
        dist[j] = dist[i] + 1;
        p[j] = i;
        queue.push([j, dist[j]]);
      }
    }
    {
      const queue = [];
      for (let i of seta) {
        queue.push(p[i]);
      }
      for (let i of queue) {
        seta.delete(i);
        if (p[i] !== -1 && p[i] !== undefined) queue.push(p[i]);
      }
    }
  }
  for (let i of seta) {
    res += dist[i] * 2;
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    await read();
    const [n, k] = (await read()).split(' ').map(Number);
    const [x, y] = (await read()).split(' ').map(Number);
    const a = (await read()).split(' ').map(Number);
    const b = [];
    let tmp = n - 1;
    while (tmp--) {
      b.push((await read()).split(' ').filter(str => str !== '').map(s => Number(s) - 1));
    }
    solve(n, k, x, y, a, b);
  }
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, k, x, y, a, b) {
  x--;
  y--;
  const g = Array.from({
    length: n
  }, () => []);
  for (let [u, v] of b) {
    g[u].push(v);
    g[v].push(u);
  }
  const p = [];
  let res = 0;
  {
    const queue = [x],
          st = [];
    p[x] = -1;
    for (let i of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j]) continue;
        queue.push(j);
        p[j] = i;
      }
    }
  }
  const set = new Set();
  set.add(x);
  set.add(y);
  {
    const queue = [y];
    for (let i of queue) {
      set.add(i);
      if (p[i] !== -1) {
        res++;
        queue.push(p[i]);
      }
    }
  }
  const dist = [];
  {
    const queue = [...set].map(num => [num, 0]),
          st = [];
    for (let i of set) {
      dist[i] = 0;
    }
    for (let [i, dis] of queue) {
      if (st[i]) continue;
      st[i] = 1;
      for (let j of g[i]) {
        if (st[j] || set.has(j)) continue;
        dist[j] = dist[i] + 1;
      }
    }
  }
  for (let i of [...new Set(a)].map(num => num - 1)) {
    res += dist[i] * 2;
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    await read();
    const [n, k] = (await read()).split(' ').map(Number);
    const [x, y] = (await read()).split(' ').map(Number);
    const a = (await read()).split(' ').map(Number);
    const b = [];
    let tmp = n - 1;
    while (tmp--) {
      b.push((await read()).split(' ').filter(str => str !== '').map(s => Number(s) - 1));
    }
    solve(n, k, x, y, a, b);
  }
}

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


A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are  roads in total. It takes exactly y seconds to traverse any single road.A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads.Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y.You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once.

The first line of the input contains three integers n, x and y (2 ≤ n ≤ 200 000, 1 ≤ x, y ≤ 109). Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree.

Print a single integer — the minimum number of seconds one needs to spend in order to visit all the cities exactly once.

NoteIn the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is .In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is .

var temp = readline().split(' ');
var N = parseInt(temp[0]);
var onTree = parseInt(temp[1]);
var offTree = parseInt(temp[2]);
var edge = [];
for (var i = N+1; i--; ) edge.push([]);
var u, v;
for (var i = N-1; i--; ) {
  temp = readline().split(' ');
  u = parseInt(temp[0]);
  v = parseInt(temp[1]);
  edge[u].push(v);
  edge[v].push(u);
}
if (onTree >= offTree) {
  var star = false;
  for (var i = N; i--; ) {
    if (edge[N-i].length === N-1) {
      star = true;
      break;
    }
  }
  print(star ? (N-2) * offTree + onTree : (N-1) * offTree);
} else {
  var father = [], avail = [];
  for (var i = N+1; i--; ) {
    father.push(0);
    avail.push(2);
  }
  father[1] = null;
  var stack = [1], stac2 = [], cnt = 0;
  var node, e;
  while (node = stack.pop()) {
    stac2.push(node);
    e = edge[node];
    tail = true;
    for (var i = e.length; i--; ) {
      if (father[e[i]] === 0) {
        father[e[i]] = node;
        stack.push(e[i]);
        tail = true;
      }
    }
  }
  while (node = stac2.pop()) {
    if (avail[node] && avail[father[node]]) {
      avail[node]--;
      avail[father[node]]--;
      cnt++;
    }
  }
  print(cnt * onTree + (N-1-cnt) * offTree);
}

var readInt = (keys) => {
  var val = readline().split(' ');
  var key = keys.split(', ');
  for (var i = 0; i < key.length; ++i) {
    this[key[i]] = parseInt(val[i]);
  }
};
Array.prototype.init = function (val) {
  var foo = typeof val === 'function' ? val : () => val;
  for (var i = this.length; i--; ) {
    this[i] = foo();
  }
  return this;
};

readInt('N, onTree, offTree');
var edge = new Array(N+1).init(() => []);
for (var i = N-1; i--; ) {
  readInt('u, v');
  edge[u].push(v);
  edge[v].push(u);
}
if (onTree >= offTree) {
  var star = false;
  edge.forEach(arr => star = star || arr.length === N-1);
  print(star ? (N-2) * offTree + onTree : (N-1) * offTree);
} else {
  var father = new Array(N+1).init(0);
  var avail = new Array(N+1).init(2);
  father[1] = null;
  var sa = [1], sb = [], me;
  var bind = (son) => {
    if (father[son] === 0) {
      father[son] = me;
      sa.push(son);
    }
  }
  while (me = sa.pop()) {
    sb.push(me);
    edge[me].forEach(bind);
  }
  var cnt = 0;
  while (me = sb.pop()) {
    if (avail[me] && avail[father[me]]) {
      avail[me]--; avail[father[me]]--;
      cnt++;
    }
  }
  print(cnt * onTree + (N-1-cnt) * offTree);
}

var readInt = (keys) => {
  var val = readline().split(' ');
  var key = keys.split(', ');
  for (var i = 0; i < key.length; ++i) {
    this[key[i]] = parseInt(val[i]);
  }
};
Array.prototype.init = function (val) {
  var foo = typeof val === 'function' ? val : () => val;
  for (var i = this.length; i--; ) {
    this[i] = foo();
  }
  return this;
};
readInt('N, onTree, offTree');
var edge = new Array(N+1).init(() => []);
for (var i = N-1; i--; ) {
  readInt('u, v');
  edge[u].push(v);
  edge[v].push(u);
}
if (onTree >= offTree) {
  var star; edge.forEach(arr => star = arr.length === N-1);
  print(star ? (N-2) * offTree + onTree : (N-1) * offTree);
} else {
  var father = new Array(N+1).init(0);
  var avail = new Array(N+1).init(2);
  father[1] = null;
  var sa = [1], sb = [], me;
  var bind = (son) => {
    if (father[son] === 0) {
      father[son] = me;
      sa.push(son);
    }
  }
  while (me = sa.pop()) {
    sb.push(me);
    edge[me].forEach(bind);
  }
  var cnt = 0;
  while (me = sb.pop()) {
    if (avail[me] && avail[father[me]]) {
      avail[me]--; avail[father[me]]--;
      cnt++;
    }
  }
  print(cnt * onTree + (N-1-cnt) * offTree);
}

var temp = readline().split(' ');
var N = parseInt(temp[0]);
var onTree = parseInt(temp[1]);
var offTree = parseInt(temp[2]);
var edge = [];
for (var i = N+1; i--; ) edge.push([]);
var u, v;
for (var i = N-1; i--; ) {
  temp = readline().split(' ');
  u = parseInt(temp[0]);
  v = parseInt(temp[1]);
  edge[u].push(v);
  edge[v].push(u);
}
if (onTree >= offTree) {
  var star = false;
  for (var i = N; i--; ) {
    if (edge[N-i].length === N-1) {
      star = true;
      break;
    }
  }
  print(star ? (N-2) * offTree + onTree : (N-1) * offTree);
} else {
  var father = [], avail = [];
  for (var i = N+1; i--; ) {
    father.push(0);
    avail.push(2);
  }
  father[1] = null;
  var stack = [1], stac2 = [], cnt = 0;
  var node, e;
  while (node = stack.pop()) {
    stac2.push(node);
    e = edge[node];
    tail = true;
    for (var i = e.length; i--; ) {
      if (father[e[i]] === 0) {
        father[e[i]] = node;
        stack.push(e[i]);
        tail = true;
      }
    }
  }
  while (node = stac2.pop()) {
    if (avail[node] && father[node]) {
      avail[node]--;
      avail[father[node]]--;
      cnt++;
    }
  }
  print(cnt * onTree + (N-1-cnt) * offTree);
}

var temp = readline().split(' ');
var N = parseInt(temp[0]);
var onTree = parseInt(temp[1]);
var offTree = parseInt(temp[2]);
var edge = [];
for (var i = N+1; i--; ) edge.push([]);
var u, v;
for (var i = N-1; i--; ) {
  temp = readline().split(' ');
  u = parseInt(temp[0]);
  v = parseInt(temp[1]);
  edge[u].push(v);
  edge[v].push(u);
}
var dia = (() => {
  var farthestFrom = (src) => {
    var dis = [];
    for (var i = N+1; i--; ) dis.push(Infinity);
    dis[src] = 0;
    var queue = [src], l = 0;
    queue.pop = () => queue[l++];
    var u, ue, max = 0, maxu = src;
    while (u = queue.pop()) {
      if (dis[u] > max) {
        max = dis[u];
        maxu = u;
      }
      ue = edge[u];
      for (var i = ue.length; i--; ) {
        if (dis[ue[i]] === Infinity) {
          dis[ue[i]] = dis[u] + 1;
          queue.push(ue[i]);
        }
      }
    }
    return {
      dis: max,
      id: maxu
    };
  };
  var memo;
  return () => {
    if (typeof memo !== 'undefined') return memo;
    var u = farthestFrom(1);
    var v = farthestFrom(u.id);
    return memo = v.dis;
  };
})();
if (onTree >= offTree) {
  var centre = false;
  for (var i = N; i--; ) {
    if (edge[N-i].length === N-1) {
      centre = true;
      break;
    }
  }
  print(centre ? (N-2) * offTree + onTree : (N-1) * offTree);
} else {
  print(dia() * onTree + (N-1-dia()) * offTree);
}


Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $$$M$$$ with $$$n$$$ rows and $$$n$$$ columns such that $$$M_{ij}=a_i \cdot a_j$$$ where $$$a_1, \dots, a_n$$$ is some sequence of positive integers.Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array $$$a_1, \dots, a_n$$$. Help Sasha restore the array!

The first line contains a single integer $$$n$$$ ($$$3 \leqslant n \leqslant 10^3$$$), the size of the table.  The next $$$n$$$ lines contain $$$n$$$ integers each. The $$$j$$$-th number of the $$$i$$$-th line contains the number $$$M_{ij}$$$ ($$$1 \leq M_{ij} \leq 10^9$$$). The table has zeroes on the main diagonal, that is, $$$M_{ii}=0$$$.

In a single line print $$$n$$$ integers, the original array $$$a_1, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). It is guaranteed that an answer exists. If there are multiple answers, print any.

process.stdin.resume()
process.stdin.setEncoding('utf8')
let arr = ""
process.stdin.on('data', function(chunk) {
  arr += chunk
});

process.stdin.on('end', () => {
  arr = arr.split('\n')
  const number = parseInt(arr.shift())
  const firstRow = arr[0].split(' ')
  const secondRow = arr[1].split(' ')
  const a1 = Math.sqrt(firstRow[1] * firstRow[2] / secondRow[2])

  process.stdout.write(a1 + ' ')

  for(let i = 1; i < number; i ++){
    process.stdout.write(`${firstRow[i] / a1} `)
  }
  console.log()
})

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});
let lineCount = 0, num, multiArr = [];
rl.on('line', function (line) {
    if (lineCount === 0) {
        num = Number(line.trim());
    } else {
        multiArr.push(line.trim().split(' ').map((item) => parseInt(item)));
    }
    if (lineCount === num) {
        console.log(getTable(multiArr));
        rl.close();
    }
    lineCount++;
});

function getTable(multiArr) {
    let len = multiArr.length;
    let resArr = [];
    for (let i = 0; i < len; i++) {
        resArr.push(getMain(i, len));
    }
    return resArr.join(' ');
}

function getMain(i, len) {
    let j, k;
    if (i === 0) {
        j = i + 1, k = i + 2;
    } else if (i === len - 1) {
        j = i - 1, k = i - 2;
    } else {
        j = i - 1; k = i + 1;
    }
    let Mij = multiArr[i][j];
    let Mik = multiArr[i][k];
    let Mjk = multiArr[j][k];
    return Math.sqrt((Mij * Mik) / Mjk);
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});
let lineCount = 0, num, multiArr = [];
rl.on('line', function (line) {
    if (lineCount === 0) {
        num = Number(line.trim());
    } else {
        multiArr.push(line.trim().split(' ').map((item) => parseInt(item)));
    }
    if (lineCount === num) {
        console.log(getTable(multiArr));
        rl.close();
    }
    lineCount++;
});

function getTable(multiArr) {
    let len = multiArr.length;
    let resArr = [];

    function getMain(i) {
        let j, k;
        if (i === 0) {
            j = i + 1, k = i + 2;
        } else if (i === len - 1) {
            j = i - 1, k = i - 2;
        } else {
            j = i - 1; k = i + 1;
        }
        let Mij = multiArr[i][j];
        let Mik = multiArr[i][k];
        let Mjk = multiArr[j][k];
        return Math.sqrt((Mij * Mik) / Mjk)
    }

    for (let i = 0; i < len; i++) {
        resArr.push(getMain(i));
    }
    return resArr.join(' ')
}

'use strict'

const size = parseInt(readline());
const M0 = readline().split(' ').map(Number);
const M1 = readline().split(' ').map(Number);

const a0 = Math.sqrt(M0[1] * M0[2] / M1[2]);
write(a0 + ' ' + M0.slice(1).map(i => i / a0).join(' '));

"use strict";

String.prototype.getNumArray = function () {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  });
};

var n = parseInt(readline());
var m = [];

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

var x1 = Math.sqrt(m[0][1] * m[1][2] / m[0][2]);
var answ = [];

for (var _i = 0; _i < n; _i++) {
  if (_i == 1) {
    answ.push(x1);
  } else {
    answ.push(m[_i][1] / x1);
  }
}

write(answ.join(' '));

'use strict'

const size = parseInt(readline());
const M0 = readline().split(' ').map(Number);
const M1 = readline().split(' ').map(Number);

const a0 = Math.sqrt(M0[1] * M0[2] / M1[2]);
write(a0 + M0.slice(1).map(i => i / a0));