You are given an array $$$a$$$ of size $$$n$$$.You can perform the following operation on the array:   Choose two different integers $$$i, j$$$ $$$(1 \leq i < j \leq n$$$), replace $$$a_i$$$ with $$$x$$$ and $$$a_j$$$ with $$$y$$$. In order not to break the array, $$$a_i | a_j = x | y$$$ must be held, where $$$|$$$ denotes the bitwise OR operation. Notice that $$$x$$$ and $$$y$$$ are non-negative integers. Please output the minimum sum of the array you can get after using the operation above any number of times.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \leq t \leq 1000)$$$. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(2 \leq n \leq 100)$$$ — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots ,a_n$$$ $$$(0 \leq a_i < 2^{30})$$$.

For each test case, print one number in a line — the minimum possible sum of the array.

NoteIn the first example, you can perform the following operations to obtain the array $$$[1, 0, 2]$$$:1. choose $$$i = 1, j = 2$$$, change $$$a_1 = 1$$$ and $$$a_2 = 2$$$, it's valid since $$$1 | 3 = 1 | 2$$$. The array becomes $$$[1, 2, 2]$$$.2. choose $$$i = 2, j = 3$$$, change $$$a_2 = 0$$$ and $$$a_3 = 2$$$, it's valid since $$$2 | 2 = 0 | 2$$$. The array becomes $$$[1, 0, 2]$$$.We can prove that the minimum sum is $$$1 + 0 + 2 = 3$$$In the second example, We don't need any operations.

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = readline().split(" ");
    var result = parseInt(caseArray[0]).toString(2);
    for (var j = 1; j < caseLength; j++)
    {
        var current = parseInt(caseArray[j]).toString(2);
        result = calcBitwiseOR(result, current);
    }
    print(parseInt(result, 2));
}

function calcBitwiseOR(result, current)
{
    if (result.length > current.length)
    {
        var zerosToBeAdded = result.length - current.length;
        for (var i = 0; i < zerosToBeAdded; i++)
        {
            current = `0${current}`;
        }
    }
    else if (result.length < current.length)
    {
        var zerosToBeAdded = current.length - result.length;
        for (var i = 0; i < zerosToBeAdded; i++)
        {
            result = `0${result}`;
        }
    }
    var answer = "";
    for (var i = 0; i < result.length; i++)
    {
        if (result[i] === '1' || current[i] === '1')
        {
            answer += "1";
        }
        else answer += "0";
    }
    return answer;
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = readline().split(" ");
    var result = parseInt(caseArray[0]).toString(2);
    for (var j = 1; j < caseLength; j++)
    {
        var current = parseInt(caseArray[j]).toString(2);
        result = calcBitwiseOR(result, current);
    }
    print(parseInt(result, 2));
}

function calcBitwiseOR(result, current)
{
    if (result.length > current.length)
    {
        var zerosToBeAdded = result.length - current.length;
        for (var i = 0; i < zerosToBeAdded; i++)
        {
            current = `0${current}`;
        }
    }
    else if (result.length < current.length)
    {
        var zerosToBeAdded = current.length - result.length;
        for (var i = 0; i < zerosToBeAdded; i++)
        {
            result = `0${result}`;
        }
    }
    var answer = "";
    for (var i = 0; i < result.length; +i++)
    {
        if (result[i] === '1' || current[i] === '1')
        {
            answer += "1";
        }
        else answer += "0";
    }
    return answer;
}

"use strict";

const nQueues = Number(this.readline().split(" "));

for (let i = 0; i < nQueues; i++) {
  const size = Number(this.readline().split(" "));
  const numbers = this.readline()
    .split(" ")
    .map(Number)
    .map((n) => n.toString(2).split("").reverse().join(""));
  const pos = [];
  const z = [];

  numbers.forEach((n) => {
    for (let i = 0; i < n.length; i++) {
      const db = n[i];
      if (db == 0) z[i] = true;
      else pos[i] = true;
    }
  });

  const cap = pos.length > z.length ? pos.length - 1 : z.length - 1;
  const sol = [];
  for (let j = 0; j < numbers.length; j++) {
    let n = pos[cap - j] ? "1" : "0";
    for (let i = cap - j - 1; i >= 0; i--) {
      if (j < numbers.length - 1) {
        n += "0";
      } else {
        if (pos[i]) n += "1";
        else n += "0";
      }
    }
    sol.push(parseInt(n, 2));
  }
  this.print(sol.reduce((prev, curr) => prev + curr, 0));
}

let context = {}
context["throw"] = function(a) { throw a }
context["makeDict"] = function() { let ret = {}; for (let i = 0; i < arguments.length; i += 2) { ret[arguments[i]] = arguments[i + 1]; } return ret; }
context["dictKeys"] = function(dict) { return Object.keys(dict) }
context["parseInt"] = function(a) { return BigInt(a) }
context["nullCheck"] = function(a) { return a; }

function main(input) {
let lines = (input).split("\n");
let nextLine = 0n;
let nt = context.parseInt(lines[nextLine]);
let ret = [];
nextLine = nextLine+1n;
for (let t = 0n; t<nt; t = t+1n) {
let n = context.parseInt(lines[nextLine]);
nextLine = nextLine+1n;
let a = (((lines[nextLine]).split(" ")).map(function (x) { return context.parseInt(x)}));
nextLine = nextLine+1n;
let ans = 0n;
for (let i = 0n; i<BigInt((a).length); i = i+1n) {
ans = ans|a[i];

}
(ret).push(("" + (ans)));

}
return (ret).join("\n");
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8')
console.log(main(input));
/*1647044803.1801252*/

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
    let t = parseInt(readline())
    while(t--){
        let n = parseInt(readline())
        let v = readline().split(" ")
        let x = 0
        for(let i in v) x|=v[i]
        console.log(x)
    }
}

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
    let t = parseInt(readline())
    while(t--){
        let n = parseInt(readline())
        let v = readline().split(" ")
        let x = 0
        for(let i in v) x|=parseInt(v[i])
        console.log(x)
    }
}

