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

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

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

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


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

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

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


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

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

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'))
}

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


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

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


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

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

const mxV = 1e5+10;

const par = Array.from(Array(mxV), x => [0, 0]);

function main () {
	let T = rn();
	while (T--) {

		for (let i = 0; i < mxV; i++) {
			par[i][0] = par[i][1] = 0;
		}

		const n = rn();
		const a = rna();

		for (let i = 0; i < n; i++) {
			par[a[i]][i&1]++;
		}

		a.sort((x, y) => x - y);

		let ok = true;
		for (let i = 0; ok && i < n; i++) {
			ok = --par[a[i]][i&1] >= 0;
		}

		console.log(ok ? 'YES' : 'NO');
	}
}

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

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

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

		const mxV = Math.max(...a) + 10;
		const par = Array.from(Array(mxV), x => [0, 0]);

		for (let i = 0; i < n; i++) {
			par[a[i]][i%2]++;
		}

		a.sort((x, y) => x - y);

		let ok = true;
		for (let i = 0; ok && i < n; i++) {
			ok = --par[a[i]][i%2] >= 0;
		}

		console.log(ok ? 'YES' : 'NO');
	}
}

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const assert = (condition) => { if (!condition) throw new Error("Assertion failed"); }
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const int = parseInt;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg2 = Math.log2;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };
const initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
const ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);
const isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 07/11/21 afternoon
const solve = (n, a) => {
    let b = [...a];
    stin(a);
    let ma = new Map();
    let mb = new Map();
    for (let i = 0; i < n; i++) {
        if (!ma.has(a[i])) ma.set(a[i], []);
        ma.get(a[i]).push(i % 2);
        if (!mb.has(b[i])) mb.set(b[i], []);
        mb.get(b[i]).push(i % 2);
    }
    // pr(ma, mb);
    for (const [x, na] of ma) {
        let nb = mb.get(x);
        // pr(na, nb);
        let sa = sb = 0;
        for (let i = 0; i < na.length; i++) {
            sa += na[i];
            sb += nb[i];
        }
        if (sa != sb) return pr('NO');
    }
    pr('YES');
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i + 1]);
            i += 2;
        }
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const assert = (condition) => { if (!condition) throw new Error("Assertion failed"); }
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const int = parseInt;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg2 = Math.log2;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };
const initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
const ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);
const isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 07/11/21 morning
 * https://codeforces.com/contest/1546/problem/C
 */
const solve = (n, a) => {
    let origin = [...a];
    let m = counter_value_in_indexA_in(origin);
    stin(a);
    let used = new Set();
    for (let i = 0; i < n; i++) {
        if (a[i] != origin[i]) {
            let idxA = m.get(a[i]);
            let find = false;
            for (const j of idxA) {
                if (!used.has(j) && abs(i - j) % 2 == 0) {
                    used.add(j);
                    find = true;
                    break;
                }
            }
            if (!find) return pr('NO');
        }
    }
    pr('YES');
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i + 1]);
            i += 2;
        }
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const assert = (condition) => { if (!condition) throw new Error("Assertion failed"); }
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const int = parseInt;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg2 = Math.log2;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };
const initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
const ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);
const isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 07/11/21 morning
 * https://codeforces.com/contest/1546/problem/C
 */
