You have a string $$$s$$$ consisting of lowercase Latin alphabet letters. You can color some letters in colors from $$$1$$$ to $$$k$$$. It is not necessary to paint all the letters. But for each color, there must be a letter painted in that color.Then you can swap any two symbols painted in the same color as many times as you want. After that, $$$k$$$ strings will be created, $$$i$$$-th of them will contain all the characters colored in the color $$$i$$$, written in the order of their sequence in the string $$$s$$$.Your task is to color the characters of the string so that all the resulting $$$k$$$ strings are palindromes, and the length of the shortest of these $$$k$$$ strings is as large as possible.Read the note for the first test case of the example if you need a clarification.Recall that a string is a palindrome if it reads the same way both from left to right and from right to left. For example, the strings abacaba, cccc, z and dxd are palindromes, but the strings abab and aaabaa — are not.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input data sets in the test.  The descriptions of the input data sets follow. The first line of the description of each input data set contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the length of the string and the number of colors in which its letters can be painted. The second line of the description of each input data set contains a string $$$s$$$ of length $$$n$$$ consisting of lowercase letters of the Latin alphabet. It is guaranteed that the sum of n over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each set of input data, output a single integer  — the maximum length of the shortest palindrome string that can be obtained.

10

8 2

bxyaxzay

6 3

aaaaaa

6 1

abcdef

6 6

abcdef

3 2

dxd

11 2

abcabcabcac

6 6

sipkic

7 2

eatoohd

3 1

llw

6 2

bfvfbv

Note In the first test case, $$$s$$$="bxyaxzay", $$$k=2$$$. We use indices in the string from $$$1$$$ to $$$8$$$. The following coloring will work: $$$\mathtt{\mathbf{\color{red}{b}\color{blue}{xy}\color{red}{a}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}$$$ (the letter z remained uncolored). After painting:  swap two red characters (with the indices $$$1$$$ and $$$4$$$), we get $$$\mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}$$$;  swap two blue characters (with the indices $$$5$$$ and $$$8$$$), we get $$$\mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{y}z\color{red}{a}\color{blue}{x}}}$$$. Now, for each of the two colors we write out the corresponding characters from left to right, we get two strings $$$\mathtt{\mathbf{\color{red}{aba}}}$$$ and $$$\mathtt{\mathbf{\color{blue}{xyyx}}}$$$. Both of them are palindromes, the length of the shortest is $$$3$$$. It can be shown that the greatest length of the shortest palindrome cannot be achieved. In the second set of input data, the following coloring is suitable: $$$[1, 1, 2, 2, 3, 3]$$$. There is no need to swap characters. Both received strings are equal to aa, they are palindromes and their length is $$$2$$$. In the third set of input data, you can color any character and take it into a string. In the fourth set of input data, you can color the $$$i$$$th character in the color $$$i$$$. In the fifth set of input data can be colored in each of the colors of one character. In the sixth set of input data, the following coloring is suitable: $$$[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0]$$$. Rearrange the characters so as to get the palindromes abcba and acbca.

/*
===== READ INPUT DATA START =====
=================================
*/

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

let inputString = '';

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

process.stdin.on('end', (_) => {
  const lines = inputString.trim().split('\n').map((string) => string.trim()).filter(Boolean);
  main(lines);
});

/*
===== READ INPUT DATA END =====
===============================
*/

function main(lines) {
  let index = 0;
  let T = Number(lines[index++]);
  let N;
  let K;
  let str;

  while (T--) {
    [N, K] = lines[index++].split(' ').map(Number);
    str = lines[index++];

    solve(N, K, str);
  }
}

function solve(N, K, str) {
  const map = new Map();
  let evenCount = 0;
  let value;
  let result;

  for (const char of str) {
    value = map.get(char) || 0;
    map.set(char, value + 1);
  }

  Array.from(map.values()).forEach((val) => {
    if (val % 2 === 0) {
      evenCount += val;
    } else {
      evenCount += val - 1;
    }
  });

  result = Math.floor(evenCount / K);

  if ((N - result * K) >= K && result % 2 === 0) {
    result++;
  }

  console.log(result);
}

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

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

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

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

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let [n, k] = ra();
  let s = readline();
  let cnt = {};
  for (let i=0; i<n; i++)
    cnt[s[i]] = (cnt[s[i]]||0)+1;
  LT({n, k, s});

  // PROCESSING:
  let K = new Array(k).fill(0);
  let i;
  for (i=0; i<n; i+=2){
    let ki = 0;
    for (let ci in cnt){
      if (ki==k)
        break;
      ki += cnt[ci]>>1;
    }
    if (ki<k)
      break;
    ki = 0;
    for (let ci in cnt){
      if (ki==k)
        break;
      while (cnt[ci]>=2 && ki<k){
        cnt[ci] -= 2;
        K[ki] += 2;
        ki++;
      }
    }
  }
    let ki = 0;
    for (let ci in cnt){
      ki += cnt[ci];
    }
    if (ki>=k)
      i++
  return i;
};

'use strict';
const readline = require('readline');
const util = require('util');
const rl = readline.createInterface({
    input: process.stdin,
});
let pos = 0;
const words = [];
rl.on('line', (line) => {
    words.push.apply(words, line.split(' ').filter(s => s != ''));
});
rl.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(words[pos++]));
}
function nextStr() {
    return words[pos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
const BASE = 'a'.charCodeAt(0);
let n;
let k;
let s;
function solve() {
    const cnt = af(26).fill(0);
    for (let i = 0; i < n; i++) {
        let c = s.charCodeAt(i) - BASE;
        cnt[c]++;
    }
    //  console.log(cnt);
    let ans = 0;
    while (true) {
        let has = 0;
        for (let i = 0; i < 26; i++) {
            if (cnt[i] >= 2) {
                has += cnt[i] - (cnt[i] % 2);
            }
        }
        if (has < 2 * k) {
            break;
        }
        ans += 2;
        let got = 0;
        for (let i = 0; got < k && i < 26; i++) {
            while (got < k && cnt[i] >= 2) {
                cnt[i] -= 2;
                got++;
            }
        }
        check(got == k);
    }
    while (true) {
        let has = 0;
        for (let i = 0; i < 26; i++) {
            if (cnt[i] > 0) {
                has += cnt[i];
            }
        }
        if (has < k) {
            break;
        }
        ans++;
        break;
    }
    return ans;
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        n = nextInt();
        k = nextInt();
        s = nextStr();
        printf("%d\n", solve());
    }
}

/* Common Template Starts */
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++];
}
/* Common Template Ends */

palindromeColoring = (s, k)=>{

    let map = new Map();
    for(let el of s){
        if(map.has(el)){
            map.set(el, map.get(el)+1)
        }
        else{
            map.set(el, 1);
        }
    }

    let values = Array.from(map.values());

    let totalPairs = 0;
    for(let i =0; i<values.length; ++i){
        totalPairs+= Math.floor(values[i]/2);
    }
    if(totalPairs < k){
        console.log(1);
        return;
    }

    let perBucket = Math.floor(totalPairs/k);
    let remainingChars = (s.length - totalPairs*2) + (totalPairs - perBucket*k)*2;
    // console.log(perBucket, remainingChars)
    if(remainingChars >=k){
        console.log(perBucket*2 + 1);
    }
    else{
        console.log(perBucket*2)
    }

}

function main() {
    //take input according to the format;
    const t = +(readline());
    for(let i =0; i<t; ++i){

        const [sLen, k] = readline().split(' ').map(el=>parseInt(el));

        const s = readline();

        palindromeColoring(s,k);
    }
}

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, k] = rna();
		const s = rl();

		const fq = new Map();
		for (const c of s) {
			fq.set(c, fq.has(c) ? fq.get(c) + 1 : 1);
		}

		let pairs = 0;
		for (const cnt of fq.values()) {
			pairs += Math.floor(cnt/2);
		}

		let ans = Math.floor(pairs/k)*2;
		ans += n - ans*k >= k;

		console.log(ans);
	}
}

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

function solve(n, k, str) {
    const count = Array(26).fill(0)
    for (let i = 0; i < str.length; i++) {
        const idx = str.charCodeAt(i) - 'a'.charCodeAt(0)
        count[idx]++
    }
    let odd = 0
    let even = 0
    for (let i = 0; i < count.length; i++) {
        if (count[i] & 1) {
            even += count[i] - 1
            odd++
        } else {
            even += count[i]
        }
    }
    return binarySearch(1, Math.floor(n / k), x => {
        if (x & 1) {
            return even >= (x - 1) * k
        } else {
            return even >= x * k
        }
    })
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => {
        let next;
        do {
            next = (await getLineGen.next());
        } while (!next.done && next.value === '');
        return next.value;
    };
})();

const readInt = async function(){
    return parseInt(await getLine());
}

const readIntArray = async function() {
    return (await getLine()).split(' ').map(num => parseInt(num));
}

let solve = async () => {
    const tsc = await readInt();
    for(let sc = 0; sc < tsc; sc++) {
        const [n,k] = await readIntArray();
        const a = (await getLine()).split('').map(c => c.charCodeAt(0));
        a.sort((a,b) => (a - b));
        let ones = 0;
        let pairs = 0;
        let i,j;

        for(i = 0; i < a.length; i=j) {
           for(j = i+1; j<a.length && a[j]===a[i]; j++);
           pairs += Math.floor((j-i)/2);
           ones += (j-i)%2;

        }

        let res = Math.floor(pairs/k) * 2;
        if ((pairs%k) * 2 + ones >= k) {
            res++;
        }
        console.log(res);

    }
}