'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++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);

        let r = 0;
        for (let i = 0; i < n; i++) {
            r |= arr[i];
        }
        output(r);
    }
}

'use strict';

function solve(n, a) {
  let res = 0;
  for (let i = 0; i < 31; i++) {
    for (let num of a) {
      if (num & 1 << i) res |= 1 << i;
    }
  }
  return res;
}

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

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

let 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];
	var n = 0;
	for(i = 1; i <= t * 2; i++){
	    if(i % 2 == 1){
	        n = lines[i];
	    }else{
	        var k = lines[i].split(' ').map(Number);
	        var ans = 0;
	        for(j = 0; j < n; j++){
	            ans |= k[j];
	        }
            console.log(ans);
	    }
	}
});

'use strict';

const { checkPrime } = require('crypto');
const { Z_FIXED } = require('zlib');

 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  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 l = process.env.DEBUG ? console.log : ()=>{};

module.exports = E;

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

const calc = (n, A)=>{
  let res = 0;
  for (let a of A){
    for (let i=1; i<=a; i*=2){
      if (a&i)
        res |= i;
    }
  }
  return res;
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let A = ra()
      l('ans')
      print(calc(n, A));
    }
}

E.calc = calc;

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() {
    var cases = readline();
    var preNum = [];

    for (var i = 0; i < 30; ++ i) {
        preNum.push(1 << i);
    }

    for (var i = 0; i < cases; ++ i) {
        readline();
        var nums = readline().split(' ');
        var filledPos = {}
        for (var j = 0; j < nums.length; ++ j) {
            for (var k = 0; k < 30; ++ k) {
                if ((nums[j] & preNum[k]) !== 0) {
                    filledPos[k] = preNum[k];
                }
            }
        }
        console.log(Object.values(filledPos).reduce((prev, cur) => prev + cur, 0));
    }
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = readline().split(" ");
    var result = parseInt(caseArray[0]).toString(2);

    print(result);
}

function calcBitwiseOR(result, current)
{
    if (result.length > current.length)
    {
        var zerosToBeAdded = result.length - current.length;
        for (var i = 0; i < zerosToBeAdded; i++)
        {
            current = `0${current}`;
        }
    }
    else if (result.length < current.length)
    {
        var zerosToBeAdded = current.length - result.length;
        for (var i = 0; i < zerosToBeAdded; i++)
        {
            result = `0$result`;
        }
    }
    var answer = "";
    for (var i = 0; i < result.length; +i++)
    {
        if (result[i] === '1' || current[i] === '1')
        {
            answer += "1";
        }
        else answer += "0";
    }
    return answer;
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = readline().split(" ");
    var result = parseInt(caseArray[0]).toString(2);
    for (var j = 1; j < caseLength; j++)
    {
        var current = parseInt(caseArray[j]).toString(2);
        result = calcBitwiseOR(result, current);
    }
    print(parseInt(result, 2));
}

function calcBitwiseOR(result, current)
{
    if (result.length > current.length)
    {
        var zerosToBeAdded = result.length - current.length;
        for (var i = 0; i < zerosToBeAdded; i++)
        {
            current = `0${current}`;
        }
    }
    else if (result.length < current.length)
    {
        var zerosToBeAdded = current.length - result.length;
        for (var i = 0; i < zerosToBeAdded; i++)
        {
            result = `0$result`;
        }
    }
    var answer = "";
    for (var i = 0; i < result.length; +i++)
    {
        if (result[i] === '1' || current[i] === '1')
        {
            answer += "1";
        }
        else answer += "0";
    }
    return answer;
}

"use strict";

const nQueues = Number(this.readline().split(" "));

for (let i = 0; i < nQueues; i++) {
  const size = Number(this.readline().split(" "));
  const numbers = this.readline()
    .split(" ")
    .map(Number)
    .map((n) => n.toString(2).split("").reverse().join(""));
  const pos = [];
  const z = [];

  numbers.forEach((n) => {
    for (let i = 0; i < n.length; i++) {
      const db = n[i];
      if (db == 0) z[i] = true;
      else pos[i] = true;
    }
  });

  const cap = pos.length > z.length ? pos.length - 1 : z.length - 1;
  const sol = [];
  for (let j = 0; j < numbers.length; j++) {
    let n = pos[cap - j] ? "1" : "0";
    for (let i = cap - j - 1; i >= 0; i--) {
      n += "0";
    }
    sol.push(parseInt(n, 2));
  }

  this.print(sol.reduce((prev, curr) => prev + curr, 0));
}


The only difference with E2 is the question of the problem..Vlad built a maze out of $$$n$$$ rooms and $$$n-1$$$ bidirectional corridors. From any room $$$u$$$ any other room $$$v$$$ can be reached through a sequence of corridors. Thus, the room system forms an undirected tree.Vlad invited $$$k$$$ friends to play a game with them.Vlad starts the game in the room $$$1$$$ and wins if he reaches a room other than $$$1$$$, into which exactly one corridor leads.Friends are placed in the maze: the friend with number $$$i$$$ is in the room $$$x_i$$$, and no two friends are in the same room (that is, $$$x_i \neq x_j$$$ for all $$$i \neq j$$$). Friends win if one of them meets Vlad in any room or corridor before he wins.For one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time. Friends know the plan of a maze and intend to win. Vlad is a bit afraid of their ardor. Determine if he can guarantee victory (i.e. can he win in any way friends play).In other words, determine if there is such a sequence of Vlad's moves that lets Vlad win in any way friends play.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. The input contains an empty string before each test case. The first line of the test case contains two numbers $$$n$$$ and $$$k$$$ ($$$1 \le k < n \le 2\cdot 10^5$$$) — the number of rooms and friends, respectively. The next line of the test case contains $$$k$$$ integers $$$x_1, x_2, \dots, x_k$$$ ($$$2 \le x_i \le n$$$) — numbers of rooms with friends. All $$$x_i$$$ are different. The next $$$n-1$$$ lines contain descriptions of the corridors, two numbers per line $$$v_j$$$ and $$$u_j$$$ ($$$1 \le u_j, v_j \le n$$$) — numbers of rooms that connect the $$$j$$$ corridor. All corridors are bidirectional. From any room, you can go to any other by moving along the corridors. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test is not greater than $$$2\cdot10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be "YES" if Vlad can guarantee himself a victory and "NO" otherwise. You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes" and "YES" will all be recognized as positive answers).