const solve = (n, a) => {
    let origin = [...a];
    let m = counter_value_in_indexA_in(origin);
    stin(a);
    for (let i = 0; i < n; i++) {
        if (a[i] != origin[i]) {
            let idxA = m.get(a[i]);
            let find = false;
            for (const j of idxA) {
                if (abs(i - j) % 2 == 0) {
                    find = true;
                    break;
                }
            }
            if (!find) return pr('NO');
        }
    }
    pr('YES');
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i + 1]);
            i += 2;
        }
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const assert = (condition) => { if (!condition) throw new Error("Assertion failed"); }
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const int = parseInt;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg2 = Math.log2;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(0); data.push(tmp); } return data; };
const initialize3DArray = (n, m, p) => { let res = []; for (let i = 0; i < n; i++) { let data = []; for (let j = 0; j < m; j++) { let tmp = new Array(p).fill(0); data.push(tmp); } res.push(data); } return res; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
const ups = (s, i, c) => s.slice(0, i) + c + s.slice(i + 1);
const isSubsequence = (s, t) => { let sn = s.length; let tn = t.length; let i = j = 0; while (i < sn && j < tn) { if (s[i] == t[j]) { i++; j++; } else { i++; } } return j == tn; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 07/11/21 morning
 * https://codeforces.com/contest/1546/problem/C
 */
const solve = (n, a) => {
    let origin = [...a];
    let m = counter_value_in_indexA_in(origin);
    stin(a);
    for (let i = 0; i < n; i++) {
        if (a[i] != origin[i]) {
            let idxA = m.get(a[i]);
            let find = false;
            for (const j of idxA) {
                if (abs(i - j) % 2 == 0) {
                    find = true;
                }
            }
            if (!find) return pr('NO');
        }
    }
    pr('YES');
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i + 1]);
            i += 2;
        }
    });
};

main()


'use strict'

let lll = readline().split(' ').map(v => parseInt(v))

const N = lll[0]
const M = lll[1]

let plc = -1

;(function () {
  while(lll = readline()) {
    let lc = lll[0]
    for (var i = 1; i < lll.length; i++) {
      if (lc != lll[i]) return print('NO')
    }
    if (plc == lc) return print('NO')
    plc = lc
  }
  print('YES')
})()

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

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

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

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

	var previousColor = -1;

	for (var r = 0; r < rowNum; r += 1) {
		var row = trim(readline());
		if (row[0] == previousColor) {
			print("NO");
			return;
		}
		previousColor = row[0];
		for (var c = 1; c < colNum; c += 1) {
			if (row[c] != row[c-1]) {
				print("NO");
				return;
			}
		}
	}

	print("YES");
}

main();

var nm = readline().split(' ').map(Number);
var n = nm[0];
var m = nm[1];
var f = [];
var ans = 'YES';
for (var i=0; i<n; i++){
	f[i] = readline();
}
for (var j=0; j<n; j++){
	for (var i=0; i<m-1; i++){
	if (f[j][i] != f[j][i+1]){
			ans = 'NO';
			break;
		}
	}
	if (j<n-1){
			if (f[j][0] == f[j+1][0]){
			ans = 'NO';
			break;
		}
	}
}
print(ans);

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

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

  const s = new Set(d);

  if (s.size !== 1 || prev === d[0]) {
    ans = 'NO';
  }
  else {
    prev = d[0];
  }

  c++;
});

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

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var isSameChar = function(str){
    for(let i=0; i<str.length; i++){
        if(str[0]!=str[i])
           return false;
    }
    return true;
}

var n, m, temp = [], indicator = 0, prev="", ans="YES";

rl.on('line', (input) => {
    if (indicator == 0) {
        temp = input.split(' ').map(item => parseInt(item));
        n = temp[0], m = temp[1];
        indicator++;
    }
    else {
        if(prev == input || !isSameChar(input))
            ans="NO";

       prev = input;
    }
}).on('close',function(){
    console.log(ans);
});

const readline = require('readline');

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

var IsSameColour = function (s) {
    // console.log("inside function s=%s  type is: %s", s, typeof s);
    for (let i = 1; i < s.length; i++) {
        if (s[0] != s[i])
            return false;
    }
    return true;
}

var prev, current, n, m, indicator = 0,
    ans = "YES";

rl.on('line', (current) => {
    if (indicator == 0) {
        var temp = current.split(' ').map(item => parseInt(item));
        n = temp[0];
        m = temp[1];
        indicator++;
    } else if (indicator == 1) {
        prev = current;

        if (!IsSameColour(prev)) {
            ans = "NO";
            rl.close();
        }
        indicator++;
    } else {
        if (!IsSameColour(current) || prev == current) {
            ans = "NO";
            //break;
            rl.close();
        }
        prev = current;

    }

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