solve();

var t = parseInt(readline());

  function solve() {
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var n = inp[0];
    var k = inp[1];
    var s = readline();

    var mp = {};

    for (var i = 0; i < n; i++) {
      if (mp.hasOwnProperty(s[i])) {
        mp[s[i]]++;
      } else {
        mp[s[i]] = 1;
      }
    }
    var p = 0,
      ind = 0;

    for (var i in mp) {
      var x = mp[i];
      p += Math.floor(x / 2);
      ind += x % 2;
    }
    var ans = Math.floor(p / k);
    ind += (p % k) * 2;
    ans *= 2;
    if (ind >= k) ans++;

    return ans;
  }

  while (t--) {
    print(solve());
  }

/*
===== READ INPUT DATA START =====
=================================
*/

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

let inputString = '';

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

process.stdin.on('end', (_) => {
  const lines = inputString.trim().split('\n').map((string) => string.trim()).filter(Boolean);
  main(lines);
});

/*
===== READ INPUT DATA END =====
===============================
*/

function main(lines) {
  let index = 0;
  let T = Number(lines[index++]);
  let N;
  let K;
  let str;

  while (T--) {
    [N, K] = lines[index++].split(' ').map(Number);
    str = lines[index++];

    solve(N, K, str);
  }
}

function solve(N, K, str) {
  const map = new Map();
  let evenCount = 0;
  let oddCount = 0;
  let value;
  let result;

  for (const char of str) {
    value = map.get(char) || 0;
    map.set(char, value + 1);
  }

  Array.from(map.values()).forEach((val) => {
    if (val % 2 === 0) {
      evenCount += val;
    } else {
      evenCount += val - 1;
      oddCount++;
    }
  });

  result = Math.floor(evenCount / K);

  if (oddCount >= K && result % 2 === 0) {
    result++;
  }

  console.log(Math.max(result, 1));
}

/*
===== READ INPUT DATA START =====
=================================
*/

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

let inputString = '';

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

process.stdin.on('end', (_) => {
  const lines = inputString.trim().split('\n').map((string) => string.trim()).filter(Boolean);
  main(lines);
});

/*
===== READ INPUT DATA END =====
===============================
*/

function main(lines) {
  let index = 0;
  let T = Number(lines[index++]);
  let N;
  let K;
  let str;

  while (T--) {
    [N, K] = lines[index++].split(' ').map(Number);
    str = lines[index++];

    solve(N, K, str);
  }
}

function solve(N, K, str) {
  const map = new Map();
  let evenCount = 0;
  let oddCount = 0;
  let value;
  let result;

  for (const char of str) {
    value = map.get(char) || 0;
    map.set(char, value + 1);
  }

  Array.from(map.values()).forEach((val) => {
    if (val % 2 === 0) {
      evenCount += val;
    } else {
      oddCount += val;
    }
  });

  result = Math.floor(evenCount / K);

  if (oddCount >= K && result % 2 === 0) {
    result++;
  }

  console.log(Math.max(result, 1));
}


Masha meets a new friend and learns his phone number — $$$s$$$. She wants to remember it as soon as possible. The phone number — is a string of length $$$m$$$ that consists of digits from $$$0$$$ to $$$9$$$. The phone number may start with 0.Masha already knows $$$n$$$ phone numbers (all numbers have the same length $$$m$$$). It will be easier for her to remember a new number if the $$$s$$$ is represented as segments of numbers she already knows. Each such segment must be of length at least $$$2$$$, otherwise there will be too many segments and Masha will get confused.For example, Masha needs to remember the number: $$$s = $$$ '12345678' and she already knows $$$n = 4$$$ numbers: '12340219', '20215601', '56782022', '12300678'. You can represent $$$s$$$ as a $$$3$$$ segment: '1234' of number one, '56' of number two, and '78' of number three. There are other ways to represent $$$s$$$.Masha asks you for help, she asks you to break the string $$$s$$$ into segments of length $$$2$$$ or more of the numbers she already knows. If there are several possible answers, print any of them.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases. Before each test case there is a blank line. Then there is a line containing integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^3$$$) —the number of phone numbers that Masha knows and the number of digits in each phone number. Then follow $$$n$$$ line, $$$i$$$-th of which describes the $$$i$$$-th number that Masha knows. The next line contains the phone number of her new friend $$$s$$$. Among the given $$$n+1$$$ phones, there may be duplicates (identical phones). It is guaranteed that the sum of $$$n \cdot m$$$ ($$$n$$$ multiplied by $$$m$$$) values over all input test cases does not exceed $$$10^6$$$.

You need to print the answers to $$$t$$$ test cases. The first line of the answer should contain one number $$$k$$$, corresponding to the number of segments into which you split the phone number $$$s$$$. Print -1 if you cannot get such a split. If the answer is yes, then follow $$$k$$$ lines containing triples of numbers $$$l, r, i$$$. Such triplets mean that the next $$$r-l+1$$$ digits of number $$$s$$$ are equal to a segment (substring) with boundaries $$$[l, r]$$$ of the phone under number $$$i$$$. Both the phones and the digits in them are numbered from $$$1$$$. Note that $$$r-l+1 \ge 2$$$ for all $$$k$$$ lines.

NoteThe example from the statement.In the second case, it is impossible to represent by segments of known numbers of length 2 or more.In the third case, you can get the segments '12' and '21' from the first phone number.

/*
===== READ INPUT DATA START =====
=================================
*/

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

let inputString = '';

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

process.stdin.on('end', (_) => {
  const lines = inputString.trim().split('\n').map((string) => string.trim()).filter(Boolean);
  main(lines);
});

/*
===== READ INPUT DATA END =====
===============================
*/

function main(lines) {
  let index = 0;
  let T = Number(lines[index++]);
  let N, M;
  let arr, str;

  while (T--) {
    [N, M] = lines[index++].split(' ').map(Number);
    arr = new Array(N);

    for (let i = 0; i < N; ++i) {
      arr[i] = lines[index++];
    }

    str = lines[index++];

    solve(N, M, arr, str);
  }
}

function solve(N, M, arr, str) {
  const map = new Map();
  const darr = new Array(M + 1).fill('');
  const solution = [];
  let index;
  let curStr;
  let strLength2;
  let strLength3;

  // base set with sequences of length 2 and 3
  for (let i = 0; i < N; ++i) {
    for (let j = 0; j < M; ++j) {
      strLength2 = arr[i][j] + arr[i][j + 1];
      strLength3 = strLength2 + arr[i][j + 2];

      if (strLength2.length === 2) {
        map.set(strLength2, [j + 1, j + 2, i + 1]);
      }

      if (strLength3.length === 3) {
        map.set(strLength3, [j + 1, j + 3, i + 1]);
      }
    }
  }

  curStr = '';

  for (let i = 1; i <= M; ++i) {
    curStr += str[i - 1];
    strLength2 = str[i - 2] + str[i - 1];
    strLength3 = str[i - 3] + strLength2;

    strLength2 = (map.has(strLength2) && strLength2) || '';
    strLength3 = (map.has(strLength3) && strLength3) || '';

    if (darr[i - 2] + strLength2 === curStr || darr[i - 3] + strLength3 === curStr) {
      darr[i] = curStr;
    }
  }

  if (!darr[M]) {
    console.log('-1');
    return;
  }

  index = M;

  while (index > 0) {
    strLength2 = str[index - 2] + str[index - 1];
    strLength3 = str[index - 3] + strLength2;

    if ((darr[index - 3] || darr[index] === strLength3) && map.has(strLength3)) {
      solution.push(map.get(strLength3));
      index -= 3;
    } else {
      solution.push(map.get(strLength2));
      index -= 2;
    }
  }

  solution.reverse();

  console.log(solution.length);
  for (let i = 0; i < solution.length; ++i) {
    console.log(solution[i].join(' '));
  }
}

/* Common Template Starts */
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++];
}
/* Common Template Ends */