NoteIn the first test case, regardless of the strategy of his friends, Vlad can win by going to room $$$4$$$. The game may look like this:  The original locations of Vlad and friends. Vlad is marked in green, friends — in red.   Locations after one unit of time.   End of the game. Note that if Vlad tries to reach the exit at the room $$$8$$$, then a friend from the $$$3$$$ room will be able to catch him.

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

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(`\nTest #${testN}`, obj);

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

tests = [
`YES`, // Test #1
`NO`, // Test #2
`YES`, // Test #3
`NO`, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const calc = (testN)=>{
  // READING:
  readline();
  let [n, k] = ra();
  let K = ra();
  for (let i=0; i<k; i++)
    K[i]--;
  let G = {};
  for (let i=0; i<n-1; i++){
    let [v, u] = ra();
    v--;
    u--;
    if (!G[v])
      G[v] = [];
    G[v].push(u);
    if (!G[u])
      G[u] = [];
    G[u].push(v);
  }
  LT({n, k, K, G});
  // PROCESSING:
  let myQueue = [], mqi = 0;
  myQueue.push([0, -1]);
  let myVisited = new Set();
  let enemyQueue = [], eqi = 0;
  let enemyVisited = new Set();
  for (let i=0; i<k; i++){
    enemyQueue.push(K[i]);
    enemyVisited.add(K[i]);
  }
  while (mqi<myQueue.length){
    // process my queue
    let wave = myQueue.length;
    for (let i=mqi; i<wave; i++){
      let [v, p] = myQueue[i];
      if (enemyVisited.has(v))
        continue;
      let ch = G[v]||[];
      if (p>=0 && ch.length==1)
        return 'YES'
      for (let j=0; j<ch.length; j++){
        let u = ch[j];
        if (u==p || enemyVisited.has(u)){
          continue;
        }
        myQueue.push([u, v]);
      }
    }
    mqi = wave;
    // process enemy queue
    wave = enemyQueue.length;
    for (let i=eqi; i<wave; i++){
      let v = enemyQueue[i];
      let ch = G[v]||[];
      for (let j=0; j<ch.length; j++){
        if (!enemyVisited.has(ch[j])){
          enemyVisited.add(ch[j]);
          enemyQueue.push(ch[j])
        }
      }
    }
    eqi = wave;
  }
  return 'NO';
};

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, f] = lines[l++].trim().split(' ').map(Number)
        const fs = 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, f, fs, edges)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, f, fs, edges) {
    // const map = fs.reduce((o, x) => {
    //     o[x] = 1
    //     return 0
    // }, {})
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
// console.log(adj, min, leaf)
    // const q = fs.map(u => [u, 0, 0])
    // q.push([1, 0, 1])
    const q = Array(n + 1)
    fs.forEach((u, i) => q[i] = [u, 0, 0])
    q[fs.length] = [1, 0, 1]
    const visited = {}
let qi = 0
let qj = fs.length + 1
    while (qi < qj) {
    // while (q.length) {
        // const [u, d, isr] = q.shift()
        const [u, d, isr] = q[qi++]
        if (visited[u]) {
            if (visited[u][0] === d) visited[u][1] = 0
            continue
        }
        visited[u] = [d, isr]

        ;(adj[u] || []).forEach(v => {
            if (visited[v]) return
            // q.push([v, d + 1, isr])
            q[qj++] = ([v, d + 1, isr])
        })
    }
// console.log('visited', visited)
    for (let u = 2; u <= n; u++) {
        if (adj[u].length === 1 && visited[u][1]) return 'YES'
    }
    return 'NO'
}

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

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(`\nTest #${testN}`, obj);

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

tests = [
`YES`, // Test #1
`NO`, // Test #2
`YES`, // Test #3
`NO`, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const calc = (testN)=>{
  // READING:
  readline();
  let [n, k] = ra();
  let K = ra();
  for (let i=0; i<k; i++)
    K[i]--;
  let G = {};
  for (let i=0; i<n-1; i++){
    let [v, u] = ra();
    v--;
    u--;
    if (!G[v])
      G[v] = [];
    G[v].push(u);
    if (!G[u])
      G[u] = [];
    G[u].push(v);
  }
  LT({n, k, K, G});
  // PROCESSING:
  let myQueue = [], mqi = 0;
  myQueue.push([0, -1]);
  let myVisited = new Set();
  let enemyQueue = [], eqi = 0;
  let enemyVisited = new Set();
  for (let i=0; i<k; i++){
    enemyQueue.push(K[i]);
    enemyVisited.add(K[i]);
  }
  while (mqi<myQueue.length){
    // process enemy queue
    let wave = enemyQueue.length;
    for (let i=eqi; i<wave; i++){
      let v = enemyQueue[i];
      let ch = G[v]||[];
      for (let j=0; j<ch.length; j++){
        if (!enemyVisited.has(ch[j])){
          enemyVisited.add(ch[j]);
          enemyQueue.push(ch[j])
        }
      }
    }
    eqi = wave;
    // process my queue
    while (mqi<myQueue.length){
      let [v, p] = myQueue[mqi++];
      let ch = G[v]||[];
      if (p>=0 && ch.length==1)
        return 'YES'
      for (let j=0; j<ch.length; j++){
        let u = ch[j];
        if (u==p || enemyVisited.has(u)){
          continue;
        }
        myQueue.push([u, v]);
      }
    }
  }
  return 'NO';
};

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

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(`\nTest #${testN}`, obj);

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

tests = [
`YES`, // Test #1
`NO`, // Test #2
`YES`, // Test #3
`NO`, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const calc = (testN)=>{
  // READING:
  readline();
  let [n, k] = ra();
  let K = ra();
  for (let i=0; i<k; i++)
    K[i]--;
  let G = {};
  for (let i=0; i<n-1; i++){
    let [v, u] = ra();
    v--;
    u--;
    if (!G[v])
      G[v] = [];
    G[v].push(u);
    if (!G[u])
      G[u] = [];
    G[u].push(v);
  }
  LT({n, k, K, G});
  // PROCESSING:
  let myQueue = [], mqi = 0;
  myQueue.push([0, -1]);
  let myVisited = new Set();
  let enemyQueue = [], eqi = 0;
  let enemyVisited = new Set();
  for (let i=0; i<k; i++){
    enemyQueue.push(K[i]);
    enemyVisited.add(K[i]);
  }
  while (mqi<myQueue.length){
    // process my queue
    while (mqi<myQueue.length){
      let [v, p] = myQueue[mqi++];
      if (enemyVisited.has(v))
        continue;
      let ch = G[v]||[];
      if (p>=0 && ch.length==1)
        return 'YES'
      for (let j=0; j<ch.length; j++){
        let u = ch[j];
        if (u==p || enemyVisited.has(u)){
          continue;
        }
        myQueue.push([u, v]);
      }
    }
    // process enemy queue
    let wave = enemyQueue.length;
    for (let i=eqi; i<wave; i++){
      let v = enemyQueue[i];
      let ch = G[v]||[];
      for (let j=0; j<ch.length; j++){
        if (!enemyVisited.has(ch[j])){
          enemyVisited.add(ch[j]);
          enemyQueue.push(ch[j])
        }
      }
    }
    eqi = wave;
  }
  return 'NO';
};

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

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(`\nTest #${testN}`, obj);

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

tests = [
`YES`, // Test #1
`NO`, // Test #2
`YES`, // Test #3
`NO`, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const calc = (testN)=>{
  // READING:
  readline();
  let [n, k] = ra();
  let K = ra();
  for (let i=0; i<k; i++)
    K[i]--;
  let G = {};
  for (let i=0; i<n-1; i++){
    let [v, u] = ra();
    v--;
    u--;
    if (!G[v])
      G[v] = [];
    G[v].push(u);
    if (!G[u])
      G[u] = [];
    G[u].push(v);
  }
  LT({n, k, K, G});
  // PROCESSING:
  let myQueue = [], mqi = 0;
  myQueue.push([0, -1]);
  let myVisited = new Set();
  let enemyQueue = [], eqi = 0;
  let enemyVisited = new Set();
  for (let i=0; i<k; i++){
    enemyQueue.push(K[i]);
    enemyVisited.add(K[i]);
  }
  while (mqi<myQueue.length){
    // process my queue
    while (mqi<myQueue.length){
      let [v, p] = myQueue[mqi++];
      if (enemyVisited.has(v))
        continue;
      let ch = G[v]||[];
      for (let j=0; j<ch.length; j++){
        let u = ch[j];
        if (u==p || enemyVisited.has(u)){
          continue;
        }
        myQueue.push([u, v]);
        if (!G[u] || G[u].length==1)
          return 'YES';
      }
    }
    // process enemy queue
    let wave = enemyQueue.length;
    for (let i=eqi; i<wave; i++){
      let v = enemyQueue[i];
      let ch = G[v]||[];
      for (let j=0; j<ch.length; j++){
        if (!enemyVisited.has(ch[j])){
          enemyVisited.add(ch[j]);
          enemyQueue.push(ch[j])
        }
      }
    }
    eqi = wave;
  }
  return 'NO';
};

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, f] = lines[l++].trim().split(' ').map(Number)
        const fs = 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, f, fs, edges)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, f, fs, edges) {
    // const map = fs.reduce((o, x) => {
    //     o[x] = 1
    //     return 0
    // }, {})
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
    const [min, leaf] = dfs(adj, 1, {}) // min
// console.log(adj, min, leaf)
    const q = fs.map(u => [u, 0])
    const visited = {}
    let count = 0
    while (q.length) {
        const [u, d] = q.shift()
        if (visited[u]) continue
        visited[u] = 1
        if (u !== 1 && adj[u].length === 1) count++

        ;(adj[u] || []).forEach(v => {
            if (visited[v]) return
            if (d + 1 <= min) {
                q.push([v, d + 1])
            }
        })
    }
// console.log('visited', visited, count)
    return count < leaf ? 'YES' : 'NO'
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1, 0]]
    let ans = Infinity
    let leaf = 0
    while (stack.length) {
        const [u, i, p, d] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            if (u !== r && nb.length === 1) {
                leaf++
                ans = Math.min(d, ans)
            }
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u, d + 1])
            }
        } else {
            // last visited
            stack.pop()
        }
    }
    return [ans, leaf]
}

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, f] = lines[l++].trim().split(' ').map(Number)
        const fs = 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, f, fs, edges)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, f, fs, edges) {
    // const map = fs.reduce((o, x) => {
    //     o[x] = 1
    //     return 0
    // }, {})
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
    const [min, leaf] = dfs(adj, 1, {}) // min
// console.log(adj, min, leaf)
    const q = fs.map(u => [u, 0])
    const visited = {}
    let count = 0
    while (q.length) {
        const [u, d] = q.shift()
        if (visited[u]) continue
        visited[u] = 1
        if (u !== 1 && adj[u].length === 1) count++

        ;(adj[u] || []).forEach(v => {
            if (visited[v]) return
            if (d + 1 < min) {
                q.push([v, d + 1])
            }
        })
    }
    return count < leaf ? 'YES' : 'NO'
}
function dfs(adj, r, visited) {
    const stack = [[r, 0, -1, 0]]
    let ans = 0
    let leaf = 0
    while (stack.length) {
        const [u, i, p, d] = stack[stack.length - 1]
        visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
            ans = Math.max(d, ans)
            if (u !== r && nb.length === 1) leaf++
        }
        if (i < nb.length) {
            stack[stack.length - 1][1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u, d + 1])
            }
        } else {
            // last visited
            stack.pop()
        }
    }
    return [ans, leaf]
}