let map = null;
let s = null;
let arr = null;
let solution = []
function main() {
    const mashaForgetul = (i)=>{
        if(i >= s.length){
            return true;
        }
        if(arr[i]!= -1) return arr[i];
        let s1 = s.substring(i, i+2);
        let s2 = s.substring(i, i+3);

        let c1 = map.has(s1) && mashaForgetul(i+2);
        let c2 = false;
        if(!c1 )
            c2 = map.has(s2) && mashaForgetul(i+3);

        if(c2 ){
            let val = map.get(s2);
            solution.push([...val])
        }
        else{
            if(c1){
                let val = map.get(s1);
                solution.push([...val])
            }
        }
        arr[i] = c1||c2;

        return c1 || c2;
    }
    //take input according to the format;
    const t = +(readline());
    readline();
    for(let i =0; i<t; ++i){
        map = new Map()
        solution = [];
        const n = readline().split(' ')[0];

        for(let j =0; j< n; ++j){
            const ns = readline();

            for(let k=0; k<ns.length; ++k){
                k+2 <= ns.length && map.set(ns.substring(k, k+2), [k+1, k+2, j+1] );
                k+3 <= ns.length && map.set(ns.substring(k, k+3), [k+1, k+3, j+1] );
            }
        }
        s = readline();

        arr = new Array(s.length).fill(-1);
        mashaForgetul(0);
        if(arr[0]=== true){
            solution = solution.reverse();
            console.log(solution.length)
            for(let j = 0; j< solution.length; ++j){
                console.log(...solution[j]);
            }
        }
        else{
            console.log(-1)
        }
        readline();

    }
}

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, m] = lines[l++].trim().split(' ').map(Number)
        const arr = lines.slice(l, l + n).map(str => str.trim())
        l += n
        const str = lines[l++]
        output[i] = solve(n, m, arr, str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, m, arr, str) {
    const map = {}
    arr.forEach((s, j) => {
        for (let i = 0; i < s.length; i++) {
            if (i + 1 < s.length) {
                const x = s.slice(i, i + 1 + 1)
                map[x] = [i + 1, i + 2, j + 1]
            }
            if (i + 2 < s.length) {
                const x = s.slice(i, i + 2 + 1)
                map[x] = [i + 1, i + 3, j + 1]
            }
        }
    })
    const dp = []
    dp[0] = []
    dp[1] = null
    for (let i = 2; i <= str.length; i++) {
        const a1 = dp[i - 2]
        const a2 = map[str.slice(i - 2, i)]
        if (a1 && a2) {
            dp[i] = 2
            continue
        }
        const b1 = i - 3 >= 0 ? dp[i - 3] : null
        const b2 = map[str.slice(i - 3, i)]
        if (b1 && b2) {
            dp[i] = 3
            continue
        }
        dp[i] = null
    }
    // console.log(dp)
    if (!dp[m]) return -1
    let x = m
    const ans = []
    dp[0] = null // tricky
    while (dp[x]) {
        // console.log(x)
        ans.unshift(map[str.slice(x - dp[x], x)])
        x -= dp[x]
    }
    return ans.length + '\n' + ans.map(r => r.join(' ')).join('\n')
}

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--) {
		rl();
		const [n, m] = rna();
		const known = [];
		for (let i = 0; i < n; i++) {
			known[i] = rl();
		}
		const s = rl();

		const avl = new Map();
		for (let i = 0; i < n; i++) {
			const ph = known[i];
			for (let j = 0; j < m; j++) {
				j+2 <= m && avl.set(ph.substr(j, 2), [j+1, j+2, i+1]);
				j+3 <= m && avl.set(ph.substr(j, 3), [j+1, j+3, i+1]);
			}
		}

		const dp = Array(n);
		dp[-1] = dp[-2] = true;
		for (let i = 1; i < m; i++) {
			const sx2 = s.substr(i-1, 2);
			const sx3 = s.substr(i-2, 3);

			if (dp[i-2] && avl.has(sx2)) {
				dp[i] = 2;
			} else if (dp[i-3] && avl.has(sx3)) {
				dp[i] = 3;
			}
		}

		if (dp[m-1]) {
			const ans = [];
			let i = m - 1;
			while (i >= 0) {
				const sx = s.substr(i-dp[i]+1, dp[i]);
				ans.push(avl.get(sx));
				i -= dp[i];
			}
			ans.reverse();

			console.log(ans.length);
			for (const ln of ans) {
				console.log(ln.join(' '));
			}
		} else {
			console.log(-1);
		}
	}
}

/*
===== READ INPUT DATA START =====
=================================
*/

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

let inputString = '';

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

process.stdin.on('end', (_) => {
  const lines = inputString.trim().split('\n').map((string) => string.trim()).filter(Boolean);
  main(lines);
});

/*
===== READ INPUT DATA END =====
===============================
*/

function main(lines) {
  let index = 0;
  let T = Number(lines[index++]);
  let N, M;
  let arr, str;

  while (T--) {
    [N, M] = lines[index++].split(' ').map(Number);
    arr = new Array(N);

    for (let i = 0; i < N; ++i) {
      arr[i] = lines[index++];
    }

    str = lines[index++];

    solve(N, M, arr, str);
  }
}

function solve(N, M, arr, str) {
  const map = new Array(1000);
  const darr = new Array(M + 1).fill('');
  const solution = [];
  let index;
  let curStr;
  let strLength2;
  let strLength3;

  // base set with sequences of length 2 and 3
  for (let i = 0; i < N; ++i) {
    for (let j = 0; j < M; ++j) {
      strLength2 = arr[i][j] + arr[i][j + 1];
      strLength3 = strLength2 + arr[i][j + 2];

      if (strLength2.length === 2) {
        map[Number(strLength2)] = [j + 1, j + 2, i + 1];
      }

      if (strLength3.length === 3) {
        map[Number(strLength3)] = [j + 1, j + 3, i + 1];
      }
    }
  }

  curStr = '';

  for (let i = 1; i <= M; ++i) {
    curStr += str[i - 1];
    strLength2 = str[i - 2] + str[i - 1];
    strLength3 = str[i - 3] + strLength2;

    strLength2 = (map[Number(strLength2)] && strLength2) || '';
    strLength3 = (map[Number(strLength3)] && strLength3) || '';

    if (darr[i - 2] + strLength2 === curStr || darr[i - 3] + strLength3 === curStr) {
      darr[i] = curStr;
    }
  }

  if (!darr[M]) {
    console.log('-1');
    return;
  }

  index = M;

  while (index > 0) {
    strLength2 = str[index - 2] + str[index - 1];
    strLength3 = str[index - 3] + strLength2;

    if ((darr[index - 3] || darr[index] === strLength3) && map[Number(strLength3)]) {
      solution.push(map[Number(strLength3)]);
      index -= 3;
    } else {
      solution.push(map[Number(strLength2)]);
      index -= 2;
    }
  }

  solution.reverse();

  console.log(solution.length);

  for (let i = 0; i < solution.length; ++i) {
    console.log(solution[i].join(' '));
  }
}

/*
===== READ INPUT DATA START =====
=================================
*/

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

let inputString = '';

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

process.stdin.on('end', (_) => {
  const lines = inputString.trim().split('\n').map((string) => string.trim()).filter(Boolean);
  main(lines);
});

/*
===== READ INPUT DATA END =====
===============================
*/

function main(lines) {
  let index = 0;
  let T = Number(lines[index++]);
  let N, M;
  let arr, str;

  while (T--) {
    [N, M] = lines[index++].split(' ').map(Number);
    arr = new Array(N);

    for (let i = 0; i < N; ++i) {
      arr[i] = lines[index++];
    }

    str = lines[index++];

    solve(N, M, arr, str);
  }
}

function solve(N, M, arr, str) {
  const map = new Array(1000);
  const darr = new Array(M + 1).fill('');
  const solution = [];
  let index;
  let curStr;
  let strLength2;
  let strLength3;

  // base set with sequences of length 2 and 3
  for (let i = 0; i < N; ++i) {
    for (let j = 0; j < M; ++j) {
      strLength2 = arr[i][j] + arr[i][j + 1];
      strLength3 = strLength2 + arr[i][j + 2];

      if (strLength2.length === 2) {
        map[Number(strLength2)] = [j + 1, j + 2, i + 1];
      }

      if (strLength3.length === 3) {
        map[Number(strLength3)] = [j + 1, j + 2, i + 1];
      }
    }
  }

  curStr = '';

  for (let i = 1; i <= M; ++i) {
    curStr += str[i - 1];
    strLength2 = str[i - 2] + str[i - 1];
    strLength3 = str[i - 3] + strLength2;

    strLength2 = (map[Number(strLength2)] && strLength2) || '';
    strLength3 = (map[Number(strLength3)] && strLength3) || '';

    if (darr[i - 2] + strLength2 === curStr || darr[i - 3] + strLength3 === curStr) {
      darr[i] = curStr;
    }
  }

  if (!darr[M]) {
    console.log('-1');
    return;
  }

  index = M;

  while (index > 0) {
    strLength2 = str[index - 2] + str[index - 1];
    strLength3 = str[index - 3] + strLength2;

    if ((darr[index - 3] || darr[index] === strLength3) && map[Number(strLength3)]) {
      solution.push(map[Number(strLength3)]);
      index -= 3;
    } else {
      solution.push(map[Number(strLength2)]);
      index -= 2;
    }
  }

  solution.reverse();

  console.log(solution.length);

  for (let i = 0; i < solution.length; ++i) {
    console.log(solution[i].join(' '));
  }
}

/* Common Template Starts */
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++];
}
/* Common Template Ends */

let map = null;
let s = null;
let arr = null;
let solution = []
function main() {
    const mashaForgetul = (i)=>{
        if(i >= s.length){
            return true;
        }
        if(arr[i]!= -1) return arr[i];
        let s1 = s.substring(i, i+2);
        let s2 = s.substring(i, i+3);

        let c1 = map.has(s1) && mashaForgetul(i+2);
        let c2 = map.has(s2) && mashaForgetul(i+3);

        if(c2 ){
            let val = map.get(s2);
            solution.push([...val])
        }
        else{
            if(c1){
                let val = map.get(s1);
                solution.push([...val])
            }
        }
        arr[i] = c1||c2;

        return c1 || c2;
    }
    //take input according to the format;
    const t = +(readline());
    readline();
    for(let i =0; i<t; ++i){
        map = new Map()
        solution = [];
        const n = readline().split(' ')[0];

        for(let j =0; j< n; ++j){
            const ns = readline();

            for(let k=0; k<ns.length; ++k){
                k+2 <= ns.length && map.set(ns.substring(k, k+2), [k+1, k+2, j+1] );
                k+3 <= ns.length && map.set(ns.substring(k, k+3), [k+1, k+3, j+1] );
            }
        }
        s = readline();

        arr = new Array(s.length).fill(-1)
        mashaForgetul(0);
        if(arr[0]=== true){
            solution = solution.reverse();
            console.log(solution.length)
            for(let j = 0; j< solution.length; ++j){
                console.log(...solution[j]);
            }
        }
        else{
            console.log(-1)
        }
        readline();

    }
}