Let $$$LCM(x, y)$$$ be the minimum positive integer that is divisible by both $$$x$$$ and $$$y$$$. For example, $$$LCM(13, 37) = 481$$$, $$$LCM(9, 6) = 18$$$.You are given two integers $$$l$$$ and $$$r$$$. Find two integers $$$x$$$ and $$$y$$$ such that $$$l \le x < y \le r$$$ and $$$l \le LCM(x, y) \le r$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. Each test case is represented by one line containing two integers $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le 10^9$$$).

For each test case, print two integers:   if it is impossible to find integers $$$x$$$ and $$$y$$$ meeting the constraints in the statement, print two integers equal to $$$-1$$$;  otherwise, print the values of $$$x$$$ and $$$y$$$ (if there are multiple valid answers, you may print any of them).

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){
    var returnObj = {
      list : input, index : 0, max : input.length,
      hasNext : function(){return (this.index < this.max);},
      next : function(){
        if(!this.hasNext()){

            throw "ArrayIndexOutOfBoundsException これ以上ないよ";
        }
        else{
            var returnInput = this.list[this.index];
            this.index++;
            return returnInput;
        }
    }};
    return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
      //[no]要素の扱い。数値型
      //不明値、異常時:引数そのまま返す 1:数値へ変換
      //2:半角SPで分割 4:半角SPで分割し、数値配列へ
      //6:1文字で分割  7:1文字で分割し、数値配列へ
      //8:半角SPで結合 9:改行で結合 0:文字なしで結合
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;
    }
}
function Main(){
    var output = [];

    var tc = nextInt() ;

    // myout(m+ " "+d)
    while(tc--) {
        var v = nextIntArray();
        var a = v[0] ;
        var b = v[1] ;
        var c = b / a ;
        if(c < 2) {
            myout("-1 -1") ;
        }
        else {
            myout(a+" "+(a*2))
        }
    }

}

'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').join(' ').split(' ').map(string => {
        return string.trim();
    });

    main();
});

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

function print(x) {
    process.stdout.write(x)
    process.stdout.write('\n')
}

function main() {
    let t = Number(read())
    while(t) {
        t -= 1
        let x = Number(read())
        let y = Number(read())
        if (x * 2 <= y) {
            print(String(x) + ' ' + String(x * 2))
        } else {
            print('-1 -1')
        }
    }
}

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 [l, r] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    if (l * 2 <= r) {
      console.log(`${l} ${l * 2}`);
    } else {
      console.log(`-1 -1`);
    }
  }
}

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

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
  	var tmp = nextIntArray();
  	var L = tmp[0];
  	var R = tmp[1];
  	if(L * 2 <= R){
  		output[i] = L + " " + (L * 2);
  	}else{
  		output[i] = "-1 -1";
  	}
  }
  myout(myconv(output, 9));
}
function getDivisorList(val){
  var list = [];
  for(var i = 1; i * i <= val; i++){
    if(val % i == 0){
      list.push(i);
      if(i * i != val){
        list.push(val / i);
      }
    }
  }
  list.sort(function(a,b){ return a - b; });
  return list;
}

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

let stdinInput = '';

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

process.stdin.on('end', () => {
  main(stdinInput);
});

function main(data) {
	data = data.split('\n');
	const testCases = data[0] * 1;
	let i = 1;
	while (i <= testCases) {
    let a = data[i].trim().split(' ').map(Number);
    let l = a[0];
    let r = a[1];
    let j = 2;
    while (true) {
      let m = l * j;
      if (m <= r) {j = m; break;}
      if (m > r) {j = -1; break;}
      j += 1;
    }
    if (j < 0) l = -1;
    console.log(l, j);
    i += 1;
	}
}

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 cases = +readLine();

	while (cases--) {
		let [l, r] = readLine()
			.split(' ')
			.map(x => parseInt(x));

		if (l * 2 <= r) {
			console.log(l, l * 2);
		} else {
			console.log(-1, -1);
		}
	}
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numCases = readLine();
    for (let c = 0; c < numCases; c++) {
        const [l, r] = readLine().split(" ").map(i => parseInt(i));
        if (l * 2 <= r)
            console.log(l, l * 2);
        else
            console.log(-1, -1);
    }
}

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){
    var returnObj = {
      list : input, index : 0, max : input.length,
      hasNext : function(){return (this.index < this.max);},
      next : function(){
        if(!this.hasNext()){

            throw "ArrayIndexOutOfBoundsException これ以上ないよ";
        }
        else{
            var returnInput = this.list[this.index];
            this.index++;
            return returnInput;
        }
    }};
    return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
      //[no]要素の扱い。数値型
      //不明値、異常時:引数そのまま返す 1:数値へ変換
      //2:半角SPで分割 4:半角SPで分割し、数値配列へ
      //6:1文字で分割  7:1文字で分割し、数値配列へ
      //8:半角SPで結合 9:改行で結合 0:文字なしで結合
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;
    }
}
function Main(){
    var output = [];

    var tc = nextInt() ;

    // myout(m+ " "+d)
    while(tc--) {
        var v = nextIntArray();
        if(v[0] === v[1]-1) {
            myout("-1 -1") ;
        }
        else {
            myout(v[1]+" "+v[1]) ;
        }
    }

}

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

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
  	var tmp = nextIntArray();
  	var L = tmp[0];
  	var R = tmp[1];
  	var list = getDivisorList(R);
  	for(var j = 0; j < list.length; j++){
  		if(list[j] >= L && list[j] < R){
  			output[i] = list[j] + " " + R;
  			break;
  		}
  	}
  	if(output[i] == null){
  		output[i] = "-1 -1";
  	}
  }
  myout(myconv(output, 9));
}
function getDivisorList(val){
  var list = [];
  for(var i = 1; i * i <= val; i++){
    if(val % i == 0){
      list.push(i);
      if(i * i != val){
        list.push(val / i);
      }
    }
  }
  list.sort(function(a,b){ return a - b; });
  return list;
}


Ann and Borya have n piles with candies and n is even number. There are ai candies in pile with number i.Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile). Find out minimal number of moves that is required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer.

First line contains one even integer n (2 ≤ n ≤ 200 000) — number of piles with candies. Second line contains sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 109) — amounts of candies in each pile.

Output minimal number of steps required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer. If condition is already satisfied output 0.

NoteIn first example you can satisfy condition in two moves. During each move you should add one candy to second pile. After it size of second pile becomes 16. After that Borya and Ann will have two piles with number of candies which is a square of integer (second and fourth pile) and two piles with number of candies which is not a square of any integer (first and third pile).In second example you should add two candies to any three piles.

T=[0]
function sg() {
	var i=1;
	while (T[i-1] <= 1000000000) { T.push(i*i); ++i }
}
function ns(x,lb,up) {
	var m=(up+lb)>>1;
	if (lb+1===up) return up;
	if (T[m]<x)
		return ns(x,m,up)
	else if (x<T[m])
		return ns(x,lb,m)
	return m;
}
function md(x) {
	var i=ns(x,0,T.length);
	return Math.min(Math.abs(T[i]-x), Math.abs(T[Math.max(0, i-1)]-x));
}
sg()

readline()
A=readline().split(' ').map(function(i){
	var x=Number(i)
	var t=md(x)
	return {
		i:x,
		w:t,
	};
})

A.sort(function(l,r) { return l.w!==r.w ? (l.w-r.w) : (l.i-r.i); })

R=0
for (var i=0;i<(A.length>>1);++i) R+=A[i].w
for (var i=(A.length>>1);i<A.length;++i) {
	if (!A[i].w) {
		R+=(A[i].i ? 1 : 2)
	}
}
print(R)

T=[0]
function sg() {
	var i=1;
	while (T[i-1] <= 1000000000) { T.push(i*i); ++i }
}
function ns(x,lb,up) {
	var m=(up+lb)>>1;
	if (lb+1===up) return up;
	if (T[m]<x)
		return ns(x,m,up)
	else if (x<T[m])
		return ns(x,lb,m)
	return m;
}
function md(x) {
	var i=ns(x,0,T.length);
	return Math.min(Math.abs(T[i]-x), Math.abs(T[Math.max(0, i-1)]-x));
}
sg()

readline()
A=readline().split(' ').map(function(i){
	var x=Number(i)
	var t=md(x)
	return {
		i:x,
		w:t,
	};
})

A.sort(function(l,r) { return l.w-r.w; })
R=0
for (var i=0;i<(A.length>>1);++i) R+=A[i].w
for (var i=(A.length>>1);i<A.length;++i) {
	if (!A[i].w) {
		R+=(A[i].i ? 1 : 2)
	}
}
print(R)


Masha has $$$n$$$ types of tiles of size $$$2 \times 2$$$. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.Masha decides to construct the square of size $$$m \times m$$$ consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding.Symmetric with respect to the main diagonal matrix is such a square $$$s$$$ that for each pair $$$(i, j)$$$ the condition $$$s[i][j] = s[j][i]$$$ holds. I.e. it is true that the element written in the $$$i$$$-row and $$$j$$$-th column equals to the element written in the $$$j$$$-th row and $$$i$$$-th column.Your task is to determine if Masha can construct a square of size $$$m \times m$$$ which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she can not rotate tiles, she can only place them in the orientation they have in the input.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 100$$$) — the number of types of tiles and the size of the square Masha wants to construct. The next $$$2n$$$ lines of the test case contain descriptions of tiles types. Types of tiles are written one after another, each type is written on two lines.  The first line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ — the number written in the top left corner of the tile and the number written in the top right corner of the tile of the current type. The second line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ — the number written in the bottom left corner of the tile and the number written in the bottom right corner of the tile of the current type. It is forbidden to rotate tiles, it is only allowed to place them in the orientation they have in the input.

For each test case print the answer: "YES" (without quotes) if Masha can construct the square of size $$$m \times m$$$ which is a symmetric matrix. Otherwise, print "NO" (withtout quotes).

NoteThe first test case of the input has three types of tiles, they are shown on the picture below.  Masha can construct, for example, the following square of size $$$4 \times 4$$$ which is a symmetric matrix:

var t = Number( readline() );
for(var i=0; i<t; i++){
 var r = readline().split(' ').map(a=>Number(a));
 var n = r[0];
 var m = r[1];
 var res = 0;
 for(var j=0;j<n;j++){
  if(readline().split(' ').map(a=>Number(a))[1] == readline().split(' ').map(a=>Number(a))[0]){
   res = 1;
  }
 }
 if(m&1) res=0;
 print((res==1)?"YES":"NO");
}

function int(v) {
        return parseInt(v)
}

var t = int(readline())

while(t--) {
        var arr = readline().split(' ').map(int)
        var n = arr[0], m = arr[1]
        var type2 = 0

        for(var i = 0; i < n; i++) {
                var block1 = readline().split(' ').map(int)
                var block2 = readline().split(' ').map(int)
                type2 += (block1[1] == block2[0])
        }

        print((m % 2 === 0 && type2 ? 'YES' : 'NO'))
}

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

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    let [len, target] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    let d = 0;
    let found = false;
    while (len--) {
      const [r0c0, r0c1] = readLine()
        .split(" ")
        .map((n) => parseInt(n));
      const [r1c0, r1c1] = readLine()
        .split(" ")
        .map((n) => parseInt(n));
      if (r0c1 === r1c0) d++;
    }
    if (d > 0 && target % 2 === 0) {
      console.log("YES");
    } else console.log("NO");
  }
}