/* Common Template Starts */
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++];
}
/* Common Template Ends */

let map = null;
let s = null;
let arr = null;
let solution = []
function main() {
    const mashaForgetul = (i)=>{
        if(i >= s.length){
            return true;
        }
        if(arr[i]!= -1) return arr[i];
        let s1 = s.substring(i, i+2);
        let s2 = s.substring(i, i+3);

        let c1 = map.has(s1) && mashaForgetul(i+2);
        let c2 = map.has(s2) && mashaForgetul(i+3);

        if(c2 ){
            let val = map.get(s2);
            solution.push([...val])
        }
        else{
            if(c1){
                let val = map.get(s1);
                solution.push([...val])
            }
        }
        arr[i] = c1||c2;

        return c1 || c2;
    }
    //take input according to the format;
    const t = +(readline());
    readline();
    for(let i =0; i<t; ++i){
        map = new Map()
        solution = [];
        const n = readline().split(' ')[0];

        for(let j =0; j< n; ++j){
            const ns = readline();

            for(let k=0; k<ns.length; ++k){
                k+2 < ns.length && map.set(ns.substring(k, k+2), [k+1, k+2, j+1] );
                k+3 < ns.length && map.set(ns.substring(k, k+3), [k+1, k+3, j+1] );
            }
        }
        s = readline();

        arr = new Array(s.length).fill(-1)
        mashaForgetul(0);
        if(arr[0]=== true){
            solution = solution.reverse();
            console.log(solution.length)
            for(let j = 0; j< solution.length; ++j){
                console.log(...solution[j]);
            }
        }
        else{
            console.log(-1)
        }
        readline();

    }
}

/* Common Template Starts */
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++];
}
/* Common Template Ends */

let map = null;
let s = null;
let arr = null;
let solution = []
function main() {
    const mashaForgetul = (i)=>{
        if(i >= s.length){
            return true;
        }
        if(arr[i]!= -1) return arr[i];
        let s1 = s.substring(i, i+2);
        let s2 = s.substring(i, i+3);

        let c1 = map.has(s1) && mashaForgetul(i+2);
        let c2 = map.has(s2) && mashaForgetul(i+3);

        if(c2 ){
            let val = map.get(s2);
            solution.push([...val])
        }
        else{
            if(c1){
                let val = map.get(s1);
                solution.push([...val])
            }
        }
        arr[i] = c1||c2;

        return c1 || c2;
    }
    //take input according to the format;
    const t = +(readline());
    readline();
    for(let i =0; i<t; ++i){
        map = new Map()
        solution = [];
        const n = readline().split(' ')[0];

        for(let j =0; j< n; ++j){
            const ns = readline();

            for(let k=0; k<ns.length; ++k){
                k+2 < ns.length && map.set(ns.substring(k, k+2), [k+1, k+2, j+1] );
                k+3 < ns.length && map.set(ns.substring(k, k+3), [k+1, k+3, j+1] );
            }
        }
        s = readline();

        arr = new Array(s.length).fill(-1)
        mashaForgetul(0);
        if(arr[0]){
            solution = solution.reverse();
            console.log(solution.length)
            for(let j = 0; j< solution.length; ++j){
                console.log(...solution[j]);
            }
        }
        else{
            console.log(-1)
        }
        readline();

    }
}

/* Common Template Starts */
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++];
}
/* Common Template Ends */

let map = null;
let s = null;
let arr = null;
let solution = []
function main() {
    const mashaForgetul = (i)=>{
        if(i >= s.length){
            return true;
        }
        if(arr[i]!= -1) return arr[i];
        let s1 = s.substring(i, i+2);
        let s2 = s.substring(i, i+3);

        let c1 = map.has(s1) && mashaForgetul(i+2);
        let c2 = map.has(s2) && mashaForgetul(i+3);

        if(c2 ){
            let val = map.get(s2);
            solution.push([...val])
        }
        else{
            if(c1){
                let val = map.get(s1);
                solution.push([...val])
            }
        }
        arr[i] = c1||c2;

        return c1 || c2;
    }
    //take input according to the format;
    const t = +(readline());
    readline();
    for(let i =0; i<t; ++i){
        map = new Map()
        solution = [];
        const n = readline().split(' ')[0];

        for(let j =0; j< n; ++j){
            const ns = readline();

            for(let k=0; k<ns.length; ++k){
                k+2 < ns.length && map.set(ns.substring(k, k+2), [k+1, k+2, j+1] );
                k+3 < ns.length && map.set(ns.substring(k, k+3), [k+1, k+3, j+1] );
            }
        }
        s = readline();

        arr = new Array(s.length).fill(-1)
        mashaForgetul(0);
        if(arr[0]){
            solution = solution.reverse().sort((a,b)=> a[2] - b[2]);
            console.log(solution.length)
            for(let j = 0; j< solution.length; ++j){
                console.log(...solution[j]);
            }
        }
        else{
            console.log(-1)
        }
        readline();

    }
}

/* Common Template Starts */
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++];
}
/* Common Template Ends */

let map = null;
let s = null;
let arr = null;
let solution = []
function main() {
    const mashaForgetul = (i)=>{
        if(i >= s.length){
            return true;
        }
        if(arr[i]!= -1) return arr[i];
        let s1 = s.substring(i, i+2);
        let s2 = s.substring(i, i+3);

        let c1 = map.has(s1) && mashaForgetul(i+2);
        let c2 = map.has(s2) && mashaForgetul(i+3);

        if(c2 ){
            let val = map.get(s2);
            solution.push([...val])
        }
        else{
            if(c1){
                let val = map.get(s1);
                solution.push([...val])
            }
        }
        arr[i] = c1||c2;

        return c1 || c2;
    }
    //take input according to the format;
    const t = +(readline());
    readline();
    for(let i =0; i<t; ++i){
        map = new Map()
        solution = [];
        const n = readline().split(' ')[0];

        for(let j =0; j< n; ++j){
            const ns = readline();

            for(let k=0; k<ns.length; ++k){
                k+2 < ns.length && map.set(ns.substring(k, k+2), [k+1, k+2, j+1] );
                k+3 < ns.length && map.set(ns.substring(k, k+3), [k+1, k+3, j+1] );
            }
        }
        s = readline();

        arr = new Array(s.length).fill(-1)
        mashaForgetul(0);
        if(arr[0]){
            solution = solution.reverse().sort((a,b)=> a[2] - b[2]);
            console.log(solution.length)
            for(let j = 0; j< solution.length; ++j){
                console.log(solution[j]);
            }
        }
        else{
            console.log(-1)
        }
        readline();

    }
}

/* Common Template Starts */
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++];
}
/* Common Template Ends */

let map = null;
let s = null;
let arr = null;
let solution = []
function main() {
    const mashaForgetul = (i)=>{
        if(i >= s.length){
            return true;
        }
        if(arr[i]!= -1) return arr[i];
        let s1 = s.substring(i, i+2);
        let s2 = s.substring(i, i+3);

        let c1 = map.has(s1) && mashaForgetul(i+2);
        let c2 = map.has(s2) && mashaForgetul(i+3);

        if(c2 ){
            let val = map.get(s2);
            solution.push([...val])
        }
        else{
            if(c1){
                let val = map.get(s1);
                solution.push([...val])
            }
        }
        arr[i] = c1||c2;

        return c1 || c2;
    }
    //take input according to the format;
    const t = +(readline());
    readline();
    for(let i =0; i<t; ++i){
        map = new Map()
        solution = [];
        const n = readline().split(' ')[0];

        for(let j =0; j< n; ++j){
            const ns = readline();

            for(let k=0; k<ns.length; ++k){
                k+2 < ns.length && map.set(ns.substring(k, k+2), [k+1, k+2, j+1] );
                k+3 < ns.length && map.set(ns.substring(k, k+3), [k+1, k+3, j+1] );
            }
        }
        s = readline();

        arr = new Array(s.length).fill(-1)
        mashaForgetul(0);
        if(arr[0]){
            solution = solution.reverse();
            console.log(solution.length)
            for(let j = 0; j< solution.length; ++j){
                console.log(solution[j]);
            }
        }
        else{
            console.log(-1)
        }
        readline();

    }
}

/* Common Template Starts */
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++];
}
/* Common Template Ends */

let map = null;
let s = null;
let arr = null;
let solution = []
function main() {
    const mashaForgetul = (i)=>{
        if(i >= s.length){
            return true;
        }
        if(arr[i]!= -1) return arr[i];
        let s1 = s.substring(i, i+2);
        let s2 = s.substring(i, i+3);

        let c1 = map.has(s1) && mashaForgetul(i+2);
        let c2 = map.has(s2) && mashaForgetul(i+3);

        if(c2 ){
            let val = map.get(s2);
            solution.push([...val])
        }
        else{
            if(c1){
                let val = map.get(s1);
                solution.push([...val])
            }
        }
        arr[i] = c1||c2;

        return c1 || c2;
    }
    //take input according to the format;
    const t = +(readline());
    readline();
    for(let i =0; i<t; ++i){
        map = new Map()
        solution = [];
        const n = readline().split(' ')[0];

        for(let j =0; j< n; ++j){
            const ns = readline();

            for(let k=0; k<ns.length; ++k){
                k+2 < ns.length && map.set(ns.substring(k, k+2), [k+1, k+2, j+1] );
                k+3 < ns.length && map.set(ns.substring(k, k+3), [k+2, k+3, j+1] );
            }
        }
        s = readline();

        arr = new Array(s.length).fill(-1)
        mashaForgetul(0);
        if(arr[0]){
            solution = solution.reverse();
            console.log(solution.length)
            for(let j = 0; j< solution.length; ++j){
                console.log(solution[j]);
            }
        }
        else{
            console.log(-1)
        }
        readline();

    }
}