//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↑入力 ↓出力');
  Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var N = one[0];
    var M = one[1];
    var isOK = false;
    for(var j = 0; j < N; j++){
      var L = nextIntArray();
      var R = nextIntArray();
      if(L[1] == R[0]){
        isOK = true;
      }
    }
    output[i] = (isOK) ? "YES" : "NO";
    if(M % 2 == 1){
      output[i] = "NO";
    }
  }
  myout(myconv(output, 9));
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn, init) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b, fn);
  if (b < a) return [];
  let arr = Array(b - a + 1).fill(0);
  if (init) init(arr);
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}
// [m] = extendedEuclid(a, 998244353);
// let MOD = 998244353n;
// let gt = Arr(n, (i, a) => i == 0 ? 1n : a[i - 1] * BigInt(i) % MOD);
// let rgt = Arr(n, (i, a) => i <= 1 ? 1n : MOD - MOD / BigInt(i) * a[998244353 % i] % MOD);
// for (let i = 2; i < n; i++) rgt[i] = rgt[i] * rgt[i - 1] % MOD;
// let nCk = (n, k) => gt[n] * rgt[k] * rgt[n - k] % MOD;
// for (let i = dm[l.l]; i <= n + n; i += i & -i) s[i]++; // start from index 1

// let p = [2, 3, 5];
// for (let i = 6; i < 1e5; i += 6) {
//   let j, x = i + 1;
//   for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;
//   if (x % p[j] != 0) p.push(x);
//   x = i + 5;
//   for (j = 0; p[j] * p[j] <= x; j++) if (x % p[j] == 0) break;
//   if (x % p[j] != 0) p.push(x);
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, min = Math.min, max = Math.max, abs = Math.abs;
  let t = $()
  while (t--) {
    let n = $(), m = $()
    let a = $(n * 4)
    if (m % 2 == 1) log('NO')
    else {
      log(For(n, i => a[i * 4 + 1] == a[i * 4 + 2] ? 1 : null) ? 'YES' : 'NO')
    }
  }
}

function int(v) {
        return parseInt(v)
}

var t = int(readline())

while(t--) {
        var arr = readline().split(' ').map(int)
        var n = arr[0], m = arr[1]
        var type1 = 0, type2 = 0

        for(var i = 0; i < n; i++) {
                var block1 = readline().split(' ').map(int)
                var block2 = readline().split(' ').map(int)
                type1 += (block1[0] == block2[1] && block1[1] == block2[0])
                type2 += (block1[0] == block2[1])
        }

        print((m % 2 === 0 && type1 && type1 + type2 > 1 ? 'YES' : 'NO'))
}

function int(v) {
        return parseInt(v)
}

var t = int(readline())

while(t--) {
        var arr = readline().split(' ').map(int)
        var n = arr[0], m = arr[1]
        var type2 = 0

        for(var i = 0; i < n; i++) {
                var block1 = readline().split(' ').map(int)
                var block2 = readline().split(' ').map(int)
                type2 += (block1[0] == block2[1])
        }

        print((m % 2 === 0 && type2 ? 'YES' : 'NO'))
}

function int(v) {
        return parseInt(v)
}

var t = int(readline())

while(t--) {
        var arr = readline().split(' ').map(int)
        var n = arr[0], m = arr[1]
        var type1 = 0

        for(var i = 0; i < n; i++) {
                var block1 = readline().split(' ').map(int)
                var block2 = readline().split(' ').map(int)
                type1 += (block1[0] == block2[1] && block1[1] == block2[0])
        }

        print((m % 2 === 0 && type1 ? 'YES' : 'NO'))
}

function int(v) {
        return parseInt(v)
}

var t = int(readline())

while(t--) {
        var arr = readline().split(' ').map(int)
        var n = arr[0], m = arr[1]
        var type1 = 0, type2 = 0

        for(var i = 0; i < n; i++) {
                var block1 = readline().split(' ').map(int)
                var block2 = readline().split(' ').map(int)
                type1 += (block1[0] == block2[1] && block1[1] == block2[0])
                type2 += (block1[0] == block2[1])
        }

        print((type1 && type1 + type2 > 1 ? 'YES' : 'NO'))
}

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

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    let [len, target] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    let [d1, d2] = [0, 0];
    let found = false;
    while (len--) {
      const [r0c0, r0c1] = readLine()
        .split(" ")
        .map((n) => parseInt(n));
      const [r1c0, r1c1] = readLine()
        .split(" ")
        .map((n) => parseInt(n));
      if (r0c0 === r1c1) d1++;
      if (r0c1 === r1c0) d2++;
    }
    if (d1 > 0 && d2 > 0 && target % 2 === 0) {
      console.log("YES");
    } else console.log("NO");
  }
}

//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↑入力 ↓出力');
  Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var N = one[0];
    var M = one[1];
    var isOK = false;
    for(var j = 0; j < N; j++){
      var L = nextIntArray();
      var R = nextIntArray();
      if(L[0] == R[1] && L[1] == R[0]){
        isOK = true;
      }
    }
    output[i] = (isOK) ? "YES" : "NO";
    if(M % 2 == 1){
      output[i] = "NO";
    }
  }
  myout(myconv(output, 9));
}


It is a complicated version of problem F1. The difference between them is the constraints (F1: $$$k \le 2$$$, F2: $$$k \le 10$$$).You are given an integer $$$n$$$. Find the minimum integer $$$x$$$ such that $$$x \ge n$$$ and the number $$$x$$$ is $$$k$$$-beautiful.A number is called $$$k$$$-beautiful if its decimal representation having no leading zeroes contains no more than $$$k$$$ different digits. E.g. if $$$k = 2$$$, the numbers $$$3434443$$$, $$$55550$$$, $$$777$$$ and $$$21$$$ are $$$k$$$-beautiful whereas the numbers $$$120$$$, $$$445435$$$ and $$$998244353$$$ are not.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le k \le 10$$$).

For each test case output on a separate line $$$x$$$ — the minimum $$$k$$$-beautiful integer such that $$$x \ge n$$$.

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

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

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