Consider a table of size $$$n \times m$$$, initially fully white. Rows are numbered $$$1$$$ through $$$n$$$ from top to bottom, columns $$$1$$$ through $$$m$$$ from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 115$$$) — the number of rows and the number of columns in the table. The $$$i$$$-th of the next $$$n$$$ lines contains a string of $$$m$$$ characters $$$s_{i1} s_{i2} \ldots s_{im}$$$ ($$$s_{ij}$$$ is 'W' for white cells and 'B' for black cells), describing the $$$i$$$-th row of the table.

Output two integers $$$r$$$ and $$$c$$$ ($$$1 \le r \le n$$$, $$$1 \le c \le m$$$) separated by a space — the row and column numbers of the center of the black square.

//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 one = nextIntArray();
	var H = one[0];
	var W = one[1];
	var list = new Array(H);
	for(var i = 0; i < H; i++){
		list[i] = nextCharArray();
	}
	for(var i = 0; i < H; i++){
		for(var j = 0; j < W; j++){
			if(list[i][j] == "B"){
				var add = -1;
				for(var k = 0; k < Math.min(H, W); k++){
					try{
						if(list[i + k][j + k] == "B"){
							add++;
						}else{
							break;
						}
					}catch(e){
						break;
					}

				}
				add = Math.ceil(add / 2);
				myout((i + 1 + add) + " " + (j + 1 + add));
				return;
			}
		}
	}
}

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    [n, m] = d.split(' ').map(Number);
    return;
  }

  matrix.push(d.split(''));

  c++;
});

rl.on('close', () => {
  const idxTop = [];
  const idxBottom = [];

  isDone:
  for (let i = 0; i < matrix.length; i++) {
    for (let j = 0; j < matrix[i].length; j++) {
      if (matrix[i][j] === 'B') {
        idxTop.push(i + 1, j + 1);
        break isDone;
      }
    }
  }

  isDone:
  for (let i = matrix.length - 1; i >= 0; i--) {
    for (let j = matrix[i].length - 1; j >= 0; j--) {
      if (matrix[i][j] === 'B') {
        idxBottom.push(i + 1, j + 1);
        break isDone;
      }
    }
  }

  const y = (idxTop[0] + idxBottom[0]) / 2;
  const x = (idxTop[1] + idxBottom[1]) / 2;

  console.log(y, x);

  // let width = 1;
  // let height = 1;
  // let x, y;

  // for (let i = 0; i < matrix.length; i++) {
  //   for (let j = 0; j < matrix[i].length; j++) {
  //     if (matrix[i][j] === 'B') {
  //       x = j;
  //       y = i;

  //       while (matrix[i] && matrix[i][j] === 'B') {
  //         if (matrix[i][j + 1] === 'B') {
  //           width++;
  //           j++;
  //         }
  //         else if (matrix[i + 1] && matrix[i + 1][j] === 'B') {
  //           height++;
  //           i++;
  //         }
  //         else {
  //           j++;
  //           i++;
  //         }
  //       }

  //       break;
  //     }
  //   }
  // }

  // console.log(y + 1 + Math.floor(height / 2), x + 1 + Math.floor(width / 2));
});

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    [n, m] = d.split(' ').map(Number);
    return;
  }

  matrix.push(d.split(''));

  c++;
});

rl.on('close', () => {
  let x = 0;
  let y = 0;
  let cnt = 0;

  for (let i = 0; i < matrix.length; i++) {
    for (let j = 0; j < matrix[i].length; j++) {
      if (matrix[i][j] === 'B') {
        x += j;
        y += i;
        cnt++;
      }
    }
  }

  console.log(y / cnt + 1, x / cnt + 1);

  // let minX = Infinity;
  // let maxX = -Infinity;
  // let minY = Infinity;
  // let maxY = -Infinity;

  // for (let i = 0; i < matrix.length; i++) {
  //   for (let j = 0; j < matrix[i].length; j++) {
  //     if (matrix[i][j] === 'B') {
  //       minX = Math.min(minX, j);
  //       maxX = Math.max(maxX, j);
  //       minY = Math.min(minY, i);
  //       maxY = Math.max(maxY, i);
  //     }
  //   }
  // }

  // console.log((minY + maxY) / 2 + 1, (minX + maxX) / 2 + 1);
  ////////////////////////////////////////////

  // const idxTop = [];
  // const idxBottom = [];

  // isDone: {
  //   for (let i = 0; i < matrix.length; i++) {
  //     for (let j = 0; j < matrix[i].length; j++) {
  //       if (matrix[i][j] === 'B') {
  //         idxTop.push(i + 1, j + 1);
  //         break isDone;
  //       }
  //     }
  //   }
  // }

  // isDone: {
  //   for (let i = matrix.length - 1; i >= 0; i--) {
  //     for (let j = matrix[i].length - 1; j >= 0; j--) {
  //       if (matrix[i][j] === 'B') {
  //         idxBottom.push(i + 1, j + 1);
  //         break isDone;
  //       }
  //     }
  //   }
  // }

  // const y = (idxTop[0] + idxBottom[0]) / 2;
  // const x = (idxTop[1] + idxBottom[1]) / 2;

  // console.log(y, x);
  //////////////////////////////////////

  // let width = 1;
  // let height = 1;
  // let x, y;

  // for (let i = 0; i < matrix.length; i++) {
  //   for (let j = 0; j < matrix[i].length; j++) {
  //     if (matrix[i][j] === 'B') {
  //       x = j;
  //       y = i;

  //       while (matrix[i] && matrix[i][j] === 'B') {
  //         if (matrix[i][j + 1] === 'B') {
  //           width++;
  //           j++;
  //         }
  //         else if (matrix[i + 1] && matrix[i + 1][j] === 'B') {
  //           height++;
  //           i++;
  //         }
  //         else {
  //           j++;
  //           i++;
  //         }
  //       }

  //       break;
  //     }
  //   }
  // }

  // console.log(y + 1 + Math.floor(height / 2), x + 1 + Math.floor(width / 2));
});

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    [n, m] = d.split(' ').map(Number);
    return;
  }

  matrix.push(d.split(''));

  c++;
});

rl.on('close', () => {
  let minX = Infinity;
  let maxX = -Infinity;
  let minY = Infinity;
  let maxY = -Infinity;

  for (let i = 0; i < matrix.length; i++) {
    for (let j = 0; j < matrix[i].length; j++) {
      if (matrix[i][j] === 'B') {
        minX = Math.min(minX, j);
        maxX = Math.max(maxX, j);
        minY = Math.min(minY, i);
        maxY = Math.max(maxY, i);
      }
    }
  }

  console.log((minY + maxY) / 2 + 1, (minX + maxX) / 2 + 1);

  // const idxTop = [];
  // const idxBottom = [];

  // isDone: {
  //   for (let i = 0; i < matrix.length; i++) {
  //     for (let j = 0; j < matrix[i].length; j++) {
  //       if (matrix[i][j] === 'B') {
  //         idxTop.push(i + 1, j + 1);
  //         break isDone;
  //       }
  //     }
  //   }
  // }

  // isDone: {
  //   for (let i = matrix.length - 1; i >= 0; i--) {
  //     for (let j = matrix[i].length - 1; j >= 0; j--) {
  //       if (matrix[i][j] === 'B') {
  //         idxBottom.push(i + 1, j + 1);
  //         break isDone;
  //       }
  //     }
  //   }
  // }

  // const y = (idxTop[0] + idxBottom[0]) / 2;
  // const x = (idxTop[1] + idxBottom[1]) / 2;

  // console.log(y, x);
  //////////////////////////////////////

  // let width = 1;
  // let height = 1;
  // let x, y;

  // for (let i = 0; i < matrix.length; i++) {
  //   for (let j = 0; j < matrix[i].length; j++) {
  //     if (matrix[i][j] === 'B') {
  //       x = j;
  //       y = i;

  //       while (matrix[i] && matrix[i][j] === 'B') {
  //         if (matrix[i][j + 1] === 'B') {
  //           width++;
  //           j++;
  //         }
  //         else if (matrix[i + 1] && matrix[i + 1][j] === 'B') {
  //           height++;
  //           i++;
  //         }
  //         else {
  //           j++;
  //           i++;
  //         }
  //       }

  //       break;
  //     }
  //   }
  // }

  // console.log(y + 1 + Math.floor(height / 2), x + 1 + Math.floor(width / 2));
});

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    [n, m] = d.split(' ').map(Number);
    return;
  }

  matrix.push(d.split(''));

  c++;
});

rl.on('close', () => {
  let width = 1;
  let height = 1;
  let x, y;

  for (let i = 0; i < matrix.length; i++) {
    for (let j = 0; j < matrix[i].length; j++) {
      if (matrix[i][j] === 'B') {
        x = j;
        y = i;

        while (matrix[i] && matrix[i][j] === 'B') {
          if (matrix[i][j + 1] === 'B') {
            width++;
            j++;
          }
          else if (matrix[i + 1] && matrix[i + 1][j] === 'B') {
            height++;
            i++;
          }
          else {
            j++;
            i++;
          }
        }

        break;
      }
    }
  }

  console.log(y + 1 + Math.floor(height / 2), x + 1 + Math.floor(width / 2));
});

var opt = readline().split(' ');
var row = parseInt(opt[0]);
var column = parseInt(opt[1]);
var squareMassive=[];
squareMassive.length = row;

function findCentre(row,column)
{
    for(var i=0;i<row;i++)
    {
        squareMassive[i] = readline();
        var sStart = null;
        var squareLength=0;
        for(var j=0;j<column;j++)
        {
            if (squareMassive[i][j]=='B') {
                var t = j;
                while(squareMassive[i][++t] === 'B');
                var c = (t - j+1) / 2;
                return {
                    row: i + c,
                    column: j + c
                };
            }
        }

    }

}

var result=findCentre(row,column);
print(result.row);
print(result.column)

var firstLine = readline();
var n = firstLine.split(" ")[0];
var k = firstLine.split(" ")[1];

print(output(k, n))

function output(k, n) {
    var arr = []
    for (var i = 0; i < n; i++) {
        var string = readline();
        arr.push(string);
    }
    var edjeX1 = 0;
    var edjeX2 = parseInt(k) - 1;
    var edjeY1 = 0;
    var edjeY2 = parseInt(n) - 1;
    for (var i = 0; i < n; i++) {
        for (var j = 0; j < k; j++) {
            if (arr[i][j] === "B" && edjeX1 === 0) {
                edjeX1 = j + 1;
            }
            if (arr[i][j] === "W" && j > 0 && arr[i][j-1] === "B" && edjeX2 === parseInt(k) - 1) {
                edjeX2 = j;
            }
            if (arr[i][j] === "B" && edjeY1 === 0) {
                edjeY1 = i + 1;
            }
            if (arr[i][j] === "W" && i > 0 && arr[i-1][j] === "B" && edjeY2 === parseInt(n) - 1) {
                edjeY2 = i;
            }
        }
    }
    return (Math.ceil((edjeY1 + edjeY2)/2)).toString() + ' ' + (Math.ceil((edjeX1 + edjeX2)/2)).toString();
}

n = readline().split(' ').map(Number)[0]
r1 = r2 = c = -1
for (i = 0; i < n; i++) {
	a = readline()
	if (a.includes('B')) {
		if (r1==-1) r1 = i
		r2 = i
		c = (a.lastIndexOf('B')+a.indexOf('B'))/2
	}
}
print((r1+r2)/2+1, c+1)

var g = readline().split(" ");

var n = Number(g[0]);
var m = Number(g[1]);

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

    var k = readline();

    var B = k.indexOf("B");

    if(B != -1){
        var b = B;
        var side = 1;
        while(k[b] == "B"){
            side++;
            b++;
        }

        var point = Math.ceil(side/2);
        p_x = point + B;
        p_y = point + i;
        break;
    }
}

print(p_y, p_x);

//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 one = nextIntArray();
	var H = one[0];
	var W = one[1];
	var list = new Array(H);
	for(var i = 0; i < H; i++){
		list[i] = nextCharArray();
	}
	for(var i = 0; i < H; i++){
		for(var j = 0; j < W; j++){
			if(list[i][j] == "B"){
				var add = -1;
				for(var k = 0; Math.max(i + k, j + k) < Math.min(H, W); k++){
					if(list[i + k][j + k] == "B"){
						add++;
					}else{
						break;
					}
				}
				add = Math.ceil(add / 2);
				myout((i + 1 + add) + " " + (j + 1 + add));
				return;
			}
		}
	}
}

//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 one = nextIntArray();
	var H = one[0];
	var W = one[1];
	var list = new Array(H);
	for(var i = 0; i < H; i++){
		list[i] = nextCharArray();
	}
	for(var i = 0; i < H; i++){
		for(var j = 0; j < W; j++){
			if(list[i][j] == "B"){
				var add = 0;
				for(var k = 1; Math.max(i + k, j + k) < Math.min(H, W); k++){
					if(list[i + k][j + k] == "B"){
						add++;
					}else{
						break;
					}
				}
				add = Math.floor(add / 2);
				myout((i + 1 + add) + " " + (j + 1 + add));
				return;
			}
		}
	}
}

var firstLine = readline();
var n = firstLine.split(" ")[0];
var k = firstLine.split(" ")[1];

print(output(k, n))

function output(k, n) {
    var arr = []
    for (var i = 0; i < n; i++) {
        var string = readline();
        arr.push(string);
    }
    var edjeX1 = 0;
    var edjeX2 = parseInt(k) - 1;
    var edjeY1 = 0;
    var edjeY2 = parseInt(n) - 1;
    for (var i = 0; i < n; i++) {
        for (var j = 0; j < k; j++) {
            if (arr[i][j] === "B" && edjeX1 === 0) {
                edjeX1 = j;
            }
            if (arr[i][j] === "W" && j > 0 && arr[i][j-1] === "B" && edjeX2 === parseInt(k) - 1) {
                edjeX2 = j;
            }
            if (arr[i][j] === "B" && edjeY1 === 0) {
                edjeY1 = i;
            }
            if (arr[i][j] === "W" && i > 0 && arr[i-1][j] === "B" && edjeY2 === parseInt(n) - 1) {
                edjeY2 = i;
            }
        }
    }
    return (Math.ceil((edjeY1 + edjeY2)/2)).toString() + ' ' + (Math.ceil((edjeX1 + edjeX2)/2)).toString();
}

var firstLine = readline();
var n = firstLine.split(" ")[0];
var k = firstLine.split(" ")[1];

print(output(k, n))

function output(k, n) {
    var arr = []
    for (var i = 0; i < n; i++) {
        var string = readline();
        arr.push(string);
    }
    var edjeX1 = 0;
    var edjeX2 = parseInt(k) - 1;
    var edjeY1 = 0;
    var edjeY2 = parseInt(n) - 1;
    for (var i = 0; i < n; i++) {
        for (var j = 0; j < k; j++) {
            if (arr[i][j] === "B" && edjeX1 === 0) {
                edjeX1 = j;
            }
            if (arr[i][j] === "W" && j > 0 && arr[i][j-1] === "B" && edjeX2 === parseInt(k) - 1) {
                edjeX2 = j-1;
            }
            if (arr[i][j] === "B" && edjeY1 === 0) {
                edjeY1 = i;
            }
            if (arr[i][j] === "W" && i > 0 && arr[i-1][j] === "B" && edjeY2 === parseInt(n) - 1) {
                edjeY2 = i-1;
            }
        }
    }
    return (Math.ceil((edjeY1 + edjeY2)/2)).toString() + ' ' + (Math.ceil((edjeX1 + edjeX2)/2)).toString();
}

var firstLine = readline();
var n = firstLine.split(" ")[0];
var k = firstLine.split(" ")[1];

print(output(k, n))

function output(k, n) {
    var arr = []
    for (var i = 0; i < n; i++) {
        var string = readline();
        arr.push(string);
    }
    var edjeX1 = 0;
    var edjeX2 = 0;
    var edjeY1 = 0;
    var edjeY2 = 0;
    for (var i = 0; i < n; i++) {
        for (var j = 0; j < k; j++) {
            if (arr[i][j] === "B" && edjeX1 === 0) {
                edjeX1 = j;
            }
            if (arr[i][j] === "W" && arr[i][j-1] && arr[i][j-1] === "B" && edjeX2 === 0) {
                edjeX2 = j;
            }
            if (arr[i][j] === "B" && edjeY1 === 0) {
                edjeY1 = i;
            }
            if (arr[i][j] === "W" && i > 0 && arr[i-1][j] === "B" && edjeY2 === 0) {
                edjeY2 = i;
            }
        }
    }
    return (Math.ceil((edjeY1 + edjeY2)/2)).toString() + ' ' + (Math.ceil((edjeX1 + edjeX2)/2)).toString();
}

var firstLine = readline();
var n = firstLine.split(" ")[0];
var k = firstLine.split(" ")[1];

print(output(k, n))

function output(k, n) {
    var arr = []
    for (var i = 0; i < n; i++) {
        var string = readline();
        arr.push(string);
    }
    var edjeX1 = 0;
    var edjeX2 = parseInt(k) - 1;
    var edjeY1 = 0;
    var edjeY2 = parseInt(n) - 1;
    for (var i = 0; i < n; i++) {
        for (var j = 0; j < k; j++) {
            if (arr[i][j] === "B" && edjeX1 === 0) {
                edjeX1 = j;
            }
            if (arr[i][j] === "W" && arr[i][j-1] && arr[i][j-1] === "B" && edjeX2 === 0) {
                edjeX2 = j;
            }
            if (arr[i][j] === "B" && edjeY1 === 0) {
                edjeY1 = i;
            }
            if (arr[i][j] === "W" && i > 0 && arr[i-1][j] === "B" && edjeY2 === 0) {
                edjeY2 = i;
            }
        }
    }
    return (Math.ceil((edjeY1 + edjeY2)/2)).toString() + ' ' + (Math.ceil((edjeX1 + edjeX2)/2)).toString();
}