// for (let i = 600000; i <= 633633; i++) {
//     if (solve(i, 2) === '633333') {
//         console.log(i)
//     }
// }

function solve(n, k) {
    const s = String(n)
    const r = []
    const first = []
    for (let i = 0; i < s.length; i++) {
        let c = +s[i]
        const has = first.some(x => x[0] === c)
        if (has) {
            r[i] = c
        } else if (first.length < k) {
            first.push([c, i])
            r[i] = c
        } else {
            let min = Math.min(...r)
            let max = Math.max(...r)
            if (c <= min) {
                r.push(...Array(s.length - r.length).fill(min))
            } else if (c <= max) {
                while (r.indexOf(c) < 0) c++
                r[i] = c
                r.push(...Array(s.length - r.length).fill(min))
            } else {
                if (r[i - 1] < max) {
                    const uniq = r.filter(x => x === r[i - 1]).length === 1
                    if (r.indexOf(r[i - 1] + 1) >= 0) {
                        r[i - 1]++
                        r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                    } else if (uniq) {
                        r[i - 1]++
                        r.push(...Array(s.length - r.length).fill(Math.min(...r)))
                    } else {
                        let prev = r.pop() + 1
                        while (r.indexOf(prev) < 0) prev++
                        r.push(prev)
                        r.push(...Array(s.length - r.length).fill(uniq ? 0 : min))
                    }
                } else {
                    // the first not equals max
                    let p = i - 1
                    for (; p >= 0; p--) {
                        if (r[p] !== max) break
                    }
                    // has max
                    let hmax = false
                    for (let x = p; x >= 0; x--) {
                        if (r[x] === max) {
                            hmax = true
                            break
                        }
                    }
                    if (!hmax) {
                        p++
                    }
                    r.length = p + 1
                        const uniq = r.filter(x => x === r[p]).length === 1
                        if (r.indexOf(r[p] + 1) >= 0) {
                            r[p]++
                            min = uniq ? 0 : min
                        } else if (uniq) {
                            r[p]++
                            min = Math.min(...r)
                        } else {
                            let prev = r.pop() + 1
                            while (r.indexOf(prev) < 0) prev++
                            r.push(prev)
                    // console.log(r, hmax, uniq)
                            min = uniq ? 0 : min
                        }
                        for (let x = p + 1; x < s.length; x++) {
                            r[x] = min
                        }
                    // } else {
                    //     const uniq = r.filter(x => x === r[p + 1]).length === 1
                    //     r[p + 1]++
                    //     if (k === 1) {
                    //         min = r[p + 1]
                    //     } else {
                    //         min = uniq ? 0 : Math.min(...r.slice(0, p + 2))
                    //     }
                    //     for (let x = p + 2; x < s.length; x++) {
                    //         r[x] = min
                    //     }
                    // }
                }
            }
            break
        }
    }
    return r.join('')
}

let inputs = []

function read() {
    return inputs.pop();
}

function readInt() {
    return parseInt(read());
}

function solve() {
    let test = readInt();
    while (test--) {
        let n = read();
        let k = readInt();
        let d = n.length;
        function can(s) {
            used = new Array(10).fill(0);
            for (let i = 0; i < s.length; i++) {
                used[parseInt(s[i])] = 1;
            }
            let cnt = 0;
            for (let i = 0; i < 10; i++) {
                cnt += used[i];
            }
            if (k < cnt) {
                return 0;
            }
            let mx = 0;
            for (let i = 0; i < 10; i++) if (used[i]) {
                mx = Math.max(mx, i);
            }
            if (cnt < k) {
                mx = 9;
            }
            while (s.length < n.length) {
                s = s + mx;
            }
            return n <= s;
        }
        s = "";
        while (s.length < n.length) {
            let found = 0;
            for (let i = 0; i < 10; i++) {
                let s2 = s;
                s2 += i;
                if (can(s2)) {
                    s = s2;
                    found = 1;
                    break;
                }
            }
            if (!found) {
                s = "";
                break;
            }
        }
        if (s != "") {
            console.log(s);
        }
        else {
            s = "1";
            for (let i = 0; i < n.length; i++) {
                s += "0";
            }
            console.log(s);
        }
    }
}

function main() {
    inputs = inputString.trim().split(/\n| /).map((string) => string.trim());
    inputs.reverse();
    solve();
}

let inputString = '';

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

process.stdin.on('end', (_) => { main(); });


Pushok the dog has been chasing Imp for a few hours already.  Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner. While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and  and . The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.Help Imp to find the maximum noise he can achieve by changing the order of the strings.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of strings in robot's memory. Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.

Print a single integer — the maxumum possible noise Imp can achieve by changing the order of the strings.

NoteThe optimal concatenation in the first sample is ssshhshhhs.

function countH(x){
    var l=0;
    for(var i=0;i<x.length;i++){
        if(x[i]=='h'){
            l++;
        }
    }
    return l;
}

function countS(x){
    var l=0;
    for(var i=0;i<x.length;i++){
        if(x[i]=='s'){
            l++;
        }
    }
    return l;
}

function calcNoise(x){
    var ls=0,lh=0,count=0;
    for(var i=0;i<x.length;i++){
        if(x[i]=='s'){
            ls++;
        }
        else{
            lh++;
        }
    }
    for(i=0;i<x.length;i++){
        if(x[i]=='s'){
            count+=lh;
        }
        else{
            lh--;
        }
    }
    return count;
}

function calc(a,b){
    return calcNoise(a)+calcNoise(b)+countS(a)*countH(b);
}

function main(){
    var n = readline().split(' ');
    var str=new Array(n);
    for(var i=0;i<n;i++){
        str[i]=readline();
    }

    str.sort(function(a,b){
        return calc(b,a)-calc(a,b);
    });
    var Fstr="";
    for(i=0;i<n;i++){
        Fstr+=str[i];
    }
    print(calcNoise(Fstr));
}

main();