You are given an integer $$$x$$$ and an array of integers $$$a_1, a_2, \ldots, a_n$$$. You have to determine if the number $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$.Here $$$k!$$$ is a factorial of $$$k$$$ — the product of all positive integers less than or equal to $$$k$$$. For example, $$$3! = 1 \cdot 2 \cdot 3 = 6$$$, and $$$5! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120$$$.

The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 500\,000$$$, $$$1 \le x \le 500\,000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le x$$$) — elements of given array.

In the only line print "Yes" (without quotes) if $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$, and "No" (without quotes) otherwise.

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

function solve(n, k, arr) {
    const map = arr.reduce((o, x) => {
        // o[x] = 1
        o[x] = (o[x] || 0) + 1
        return o
    }, {})
    for (let x = 1; x < k; x++) {
        const t = map[x] || 0
        if (t % (x + 1)) return 'No'
        map[x + 1] = (map[x + 1] || 0) + (t / (x + 1))
    }
    return 'Yes'
}


Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals n squares (n is an odd number) and each unit square contains some small letter of the English alphabet.Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:  on both diagonals of the square paper all letters are the same;  all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. Help Valera, write the program that completes the described task for him.

The first line contains integer n (3 ≤ n < 300; n is odd). Each of the next n lines contains n small English letters — the description of Valera's paper.

Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes.

let fs = require("fs");

let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
// txt.shift();
for (let index = 0; index < txt.length; index++) {
    if (!isNaN(txt[index])) {
        let tab = []
        for (let i = index + 1; i < index + txt[index] * 1 + 1; i++) {
            tab.push(txt[i].split("").filter(data => {
                return data.length > 0
            }))
        }
        doit(tab)
    }

}

function doit(tab) {
    let s = tab[0][0],
        len = tab.length - 1;
    let arr = [],diag=[]
    tab.forEach(d => {
        d.forEach(data=>{
            if (!arr.includes(data)) {
                arr.push(data);
            }
            if(data==s){
                diag.push(data);
            }
        })
    })
    if (arr.length != 2 || diag.length!=tab.length*2-1) {
        console.log("NO");
        return;
    }

    let test = true
    tab.forEach((data, index) => {
        if (data[index] != s || data[len - index] != s) {
            test = false;
            return;
        }
    });
    if (test) {
        console.log("YES");
    } else {
        console.log("NO");
    }
}

print(function(n) {
	var q = [];
	for (var i = 0; i < n; i++)
		q.push(readline().split(''));
	var a = q[0][0];
	var b = q[0][1];
	if(a===b) return 'NO';
	for (var i = 0; i < n; i++)
		for (var j = 0; j < n; j++)
			if (i === j || i === n - j - 1) {
				if (q[i][j] !== a) return 'NO';
			} else {
				if (q[i][j] !== b) return 'NO';
			}

	return 'YES';

}(+readline()));

var squareSize = Number(readline())

var index = 0
var ans = true
var xLetter
var oLetter

for (var i = 0; i < squareSize; i++) {
  var line = readline()
  if (i === 0) {
    xLetter = line[0]
    oLetter = line[1]
    if (xLetter === oLetter) {
      ans = false
      break;
    }
  }

  for (var j = 0; j < line.length; j++) {
    if (j === index || j === line.length - 1 - index) {
      if (line[j] !== xLetter) {
        ans = false
      }
    } else {
      if (line[j] !== oLetter) {
        ans = false
      }
    }

    if (ans === false) {
      break;
    }
  }

  if (ans === false) {
    break;
  }

  if (i < Math.floor(squareSize / 2)) {
    index += 1
  } else {
    index -= 1
  }
}

if (ans) {
  print('YES')
} else {
  print('NO')
}

;(function () {

	var n = +readline();
	var t = [];
	for (var i = 0; i < n; i++) t.push(readline());

	var g = t[0][0];
	var b = t[0][1];

	if (g == b) {
		print('NO');
		return;
	}

	for (var i = 0; i < n; i++)
		for (var j = 0; j < n; j++)
			if ( i == j || i + j == (n - 1) ) {

				if (t[i][j] != g) {
					print('NO');
					return;
				}

			} else {

				if (t[i][j] != b) {
					print('NO');
					return;
				}

			}

	print('YES');

}).call(this);

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], 10);
	};
	return tokens;
}

function main() {
	var n = parseInt(readline()),
		rows = [], letters = [], count = {};
	for (var r = 0; r < n; ++r) {
		var row = trim(readline());
		rows.push(row);
		for (var c = 0; c < n; ++c) {
			var ch = row.charAt(c);
			if (count[ch] === undefined) {
				letters.push(ch);
				count[ch] = 0;
			}
			count[ch] += 1;
		}
	}
	if (letters.length != 2) {
		print('NO');
		return;
	}
	var xCount = 2*n - 1;
	if (count[letters[0]] == xCount) {
		var x = letters[0];
	} else if (count[letters[1]] == xCount) {
		var x = letters[1];
	} else {
		print('NO');
		return;
	}
	for (var d = 0; d < n; ++d) {
		if (rows[d].charAt(d) != x || rows[d].charAt(n-1-d) != x) {
			print('NO');
			return;
		}
	}
	print('YES');
}

main();

(function (){
    var i, j, n = parseInt(readline());
    var board = [];
    for(i = 0 ; i < n ; ++i){
        board[i] = readline();
    }

    var result = true;
    // first condition
    for( i = 0 ; result && i < n ; ++i){
        if ( board[i][i] != board[0][0] || board[i][n-1-i] != board[0][0] ){
            result = false;
        }
        for( j=0 ; result && j < n ; ++j){
            if ( j != i && j != n - 1 - i ){
                if ( board[i][j] == board[0][0] || board[i][j] != board[0][1] ){
                    result = false;
                }
            }
        }
    }
    if ( result ){
        print("YES");
    }else{
        print("NO");
    }
})();

(function () {

var n = parseInt(readline());

var first;
var second;
for (var i = 0; i < n; i++) {
    var row = readline().split('');
    if (!first) {
        first = row[0];
        second = row[1];

        if (first === second) {
            print('NO');
            return;
        }
    }

    for (var j = 0; j < row.length; j++) {
        if (i === j || row.length - 1 - i ===  j) {
            if (row[j] !== first) {
                print('NO');
                return;
            }
        } else {
            if (row[j] !== second) {
                print('NO');
                return;
            }
        }
    }
}

print('YES');
})();

(function () {

var num, n;
num = n = parseInt(readline());

var row = [];
var first;
var second;

while (num--) {
    row.push(readline().split(''));
}

first = row[0][0];
second = row[0][1];

if (first === second) {
    print('NO');
    return;
}

for (var i = 0; i < n; i++) {
    for (var j = 0; j < n; j++) {
        if (i === j || n - 1 === i + j) {
            if (row[i][j] !== first) {
                print('NO');
                return;
            }
        } else {
            if (row[i][j] !== second) {
                print('NO');
                return;
            }
        }
    }
}

print('YES');
})();

var n = parseInt(readline());

var flag = true;
var first;
var second;
var res = 'YES';
for (var i = 0; i < n; i++) {
    var row = readline().split('');
    if (!first) {
        first = row[0];
        second = row[1];

        if (first === second) {
            flag = false;
            res = 'NO';
        }
    }

    for (var j = 0; j < row.length; j++) {
        if (i === j || row.length - 1 - i ===  j) {
            if (row[j] !== first) {
                flag = false;
                res = 'NO';
                break;
            }
        } else {
            if (row[j] !== second) {
                flag = false;
                res = 'NO';
                break;
            }
        }
    }

    if (!flag) {
        break;
    }
}

print(res);

let fs = require("fs");

let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
// txt.shift();
for (let index = 0; index < txt.length; index++) {
    if (!isNaN(txt[index])) {
        let tab = []
        for (let i = index + 1; i < index + txt[index] * 1 + 1; i++) {
            tab.push(txt[i].split("").filter(data => {
                return data.length > 0
            }))
        }
        doit(tab)
    }

}

function doit(tab) {
    let s = tab[0][0],
        len = tab.length - 1;
    let arr = []
    tab.forEach(d => {
        d.forEach(data=>{
            if (!arr.includes(data)) {
                arr.push(data);
            }
        })
    })
    if (arr.length != 2) {
        console.log("NO");
        return;
    }

    let test = true
    tab.forEach((data, index) => {
        if (data[index] != s || data[len - index] != s) {
            test = false;
            return;
        }
    });
    if (test) {
        console.log("YES");
    } else {
        console.log("NO");
    }
}

let fs = require("fs");

let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
// txt.shift();
for (let index = 0; index < txt.length; index ++) {
    if(!isNaN(txt[index])){
        let tab=[]
        for (let i = index+1; i < index+txt[index]*1+1; i++) {
            tab.push(txt[i].split("").filter(data=>{return data.length>0}))
        }
        doit(tab)
    }

}

function doit(tab) {
   let s=tab[0][0],len=tab.length-1;
   let test=true
   tab.forEach((data,index) => {
       if(data[index]!=s || data[len-index]!=s){
           test=false;
           return;
       }
   });
   if(test){
       console.log("YES");
   }else{
       console.log("NO");
   }

}

let fs = require("fs");

let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
// txt.shift();
for (let index = 0; index < txt.length; index ++) {
    if(!isNaN(txt[index])){
        let tab=[]
        for (let i = index+1; i < index+txt[index]*1+1; i++) {
            tab.push(txt[i].split("").filter(data=>{return data.length>0}))
        }
        doit(tab)
    }

}

function doit(tab) {
   let s=tab[0][0],len=tab.length-1;
   let ss=tab[0][1];
   let test=true
   tab.forEach((data,index) => {
       if(data[index]!=s || data[len-index]!=s){
           test=false;
           return;
       }
       data.forEach((d,i)=>{
           if(i!=index && i!=len-index && d!=ss){
               test=false;
               return;
           }
       })
   });
   if(test){
       console.log("YES");
   }else{
       console.log("NO");
   }

}

print(function(n) {
	var q = [];
	for (var i = 0; i < n; i++)
		q.push(readline().split(''));
	var a = q[0][0];
	var b = q[0][1];
	for (var i = 0; i < n; i++)
		for (var j = 0; j < n; j++)
			if (i === j || i === n - j) {
				if (q[i][j] !== a) return 'NO';
			} else {
				if (q[i][j] !== b) return 'NO';
			}

	return 'YES';

}(+readline()));

print(function(n) {
	var q = [];
	for (var i = 0; i < n; i++)
		q.push(readline().split(''));
	var a = q[0][0];
	var b = q[0][1];
	for (var i = 0; i < n; i++)
		for (var j = 0; j < n; j++)
			if (i === j || i === n - j - 1) {
				if (q[i][j] !== a) return 'NO';
			} else {
				if (q[i][j] !== b) return 'NO';
			}

	return 'YES';

}(+readline()));

(function (){
    var i, j, n = parseInt(readline());
    var board = [];
    for(i = 0 ; i < n ; ++i){
        board[i] = readline();
    }

    var result = true;
    // first condition
    for( i = 0 ; result && i < n ; ++i){
        if ( board[i][i] != board[0][0] || board[i][n-1-i] != board[0][0] ){
            result = false;
        }
        for( j=0 ; result && j < n ; ++j){
            if ( j != i && j != n - 1 - i ){
                if ( board[i][j] == board[0][0] ){
                    result = false;
                }
            }
        }
    }
    if ( result ){
        print("YES");
    }else{
        print("NO");
    }
})();

(function () {

var n = parseInt(readline());

var row = [];
var first;
var second;

while (n--) {
    row.push(readline().split(''));
}

first = row[0][0];
second = row[1][1];

if (first === second) {
    print('NO');
    return;
}

for (var i = 0; i < n; i++) {
    for (var j = 0; j < n; j++) {
        if (i === j || n - 1 === i + j) {
            if (row[i][j] !== first) {
                print('NO');
                return;
            }
        } else {
            if (row[i][j] !== second) {
                print('NO');
                return;
            }
        }
    }
}

print('YES');
})();

(function () {

var n = parseInt(readline());

var row = [];
var first;
var second;

while (n--) {
    row.push(readline().split(''));
}

first = row[0][0];
second = row[0][1];

if (first === second) {
    print('NO');
    return;
}

for (var i = 0; i < n; i++) {
    for (var j = 0; j < n; j++) {
        if (i === j || n - 1 === i + j) {
            if (row[i][j] !== first) {
                print('NO');
                return;
            }
        } else {
            if (row[i][j] !== second) {
                print('NO');
                return;
            }
        }
    }
}

print('YES');
})();

var n = parseInt(readline());

var flag = true;
var first;
var second;
for (var i = 0; i < n; i++) {
    var row = readline().split('');
    if (!first) {
        first = row[0];
        second = row[1];
    }

    for (var j = 0; j < row.length; j++) {
        if (i === j || row.length - 1 - i ===  j) {
            if (row[j] !== first) {
                flag = false;
                break;
            }
        } else {
            if (row[j] !== second) {
                flag = false;
                break;
            }
        }
    }

    if (!flag) {
        break;
    }
}

if (!flag) {
    print("NO");
} else {
    print("YES");
}

var n = parseInt(readline());

var flag = true;
var first;
var second;
for (var i = 0; i < n; i++) {
    var row = readline().split('');
    if (!first) {
        first = row[0][0];
        second = row[0][1];
    }

    for (var j = 0; j < row.length; j++) {
        if (i === j || row.length - 1 - i ===  j) {
            if (row[i][j] !== first) {
                flag = false;
                break;
            }
        } else {
            if (row[i][j] !== second) {
                flag = false;
                break;
            }
        }
    }

    if (!flag) {
        break;
    }
}

if (!flag) {
    print("NO");
} else {
    print("YES");
}


Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.

For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.

NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.

const myMap = new Set();
function findMin (currentPos){
	if (!myMap.has(currentPos)){
		return 0;
	}
	var left =  currentPos - 1, leftVal = -1;
	var right = currentPos + 1, rightVal = -1;
	while (left > 0 || right <= endPoint){
		if (  left > 0 && !myMap.has(left) ){
			leftVal = Math.abs(currentPos-left);
			break;
		}
		else if (right <= endPoint && !myMap.has(right) ){
			rightVal = Math.abs(currentPos-right);
			break;
		}
		left -= 1; right += 1;
	}
	return (leftVal != -1) ? leftVal : rightVal;
}
var queries = parseInt(readline());
for (var i = 0; i< queries;i++)
{
var discard = readline().split(' ');
var endPoint = parseInt(discard[0]);
readline().split(' ').forEach((val)=>{
	myMap.add(parseInt(val));
})
print(findMin(parseInt(discard[1])));
myMap.clear();
}

const myMap = new Set();
function findMin (currentPos){
	if (!myMap.has(currentPos)){
		return 0;
	}
	var left =  currentPos - 1, leftVal = -1;
	var right = currentPos + 1, rightVal = -1;
	while (left > 0 || right <= endPoint){
		if (!myMap.has(left) && left > 0){
			leftVal = Math.abs(currentPos-left);
			break;
		}
		else if (!myMap.has(right) && right <= endPoint){
			rightVal = Math.abs(currentPos-right);
			break;
		}
		left -= 1; right += 1;
	}
	return (leftVal != -1) ? leftVal : rightVal;
}
var queries = parseInt(readline());
for (var i = 0; i< queries;i++)
{
var discard = readline().split(' ');
var endPoint = parseInt(discard[0]);
readline().split(' ').forEach((val)=>{
	myMap.add(parseInt(val));
})
print(findMin(parseInt(discard[1])));
myMap.clear();
}

function main() {
    var t = readline();
    for (var i = 0; i < t; i++) {
        findNext();
    }
}

function findNext() {
    var nsk = readline().split(' ');
    var n = +nsk[0];
    var s = +nsk[1];
    var k = +nsk[2];
    var ks = readline().split(' ');

    var ksObj = {}
    for (var d = 0; d < k; d++) {
        ksObj[ks[d]] = true;
    }

    for (var j = 0; j <= n; j++) {
        var plusJ = !ksObj[s + j] && s + j <= n;
        var minusJ = !ksObj[s - j] && s - j >= 1;

        if (plusJ || minusJ) {
            print(j);
            return;
        }
    }
}
main()

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  const t = readInt(input)

  for(let count = 0; count < t; count ++) {
    const [n, s, k] = readInts(input, 2 * count)

    const ks = readInts(input, 2 * count + 1)

    sort(ks)

    let i = -2, j = -2
    if(s < n) i = ks.indexOf(s + 1)
    if(s > 1) j = ks.indexOf(s - 1)

    if(ks.indexOf(s) == -1) {
      wr(0)
      continue
    }

    if(i == -1 || j == -1) {
      wr(1)
      continue
    }
    let a = -1, b = -1

    let x = s + 1

    while(true && x <= n && i < k) {
      if(ks[i] != x) {
        a = x - s
        break
      }
      else {
        i++
        x++
      }
    }
    // wr(i, x)
    if(a == -1 && x <= n) a = x - s

    x = s - 1
    while(true && x>= 0 && j >= 0) {
      // wr(k[j], x, j)
      if(ks[j] != x) {
        b = s - x
        break
      }
      else {
        j--
        x--
      }
    }

    if(b == -1 && x > 0) b = s - x

    // wr(a, b)
    if(a == -1 && b == -1) wr(0)
    else if(a == -1) wr(b)
    else if(b == -1) wr(a)
    else wr(Math.min(a, b))
  }
}

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main(arr)
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  const t = readInt(input)

  for(let count = 0; count < t; count ++) {
    const [n, s, k] = readInts(input, 2 * count)

    const ks = readInts(input, 2 * count + 1)

    sort(ks)

    let i = -2, j = -2
    if(s < n) i = ks.indexOf(s + 1)
    if(s > 1) j = ks.indexOf(s - 1)

    if(i == -1 || j == -1) {
      wr(1)
      continue
    }
    let a = -1, b = -1

    let x = s + 1

    while(true && x <= n && i < k) {
      if(ks[i] != x) {
        a = x - s
        break
      }
      else {
        i++
        x++
      }
    }
    // wr(i, x)
    if(a == -1 && x <= n) a = x - s

    x = s - 1
    while(true && x>= 0 && j >= 0) {
      // wr(k[j], x, j)
      if(ks[j] != x) {
        b = s - x
        break
      }
      else {
        j--
        x--
      }
    }

    if(b == -1 && x > 0) b = s - x

    // wr(a, b)
    if(a == -1 && b == -1) wr(0)
    else if(a == -1) wr(b)
    else if(b == -1) wr(a)
    else wr(Math.min(a, b))
  }
}