One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.

Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.

NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".

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

  const arr = lines.slice(1, lines.length).filter(l => l);
  const defaultValue = [...new Array(500000)].map(i => 0);
  const opened = [...defaultValue];
  const closed = [...defaultValue];
  let ans = 0;

  function isCorrectBracket(str) {
    const res = [0, 0];

    for (const s of str) {
      if (s === '(') {
        res[0]++;
      } else {
        if (res[0] > 0){
          res[0]--;
        } else {
          res[1]++;
        }
      }
    }

    return res;
  }

  for (const index in arr) {
    const res = isCorrectBracket(arr[index]);

    if (res[0] === 0 && res[1] === 0) {
      ans++;
    } else if (res[0] !== 0 && res[1] !== 0) {
      continue;
    } else {
      if (res[0]) {
        opened[res[0]]++;
      } else {
        closed[res[1]]++;
      }
    }
  }

  for (let i = 1; i < 500000; i++) {
    if (opened[i]) {
      if (opened[i] > 0 && closed[i] > 0) {
        while (opened[i] && closed[i]) {
          opened[i]--;
          closed[i]--;
          ans += 2;
        }
      }
    }
  }

  console.log(parseInt(ans / 2));
});

// const lines = `7
// )())
// )
// ((
// ((
// (
// )
// )`.split('\n');

// const arr = lines.slice(1, lines.length).filter(l => l);
// const n = lines[0];
// const defaultValue = [...new Array(500000)].map(i => 0);
// const opened = [...defaultValue];
// const closed = [...defaultValue];
// let ans = 0;
//
// function isCorrectBracket(str) {
//   const res = [0, 0];
//
//   for (const s of str) {
//     if (s === '(') {
//       res[0]++;
//     } else {
//       if (res[0] > 0){
//         res[0]--;
//       } else {
//         res[1]++;
//       }
//     }
//   }
//
//   return res;
// }
//
// for (const index in arr) {
//   const res = isCorrectBracket(arr[index]);
//
//   if (res[0] === 0 && res[1] === 0) {
//     ans++;
//   } else if (res[0] !== 0 && res[1] !== 0) {
//     continue;
//   } else {
//     if (res[0]) {
//       opened[res[0]]++;
//     } else {
//       closed[res[1]]++;
//     }
//   }
// }
//
// for (let i = 1; i < 500000; i++) {
//   if (opened[i]) {
//     if (opened[i] > 0 && closed[i] > 0) {
//       while (opened[i] && closed[i]) {
//         opened[i]--;
//         closed[i]--;
//         ans += 2;
//       }
//     }
//   }
// }
//
// console.log(parseInt(ans / 2));

// function isCorrectBracket(str) {
//   const stack = [];
//
//   for (const s of str) {
//     if (s === '(') {
//       stack.push('(');
//     } else {
//       if (stack[stack.length - 1] === '('){
//         stack.pop();
//       } else {
//         stack.push(')')
//       }
//     }
//   }
//
//   return !stack.length;
// }
//
// function pairs(arr, start) {
//   const temp = [];
//   for (let j = start + 1; j < arr.length; j++) {
//     temp.push([arr[start], arr[j]]);
//   }
//
//   return temp;
// }
//
// let count = 0;
//
// for (let i = 0; i < arr.length - 1; i++) {
//   const temp = pairs(arr, i);
//
//   for (const index in temp) {
//     if (isCorrectBracket(temp[index].join('')) || isCorrectBracket(temp[index].reverse().join(''))) {
//       arr.splice(i + parseInt(index) + 1, 1);
//       count++;
//       break;
//     }
//   }
// }
//
// console.log(count);

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
  const {EOL} = require('os');
  const lines = i.split(EOL) ;/*your input text, split by lines*/
  const arr = lines.slice(1, lines.length).filter(l => l);

  function isCorrectBracket(str) {
    const stack = [];

    for (const s of str) {
      if (s === '(') {
        stack.push('(');
      } else {
        if (stack[stack.length - 1] === '('){
          stack.pop();
        } else {
          stack.push(')')
        }
      }
    }

    return !stack.length;
  }

  function pairs(arr) {
    let temp = [];

    for (let i = 0; i < arr.length - 1; i++) {
      temp[i] = [];
      for (let j = i + 1; j < arr.length; j++) {
        temp[i].push([arr[i], arr[j]]);
      }
    }

    return temp;
  }

  let count = 0;
  let temp = pairs(arr);

  for (const ssIndex in temp) {
    for (const index in temp[ssIndex]) {
      if (isCorrectBracket(temp[ssIndex][index].join('')) || isCorrectBracket(temp[ssIndex][index].reverse().join(''))) {
        temp.splice(parseInt(ssIndex) + parseInt(index) - count + 1, 1);
        count++;
        break;
      }
    }
  }

  console.log(count);
});

// const lines = `7
// )())
// )
// ((
// ((
// (
// )
// )`.split('\n');
//
// const arr = lines.slice(1, lines.length).filter(l => l);
//
// function isCorrectBracket(str) {
//   const stack = [];
//
//   for (const s of str) {
//     if (s === '(') {
//       stack.push('(');
//     } else {
//       if (stack[stack.length - 1] === '('){
//         stack.pop();
//       } else {
//         stack.push(')')
//       }
//     }
//   }
//
//   return !stack.length;
// }
//
// function pairs(arr) {
//   let temp = [];
//
//   for (let i = 0; i < arr.length - 1; i++) {
//     temp[i] = [];
//     for (let j = i + 1; j < arr.length; j++) {
//       temp[i].push([arr[i], arr[j]]);
//     }
//   }
//
//   return temp;
// }
//
// let count = 0;
// let temp = pairs(arr);
//
// for (const ssIndex in temp) {
//   for (const index in temp[ssIndex]) {
//     if (isCorrectBracket(temp[ssIndex][index].join('')) || isCorrectBracket(temp[ssIndex][index].reverse().join(''))) {
//       temp.splice(parseInt(ssIndex) + parseInt(index) - count + 1, 1);
//       count++;
//       break;
//     }
//   }
// }
//
// console.log(count);


Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and b are different. Then your task will be to find any string s3 of length n, such that f(s1, s3) = f(s2, s3) = t. If there is no such string, print  - 1.

The first line contains two integers n and t (1 ≤ n ≤ 105, 0 ≤ t ≤ n). The second line contains string s1 of length n, consisting of lowercase English letters. The third line contain string s2 of length n, consisting of lowercase English letters.

Print a string of length n, differing from string s1 and from s2 in exactly t characters. Your string should consist only from lowercase English letters. If such string doesn't exist, print -1.

input = readline().split(" ").map(Number);
var n = input[0];
var t = input[1];
var s1 = readline();
var s2 = readline();

var diff1 = 0;
var a = new Array(n);
var answer = "";
var d = [];
var j = 0;
for (var i = 0; i < n; i++)
{
	if (s1[i] != s2[i]) {
		diff1 += 1;
		d[j++] = i;
	}
}

if (diff1 <= (t+t)) {
	for (var i = 0; i < n; i++)
		a[i] = s1.charCodeAt(i);

	var samePreffix = diff1 - t;

	if (samePreffix > 0) {
		var restPreffix = samePreffix;
		for (var i = 0; i < diff1; i++) {
			// part 1
			if (i < samePreffix) {
				a[d[i]] = s2.charCodeAt(d[i]);
			}
			// part 2
			if (samePreffix <= i && i < diff1-samePreffix) {
				a[d[i]] = s1.charCodeAt(d[i]) + 1;
				if (a[d[i]] > "z".charCodeAt(0))
					a[d[i]] -= 26;

				if (a[d[i]] == s2.charCodeAt(d[i]))
					a[d[i]] += 1;
			}
			// part 3
		}
	} else {
		for (var i = 0; i < n; i++) {
			if (s1[i] == s2[i]) {
				if (samePreffix < 0) {
					a[i] += 1;
					samePreffix += 1;
				}
			} else {
				a[i] += 1;
				if (a[i] > "z".charCodeAt(0))
					a[i] -= 26;
				if (a[i] == s2.charCodeAt(i))
					a[i] += 1;
			}
		}
	}

	for (var i = 0; i < n; i++) {
		if (a[i] > "z".charCodeAt(0))
			a[i] -= 26;
		answer += String.fromCharCode(a[i]);
	}
} else {
	answer = "-1";
}

write(answer);

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    // console.log(lines);

    let [n, t] = lines[0].split(' ');
    let s1 = lines[1];
    let s2 = lines[2];
    let ans = [];
    let sameCount = 0;
    let remain1, remain2;
    let diff = t;
    let bb = true;
    t = n - t; // t defind as the count need to be the same
    for (let i = 0; i < n; i++) {
        if (s1[i] === s2[i] && n - sameCount > diff) {
            ans[i] = s1[i];
            sameCount++;
        }
    }

    if (t * 2 - sameCount > n) {
        console.log(-1);
        bb = false;
    } else {
        remain1 = remain2 = t - sameCount;
        for (i = 0; i < n; i++) {
            if (ans[i]) { continue }
            if (remain1 > 0) {
                ans[i] = s1[i];
                remain1--;
            } else if (remain2 > 0) {
                ans[i] = s2[i];
                remain2--;
            } else {
                ans[i] = ['a', 'b', 'c'].find(char => (char !== s1[i] && char !== s2[i]))
            }
        }
    }
    if (bb) {
        console.log(ans.join(''));
    }
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    // console.log(lines);

    let [n, t] = lines[0].split(' ');
    let s1 = lines[1];
    let s2 = lines[2];
    let ans = [];
    let sameCount = 0;
    let remain1, remain2;
    let diff = t;
    t = n - t; // t defind as the count need to be the same
    for (let i = 0; i < n; i++) {
        if (s1[i] === s2[i] && n - sameCount > diff) {
            ans[i] = s1[i];
            sameCount++;
        }
    }

    if (t * 2 - sameCount > n) {
        console.log(-1);
    } else {
        remain1 = remain2 = t - sameCount;
        for (i = 0; i < n; i++) {
            if (ans[i]) { continue }
            if (remain1 > 0) {
                ans[i] = s1[i];
                remain1--;
            } else if (remain2 > 0) {
                ans[i] = s2[i];
                remain2--;
            } else {
                ans[i] = ['a', 'b', 'c'].find(char => (char !== s1[i] && char !== s2[i]))
            }
        }
    }
    console.log(ans.join(''));
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    // console.log(lines);

    let [n, t] = lines[0].split(' ');
    let s1 = lines[1];
    let s2 = lines[2];
    let ans = [];
    let sameCount = 0;
    let remain1, remain2;

    t = n - t; // t defind as the count need to be the same
    for (let i = 0; i < n; i++) {
        if (s1[i] === s2[i]) {
            ans[i] = s1[i];
            sameCount++;
        }
    }

    if (t * 2 - sameCount > n) {
        console.log(-1);
    } else {
        remain1 = remain2 = t - sameCount;
        for (i = 0; i < n; i++) {
            if (ans[i]) { continue }
            if (remain1 > 0) {
                ans[i] = s1[i];
                remain1--;
            } else if (remain2 > 0) {
                ans[i] = s2[i];
                remain2--;
            } else {
                ans[i] = ['a', 'b', 'c'].find(char => (char !== s1[i] && char !== s2[i]))
            }
        }
    }
    console.log(ans.join(''));
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    // console.log(lines);

    let [n, t] = lines[0].split(' ');
    let s1 = lines[1];
    let s2 = lines[2];
    let ans = [];
    let sameCount = 0;
    let remain1, remain2;

    t = n - t; // t defind as the count need to be the same
    for (let i = 0; i < n; i++) {
        if (s1[i] === s2[i] && sameCount < n - t) {
            ans[i] = s1[i];
            sameCount++;
        }
    }

    if (t * 2 - sameCount > n) {
        console.log(-1);
    } else {
        remain1 = remain2 = t - sameCount;
        for (i = 0; i < n; i++) {
            if (ans[i]) { continue }
            if (remain1 > 0) {
                ans[i] = s1[i];
                remain1--;
            } else if (remain2 > 0) {
                ans[i] = s2[i];
                remain2--;
            } else {
                ans[i] = ['a', 'b', 'c'].find(char => (char !== s1[i] && char !== s2[i]))
            }
        }
    }
    console.log(ans.join(''));
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    console.log(lines);
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    // console.log(lines);

    let [n, t] = lines[0].split(' ');
    let s1 = lines[1];
    let s2 = lines[2];
    let ans = [];
    let sameCount = 0;
    let remain1, remain2;

    t = n - t; // t defind as the count need to be the same
    for (let i = 0; i < n; i++) {
        if (s1[i] === s2[i]) {
            ans[i] = s1[i];
            sameCount++;
        }
    }

    if (t * 2 - sameCount > n) {
        console.log(-1);
    } else {
        remain1 = remain2 = t - sameCount;
        for (i = 0; i < n; i++) {
            if (ans[i]) { continue }
            if (remain1 > 0) {
                ans[i] = s1[i];
                remain1--;
            } else if (remain2 > 0) {
                ans[i] = s2[i];
                remain2--;
            } else {
                ans[i] = ['a', 'b', 'c'].find(char => (char !== s1[i] && char !== s2[i]))
            }
        }
    }
    ans = ans.join();
    console.log(ans);
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    // console.log(lines);

    let [n, t] = lines[0].split(' ');
    let s1 = lines[1];
    let s2 = lines[2];
    let ans = [];
    let sameCount = 0;
    let remain1, remain2;

    t = n - t; // t defind as the count need to be the same
    for (let i = 0; i < n; i++) {
        if (s1[i] === s2[i]) {
            ans[i] = s1[i];
            sameCount++;
        }
    }

    if (t * 2 - sameCount > n) {
        console.log(-1);
    } else {
        remain1 = remain2 = t - sameCount;
        for (i = 0; i < n; i++) {
            if (ans[i]) { continue }
            if (remain1 > 0) {
                ans[i] = s1[i];
                remain1--;
            } else if (remain2 > 0) {
                ans[i] = s2[i];
                remain2--;
            } else {
                ans[i] = ['a', 'b', 'c'].find(char => (char !== s1[i] && char !== s2[i]))
            }
        }
    }
    console.log(ans.join());
})

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    // console.log(lines);

    let [n, t] = lines[0].split(' ');
    let s1 = lines[1];
    let s2 = lines[2];
    let ans = [];
    let sameCount = 0;
    let remain1, remain2;

    t = n - t; // t defind as the count need to be the same
    for (let i = 0; i < n; i++) {
        if (s1[i] === s2[i] && n - sameCount > t) {
            ans[i] = s1[i];
            sameCount++;
        }
    }

    if (t * 2 - sameCount > n) {
        console.log(-1);
    } else {
        remain1 = remain2 = t - sameCount;
        for (i = 0; i < n; i++) {
            if (ans[i]) { continue }
            if (remain1 > 0) {
                ans[i] = s1[i];
                remain1--;
            } else if (remain2 > 0) {
                ans[i] = s2[i];
                remain2--;
            } else {
                ans[i] = ['a', 'b', 'c'].find(char => (char !== s1[i] && char !== s2[i]))
            }
        }
    }
    console.log(ans.join(''));
})


The knight is standing in front of a long and narrow hallway. A princess is waiting at the end of it.In a hallway there are three doors: a red door, a green door and a blue door. The doors are placed one after another, however, possibly in a different order. To proceed to the next door, the knight must first open the door before.Each door can be only opened with a key of the corresponding color. So three keys: a red key, a green key and a blue key — are also placed somewhere in the hallway. To open the door, the knight should first pick up the key of its color.The knight has a map of the hallway. It can be transcribed as a string, consisting of six characters:   R, G, B — denoting red, green and blue doors, respectively;  r, g, b — denoting red, green and blue keys, respectively. Each of these six characters appears in the string exactly once.The knight is standing at the beginning of the hallway — on the left on the map.Given a map of the hallway, determine if the knight can open all doors and meet the princess at the end of the hallway.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 720$$$) — the number of testcases. Each testcase consists of a single string. Each character is one of R, G, B (for the doors), r, g, b (for the keys), and each of them appears exactly once.

For each testcase, print YES if the knight can open all doors. Otherwise, print NO.

NoteIn the first testcase, the knight first collects all keys, then opens all doors with them.In the second testcase, there is a red door right in front of the knight, but he doesn't have a key for it.In the third testcase, the key to each door is in front of each respective door, so the knight collects the key and uses it immediately three times.In the fourth testcase, the knight can't open the blue door.

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    lines.pop();
    const inputCount = Number(lines.shift());
    const results = [];

    const checkInput = (input) => {
        const keys = [ 'r', 'g', 'b' ];
        const doors = [ 'R', 'G', 'B' ];
        const data = input.split('');
        return data.every(
            (element, index, array) =>
                doors.includes(element)
                    ? array.slice(0, index).includes(element.toLowerCase())
                    : true
        );
    };

    for (let inputData of lines) {
        results.push(checkInput(inputData));
    }

    for (var result of results) console.log(result ? 'YES' : 'NO');
})

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(j = 1; j<= n; j++){
        var r = false
        var g = false
        var b = false
        var s = false

        var a = lines[j].split('')
        for(k = 0; k < a.length; k++){
            if(a[k] == 'R' && r === false){
            break;
        }else if(a[k] == 'G'&& g === false){
            break;
        }else if(a[k] == 'B' && b === false){
            break;
        }else if(a[k] == 'r'){
            r = true
        }else if(a[k] == 'g'){
            g = true
        }else if(a[k] == 'b'){
            b = true
        }

        }
        if(r === true && g === true & b === true){
            console.log('YES')
        }else{
            console.log('NO')
        }
    }
});

"use strict";
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let inputData = [];
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString = String(inputStdin);
});
process.stdin.on('end', () => {
    inputData = inputString.trim().split('\n').map(string => string.trim());
    main();
});
const readline = () => inputData[currentLine++];
const solve = (s) => {
    if (s.indexOf('r') > s.indexOf('R'))
        return "NO";
    if (s.indexOf('g') > s.indexOf('G'))
        return "NO";
    if (s.indexOf('b') > s.indexOf('B'))
        return "NO";
    return "YES";
};
const main = () => {
    let tc = parseInt(readline());
    while (tc--) {
        let s = readline();
        console.log(solve(s));
    }
};

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

    for(let i = 0; i < x; i++){
        debugger;
        let line2 = readline();
        doorKeys(line2);
    }
}

 function doorKeys(word) {
    let len = word.length;
    let kyes = [];

    for(let j = 0; j < len; j++) {
        let asciValue = word[j].charCodeAt(0);

        if(asciValue >= 97 && asciValue <= 122 ) {
            kyes.push(word[j]);
        } else {
           if(!kyes.includes(word[j].toLowerCase())) {
               console.log("NO");
               return;
           }
        }
    }
    console.log('YES');
 }

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

    let no = false;
    for (let test = 0; test < N; test++) {
        let str = readline();

        let I = {};
        for (let i = 0; i < str.length; i++) I[str[i]] = i;

        let red = I.r < I.R;
        let blue = I.b < I.B;
        let green = I.g < I.G;

        output((red && blue && green) ? 'YES' : 'NO');
    }
}

'use strict';

function solve(s) {
  let set = new Set();
  for (let ch of s) {
    const num = ch.charCodeAt(0);
    if (num > 97) {
      set.add(num - 32);
    } else {
      if (!set.has(num)) return 'NO';
    }
  }
  return 'YES';
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const s = await read();
      res[i] = solve(s);
    }
    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);
});

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 str = lines[l++]
        output[i] = solve(str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(str) {
    const map = {}
    for (let i = 0; i < str.length; i++) {
        const x = str[i]
        if (/[RGB]/.test(x)) {
            if (!map[x.toLowerCase()]) return 'NO'
        } else {
            map[x] = 1
        }
    }
    return 'YES'
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var S = next();
		var Key = "rgb";
		var Door = "RGB";
		var set = new Set();
		var ok = true;
		for(var i = 0; i < S.length; i++){
			if(Key.indexOf(S[i]) != -1){
				set.add(S[i].toUpperCase());
			}else{
				if(!set.has(S[i])){
					ok = false;
				}
			}
		}
		if(ok){
			myout("YES");
		}else{
			myout("NO");
		}
	}
}

/**
 * Author : Fazlul Hoque
 * Node.js version : 12.16.3
 * command : node fileName.js <input.txt >output.txt
 */
"use strict";
process.stdin.resume();
process.stdin.setEncoding("utf-8");
let inputString = ""; //An array of  raw inputs (includes 'n,\r , not usable. need to process before use)
let currentLine = 0; //input sequence controller variable.

process.stdin.on("data", (inputStdin) => {
    inputString += inputStdin;
});
process.stdin.on("end", () => {
    inputString = inputString.split("\n");
    main(); // after input
});

/********** Utility Functions Start **********/
/**
 *  read row Input
 * @returns string
 */
function _readRawLine() {
    return inputString[currentLine++];
}
function readLine(){
    // return _readRawLine().replace(/\s+$/g, '');
    return _readRawLine().replace('\r', '');
}

function print(x) {
    console.log(x);
}

function readSingleInt() {
    const p = readLine();
    return parseInt(p);
}

function readIntArray() {
    return readLine().split(" ").map((v) => parseInt(v));
}

function readArray() {
    return readLine().split(" ");
}

function int(n) {
    return parseInt(n);
}
/********** Utility Functions End **********/
/**
 * Don't Touch this fucntion at all , unless you know what are you doing!
 */
function main() {
    solve();
}

// ********** actual Code Starts from here **********

function processString(st=""){
    let r=false,g=false,b=false;
    const values = {
        r : false,
        g :false,
        b : false
    };
    for(let i=0;i<st.length;i++){
        if(st[i] == "R" || st[i]=="G" || st[i]=="B"){
            let small = st[i].toLowerCase();
            if(values[small]){
                continue;
            }else{
                return false;
            }
        }
        else{
            values[st[i]] = true;
        }
    }

    return true;
}
function solve() {

    const n = readSingleInt();
    let string;
    for(let i =0;i<n;i++){
        string=readLine();
        console.log(processString(string) ? "YES" : "NO");
    }
}

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0].split(' ');
    var answer = 0;
    for(var l = 1; l <= n; l++){
        var k = lines[l].split('');
        var rkey = false;
        var gkey = false;
        var bkey = false;
        var no = false;
        for(var j = 0; j < k.length; j++){
            if(k[j] == 'r'){
                rkey = true;
            }else if(k[j] == 'g'){
                gkey = true;
            }else if(k[j] == 'b'){
                bkey = true;
            }else if(k[j] == 'R' && rkey === false || k[j] == 'G' && gkey === false || k[j] == 'B' && bkey === false){
                no = true;
            }
        }
        if(!no){
            console.log('YES');
        }else{
            console.log('NO');
        }
    }
});

'use strict';
/* ================== */
process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

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

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

  main();
});

const readline = () => inputString[currentLine++];
const readline_arr = () => readline().split(' ').map((n) => parseInt(n, 10));
const print = (...txt) => process.stdout.write(`${txt}\n`)
/* ================== */

function main() {
  let t = parseInt(readline(), 10);
  while (t--) {
    solve();
  }
}

function solve() {
  const str = readline().split('');

  const keys = [];
  for (let i = 0; i < str.length; i++) {
    const p = str[i];
    if (p === p.toLowerCase()) {
      keys.push(p);
    } else {
      if (keys.some(k => k === p.toLowerCase())) {
        continue;
      } else {
        print('NO');
        return;
      }
    }
  };

  print('YES');
}

function solve(input) {
  let result = 'YES'
    // console.log('input: ', input)
  // for (let char of input) {
  //   console.log(char)
  // }
  const listStr = input.split('');
  const checkRr = listStr.filter(data => ['R', 'r'].includes(data))
  const checkGg = listStr.filter(data => ['G', 'g'].includes(data))
  const checkBb = listStr.filter(data => ['B', 'b'].includes(data))
  if (checkRr[0] === 'R' || checkGg[0] === 'G' || checkBb[0] === 'B') {
    result = 'NO'
  }
  console.log(result)
}

// =========== DEFAULT FORMAT ==============
const readline = require('readline').createInterface({ input: process.stdin });

let i = 1;
let t = 0;
readline.on('line', line => {
    if (i == 1) {
        // number of test case
        t = parseInt(line)
        i++;
    } else {
        solve(line)
        if (i <= t) i++
        else readline.close()
    }
});

// =========== DEFAULT FORMAT END ==============

doorsFilter = (arr)=> {
    return (arr.filter((e)=>{
                return e.toLowerCase() != arr[0];
            }));
};
var t = readline();
    for(var i = 0 ; i < t ; i++){
        var a = readline().split('');
        while(a.length >= 0){
            if(a.length === 0){
                print('YES');
                break;
            }
        if(a[0] == a[0].toLowerCase()){
            a = doorsFilter(a);
        }
        else{
            print('NO');
            break;
        }
    }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    console.log(lines);
    const inputCount = Number(lines.shift());
    const results = [];

    const checkInput = (input) => {
        const keys = [ 'r', 'g', 'b' ];
        const doors = [ 'R', 'G', 'B' ];
        const data = input.split('');
        return data.every(
            (element, index, array) =>
                doors.includes(element)
                    ? array.slice(0, index).includes(element.toLowerCase())
                    : true
        );
    };

    for (let inputData of lines) {
        results.push(checkInput(inputData));
    }

    for (var result of results) console.log(result ? 'YES' : 'NO');
})

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

    const inputCount = Number(lines.shift());
    const results = [];

    const checkInput = (input) => {
        const keys = [ 'r', 'g', 'b' ];
        const doors = [ 'R', 'G', 'B' ];
        const data = input.split('');
        return data.every(
            (element, index, array) =>
                doors.includes(element)
                    ? array.slice(0, index).includes(element.toLowerCase())
                    : true
        );
    };

    for (let inputData of lines) {
        results.push(checkInput(inputData));
    }

    for (var result of results) console.log(result ? 'YES' : 'NO');
})

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    var r = false
    var g = false
    var b = false
    var s = false
    for(j = 1; j<= n; j++){
        var a = lines[j].split('')
        for(k = 0; k < a.length; k++){
            if(a[k] == 'R' && r === false){
                s = false
            }else if(a[k] == 'G' && g === false){
                s = false
            }else if(a[k] == 'B' && b === false){
                s = false
            }else{
                s = true
            }
        }
        if(s === false){
            console.log('NO')
        }else{
            console.log('YES')
        }
    }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

    for(let i = 0; i < x; i++){
        debugger;
        let line2 = readline();
        doorKeys(line2);
    }
}

 function doorKeys(word) {
    let len = word.length;
    let kyes = [];

    for(let j = 0; j < len; j++) {
        let asciValue = word[j].charCodeAt(0);

        if(asciValue >= 97 && asciValue <= 122 ) {
            kyes.push(word[j]);
        } else {
           if(!kyes.includes(word[j].toLowerCase())) {
               console.log(false);
               return;
           }
        }
    }
    console.log(true);
 }


Arkady decided to buy roses for his girlfriend.A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color. Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose). Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of roses in the show and the number of roses Arkady wants to buy. The second line contains a sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 10 000), where bi equals the beauty of the i-th rose. The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O'  — orange, 'R' — red.

Print the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.

NoteIn the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11. In the second example Arkady can not buy a bouquet because all roses have the same color.

var array_length;

function heap_root(input, i) {
    var left = 2 * i + 1;
    var right = 2 * i + 2;
    var max = i;

    if (left < array_length && input[left] < input[max]) {
        max = left;
    }

    if (right < array_length && input[right] < input[max])     {
        max = right;
    }

    if (max != i) {
        swap(input, i, max);
        heap_root(input, max);
    }
}

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

function heapSort(input) {

    array_length = input.length;

    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
        heap_root(input, i);
      }

    for (i = input.length - 1; i > 0; i--) {
        swap(input, 0, i);
        array_length--;

        heap_root(input, 0);
    }
}

var temp = readline().split(" ").map(v => +v);
var n = temp[0];
var s = temp[1];

var b = readline().split(" ").map(v => +v);
var c = readline().split("");

var o = [];
var w = [];
var r = [];

for(var i = 0; i < b.length; i++){
    c[i] = c[i].trim();
    if(c[i] === "R") r.push(b[i]);
    else if(c[i] === "W") w.push(b[i]);
    else if(c[i] === "O") o.push(b[i]);
}

var sum_r = 0;
var sum_w = 0;
var white = w.length + o.length >= s && w.length > 0 && o.length > 0;
var red = r.length + o.length >= s && r.length > 0 && o.length > 0;

if((w.length === 0 && r.length === 0) || o.length === 0 || s == 1){
    print(-1);
}else{

    var wi = 0;
    var ri = 0;
    var oi = 0;
    var ori = 0;

    heapSort(r);
    heapSort(w);
    heapSort(o);

    if(white){
        sum_w +=o[oi++];
        sum_w +=w[wi++];
    }

    if(red){
        sum_r +=o[ori++];
        sum_r +=r[ri++];
    }

    for(var i = 1; i < s - 1; i++){
        if(white){
            if(wi < w.length && oi < o.length){
                if(w[wi] > o[oi]){
                    sum_w +=w[wi++];
                }else{
                    sum_w +=o[oi++];
                }
            }else if(wi < w.length){
                sum_w +=w[wi++];
            }else if(oi < o.length){
                sum_w +=o[oi++];
            }
        }

        if(red){
            if(ri < r.length && ori < o.length){
                if(r[ri] > o[ori]){
                    sum_r +=r[ri++];
                }else{
                    sum_r +=o[ori++];
                }
            }else if(ri < r.length){
                sum_r +=r[ri++];
            }else if(ori < o.length){
                sum_r +=o[ori++];
            }
        }
    }

    if(sum_r === 0 && sum_w === 0){
        print(-1);
    }else{
        print(sum_r > sum_w ? sum_r : sum_w);
    }

}

var array_length;

function heap_root(input, i) {
    var left = 2 * i + 1;
    var right = 2 * i + 2;
    var max = i;

    if (left < array_length && input[left] < input[max]) {
        max = left;
    }

    if (right < array_length && input[right] < input[max])     {
        max = right;
    }

    if (max != i) {
        swap(input, i, max);
        heap_root(input, max);
    }
}

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

function heapSort(input) {

    array_length = input.length;

    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
        heap_root(input, i);
      }

    for (i = input.length - 1; i > 0; i--) {
        swap(input, 0, i);
        array_length--;

        heap_root(input, 0);
    }
}

var temp = readline().split(" ").map(v => +v);
var n = temp[0];
var s = temp[1];

var b = readline().split(" ").map(v => +v);
var c = readline().split("");

var o = [];
var w = [];
var r = [];

for(var i = 0; i < b.length; i++){
    c[i] = c[i].trim();
    if(c[i] === "R") r.push(b[i]);
    else if(c[i] === "W") w.push(b[i]);
    else if(c[i] === "O") o.push(b[i]);
}

var sum_r = 0;
var sum_w = 0;
var white = w.length + o.length >= s && w.length > 0 && o.length > 0;
var red = r.length + o.length >= s && r.length > 0 && o.length > 0;

if((w.length === 0 && r.length === 0) || o.length === 0){
    print(-1);
}else{

    var wi = 0;
    var ri = 0;
    var oi = 0;
    var ori = 0;

    heapSort(r);
    heapSort(w);
    heapSort(o);

    if(white){
        sum_w +=o[oi++];
        sum_w +=w[wi++];
    }

    if(red){
        sum_r +=o[ori++];
        sum_r +=r[ri++];
    }

    for(var i = 1; i < s - 1; i++){
        if(white){
            if(wi < w.length && oi < o.length){
                if(w[wi] > o[oi]){
                    sum_w +=w[wi++];
                }else{
                    sum_w +=o[oi++];
                }
            }else if(wi < w.length){
                sum_w +=w[wi++];
            }else if(oi < o.length){
                sum_w +=o[oi++];
            }
        }

        if(red){
            if(ri < r.length && ori < o.length){
                if(r[ri] > o[ori]){
                    sum_r +=r[ri++];
                }else{
                    sum_r +=o[ori++];
                }
            }else if(ri < r.length){
                sum_r +=r[ri++];
            }else if(ori < o.length){
                sum_r +=o[ori++];
            }
        }
    }

    if(sum_r === 0 && sum_w === 0){
        print(-1);
    }else{
        print(sum_r > sum_w ? sum_r : sum_w);
    }

}

var array_length;

function heap_root(input, i) {
    var left = 2 * i + 1;
    var right = 2 * i + 2;
    var max = i;

    if (left < array_length && input[left] < input[max]) {
        max = left;
    }

    if (right < array_length && input[right] < input[max])     {
        max = right;
    }

    if (max != i) {
        swap(input, i, max);
        heap_root(input, max);
    }
}

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

function heapSort(input) {

    array_length = input.length;

    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
        heap_root(input, i);
      }

    for (i = input.length - 1; i > 0; i--) {
        swap(input, 0, i);
        array_length--;

        heap_root(input, 0);
    }
}

var temp = readline().split(" ").map(v => +v);
var n = temp[0];
var s = temp[1];

var b = readline().split(" ").map(v => +v);
var c = readline().split("");

var o = [];
var w = [];
var r = [];

for(var i = 0; i < b.length; i++){
    c[i] = c[i].trim();
    if(c[i] === "R") r.push(b[i]);
    else if(c[i] === "W") w.push(b[i]);
    else if(c[i] === "O") o.push(b[i]);
}

var sum_r = 0;
var sum_w = 0;
var white = w.length + o.length >= s && w.length > 0 && o.length > 0;
var red = r.length + o.length >= s && r.length > 0 && o.length > 0;

if((w.length === 0 && r.length === 0) || o.length === 0){
    print(-1);
}else{

    var wi = 0;
    var ri = 0;
    var oi = 0;
    var ori = 0;

    heapSort(r);
    heapSort(w);
    heapSort(o);

    if(white){
        sum_w +=o[oi++];
        sum_w +=w[wi++];
    }

    if(red){
        sum_r +=o[ori++];
        sum_r +=r[ri++];
    }

    for(var i = 1; i < s - 1; i++){
        if(white){
            if(wi < w.length && oi < o.length){
                if(w[wi] > o[oi]){
                    sum_w +=w[wi++];
                }else{
                    sum_w +=o[oi++];
                }
            }else if(wi < w.length){
                sum_w +=w[wi++];
            }else if(oi < o.length){
                sum_w +=o[oi++];
            }
        }

        if(red){
            if(ri < r.length && ori < o.length){
                if(r[ri] > o[ori]){
                    sum_r +=r[ri++];
                }else{
                    sum_r +=o[ori++];
                }
            }else if(ri < r.length){
                sum_r +=r[ri++];
            }else if(ori < o.length){
                sum_r +=o[ori++];
            }
        }
    }

    print(sum_r > sum_w ? sum_r : sum_w);
}

var array_length;

function heap_root(input, i) {
    var left = 2 * i + 1;
    var right = 2 * i + 2;
    var max = i;

    if (left < array_length && input[left] < input[max]) {
        max = left;
    }

    if (right < array_length && input[right] < input[max])     {
        max = right;
    }

    if (max != i) {
        swap(input, i, max);
        heap_root(input, max);
    }
}

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

function heapSort(input) {

    array_length = input.length;

    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
        heap_root(input, i);
      }

    for (i = input.length - 1; i > 0; i--) {
        swap(input, 0, i);
        array_length--;

        heap_root(input, 0);
    }
}

var temp = readline().split(" ").map(v => +v);
var n = temp[0];
var s = temp[1];

var b = readline().split(" ").map(v => +v);
var c = readline().split("");

var o = [];
var w = [];
var r = [];

for(var i = 0; i < b.length; i++){
    c[i] = c[i].trim();
    if(c[i] === "R") r.push(b[i]);
    else if(c[i] === "W") w.push(b[i]);
    else if(c[i] === "O") o.push(b[i]);
}

var sum_r = 0;
var sum_w = 0;
var white = w.length + o.length >= s;
var red = r.length + o.length >= s;

if((!white && !red) || o.length === 0){
    print(-1);
}else{

    var wi = 0;
    var ri = 0;
    var oi = 0;
    var ori = 0;

    heapSort(r);
    heapSort(w);
    heapSort(o);

    if(white){
        sum_w +=o[oi++];
    }

    if(red){
        sum_r +=o[ori++];
    }

    for(var i = 1; i < s; i++){
        if(white){
            if(wi < w.length && oi < o.length){
                if(w[wi] > o[oi]){
                    sum_w +=w[wi++];
                }else{
                    sum_w +=o[oi++];
                }
            }else if(wi < w.length){
                sum_w +=w[wi++];
            }else{
                sum_w +=o[oi++];
            }
        }

        if(red){
            if(ri < r.length && ori < o.length){
                if(r[ri] > o[ori]){
                    sum_r +=r[ri++];
                }else{
                    sum_r +=o[ori++];
                }
            }else if(ri < r.length){
                sum_r +=r[ri++];
            }else{
                sum_r +=o[ori++];
            }
        }

    }

    print(sum_r > sum_w ? sum_r : sum_w);
}

var array_length;

function heap_root(input, i) {
    var left = 2 * i + 1;
    var right = 2 * i + 2;
    var max = i;

    if (left < array_length && input[left] < input[max]) {
        max = left;
    }

    if (right < array_length && input[right] < input[max])     {
        max = right;
    }

    if (max != i) {
        swap(input, i, max);
        heap_root(input, max);
    }
}

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

function heapSort(input) {

    array_length = input.length;

    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
        heap_root(input, i);
      }

    for (i = input.length - 1; i > 0; i--) {
        swap(input, 0, i);
        array_length--;

        heap_root(input, 0);
    }
}

var temp = readline().split(" ").map(v => +v);
var n = temp[0];
var s = temp[1];

var b = readline().split(" ").map(v => +v);
var c = readline().split("");

var o = [];
var w = [];
var r = [];

for(var i = 0; i < b.length; i++){
    if(c[i] === "R") r.push(b[i]);
    else if(c[i] === "W") w.push(b[i]);
    else if(c[i] === "O") o.push(b[i]);
}

var sum_r = 0;
var sum_w = 0;
var white = w.length + o.length >= s;
var red = r.length + o.length >= s;

if((!white && !red) || o.length === 0 || (r.length === 0 && red) || (w.length === 0 && white)){
    print(-1);
}else{
    heapSort(r);
    heapSort(w);
    heapSort(o);

    var wi = 0;
    var ri = 0;
    var oi = 0;
    var ori = 0;

    if(white){
        sum_w +=o[oi++];
    }

    if(red){
        sum_r +=o[ori++];
    }

    for(var i = 1; i < s; i++){
        if(white){
            if(w[wi] !== undefined && o[oi] !== undefined){
                if(w[wi] > o[oi]){
                    sum_w +=w[wi++];
                }else{
                    sum_w +=o[oi++];
                }
            }else if(w[wi] !== undefined){
                sum_w +=w[wi++];
            }else{
                sum_w +=o[oi++];
            }
        }

        if(red){
            if(r[ri] !== undefined && o[ori] !== undefined){
                if(r[ri] > o[ori]){
                    sum_r +=r[ri++];
                }else{
                    sum_r +=o[ori++];
                }
            }else if(r[ri] !== undefined){
                sum_r +=r[ri++];
            }else{
                sum_r +=o[ori++];
            }
        }

    }

    print(sum_r > sum_w ? sum_r : sum_w);
}

var array_length;

function heap_root(input, i) {
    var left = 2 * i + 1;
    var right = 2 * i + 2;
    var max = i;

    if (left < array_length && input[left] < input[max]) {
        max = left;
    }

    if (right < array_length && input[right] < input[max])     {
        max = right;
    }

    if (max != i) {
        swap(input, i, max);
        heap_root(input, max);
    }
}

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

function heapSort(input) {

    array_length = input.length;

    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
        heap_root(input, i);
      }

    for (i = input.length - 1; i > 0; i--) {
        swap(input, 0, i);
        array_length--;

        heap_root(input, 0);
    }
}

var temp = readline().split(" ").map(v => +v);
var n = temp[0];
var s = temp[1];

var b = readline().split(" ").map(v => +v);
var c = readline().split("");

var o = [];
var w = [];
var r = [];

for(var i = 0; i < b.length; i++){
    if(c[i] === "R") r.push(b[i]);
    else if(c[i] === "W") w.push(b[i]);
    else if(c[i] === "O") o.push(b[i]);
}

var sum_r = 0;
var sum_w = 0;
var white = w.length + o.length >= s;
var red = r.length + o.length >= s;

if((!white && !red) || o.length === 0 || (r.length === 0 && red) || (w.length === 0 && white)){
    print(-1);
}else{
    heapSort(r);
    heapSort(w);
    heapSort(o);

    var wi = 0;
    var ri = 0;
    var oi = 0;
    var ori = 0;

    if(white){
        sum_w +=o[oi++];
    }

    if(red){
        sum_r +=o[ori++];
    }

    for(var i = 1; i < s; i++){
        if(white){
            if(wi < w.length && oi < o.length){
                if(w[wi] > o[oi]){
                    sum_w +=w[wi++];
                }else{
                    sum_w +=o[oi++];
                }
            }else if(wi < w.length){
                sum_w +=w[wi++];
            }else{
                sum_w +=o[oi++];
            }
        }

        if(red){
            if(ri < r.length && ori < o.length){
                if(r[ri] > o[ori]){
                    sum_r +=r[ri++];
                }else{
                    sum_r +=o[ori++];
                }
            }else if(ri < r.length){
                sum_r +=r[ri++];
            }else{
                sum_r +=o[ori++];
            }
        }

    }

    print(sum_r > sum_w ? sum_r : sum_w);
}

var array_length;

function heap_root(input, i) {
    var left = 2 * i + 1;
    var right = 2 * i + 2;
    var max = i;

    if (left < array_length && input[left] < input[max]) {
        max = left;
    }

    if (right < array_length && input[right] < input[max])     {
        max = right;
    }

    if (max != i) {
        swap(input, i, max);
        heap_root(input, max);
    }
}

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

function heapSort(input) {

    array_length = input.length;

    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
        heap_root(input, i);
      }

    for (i = input.length - 1; i > 0; i--) {
        swap(input, 0, i);
        array_length--;

        heap_root(input, 0);
    }
}

var temp = readline().split(" ").map(v => +v);
var n = temp[0];
var s = temp[1];

var b = readline().split(" ").map(v => +v);
var c = readline().split("");

var o = [];
var w = [];
var r = [];

for(var i = 0; i < b.length; i++){
    if(c[i] === "R") r.push(b[i]);
    else if(c[i] === "W") w.push(b[i]);
    else if(c[i] === "O") o.push(b[i]);
}

var sum_r = 0;
var sum_w = 0;
var white = w.length + o.length >= s;
var red = r.length + o.length >= s;

    heapSort(r);
    heapSort(w);
    heapSort(o);

if((!white && !red) || o.length === 0 || (r.length === 0 && red) || (w.length === 0 && white)){
    print(-1);
}else{

    var wi = 0;
    var ri = 0;
    var oi = 0;
    var ori = 0;

    if(white){
        sum_w +=o[oi++];
    }

    if(red){
        sum_r +=o[ori++];
    }

    for(var i = 1; i < s; i++){
        if(white){
            if(wi < w.length && oi < o.length){
                if(w[wi] > o[oi]){
                    sum_w +=w[wi++];
                }else{
                    sum_w +=o[oi++];
                }
            }else if(wi < w.length){
                sum_w +=w[wi++];
            }else{
                sum_w +=o[oi++];
            }
        }

        if(red){
            if(ri < r.length && ori < o.length){
                if(r[ri] > o[ori]){
                    sum_r +=r[ri++];
                }else{
                    sum_r +=o[ori++];
                }
            }else if(ri < r.length){
                sum_r +=r[ri++];
            }else{
                sum_r +=o[ori++];
            }
        }

    }

    print(sum_r > sum_w ? sum_r : sum_w);
}

var array_length;

function heap_root(input, i) {
    var left = 2 * i + 1;
    var right = 2 * i + 2;
    var max = i;

    if (left < array_length && input[left] < input[max]) {
        max = left;
    }

    if (right < array_length && input[right] < input[max])     {
        max = right;
    }

    if (max != i) {
        swap(input, i, max);
        heap_root(input, max);
    }
}

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

function heapSort(input) {

    array_length = input.length;

    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
        heap_root(input, i);
      }

    for (i = input.length - 1; i > 0; i--) {
        swap(input, 0, i);
        array_length--;

        heap_root(input, 0);
    }
}

var temp = readline().split(" ").map(v => +v);
var n = temp[0];
var s = temp[1];

var b = readline().split(" ").map(v => +v);
var c = readline().split("");

var o = [];
var w = [];
var r = [];

for(var i = 0; i < b.length; i++){
    c[i] = c[i].trim();
    if(c[i] === "R") r.push(b[i]);
    else if(c[i] === "W") w.push(b[i]);
    else if(c[i] === "O") o.push(b[i]);
}

var sum_r = 0;
var sum_w = 0;
var white = w.length + o.length >= s;
var red = r.length + o.length >= s;

if((!white && !red) || o.length === 0){
    print(-1);
}else{

    var wi = 0;
    var ri = 0;
    var oi = 0;
    var ori = 0;

    heapSort(r);
    heapSort(w);
    heapSort(o);

    if(white){
        sum_w +=o[oi++];
        sum_w +=w[wi++];
    }

    if(red){
        sum_r +=o[ori++];
        sum_r +=r[ri++];
    }

    for(var i = 1; i < s; i++){
        if(white){
            if(wi < w.length && oi < o.length){
                if(w[wi] > o[oi]){
                    sum_w +=w[wi++];
                }else{
                    sum_w +=o[oi++];
                }
            }else if(wi < w.length){
                sum_w +=w[wi++];
            }else{
                sum_w +=o[oi++];
            }
        }

        if(red){
            if(ri < r.length && ori < o.length){
                if(r[ri] > o[ori]){
                    sum_r +=r[ri++];
                }else{
                    sum_r +=o[ori++];
                }
            }else if(ri < r.length){
                sum_r +=r[ri++];
            }else{
                sum_r +=o[ori++];
            }
        }

    }

    print(sum_r > sum_w ? sum_r : sum_w);
}

var array_length;

function heap_root(input, i) {
    var left = 2 * i + 1;
    var right = 2 * i + 2;
    var max = i;

    if (left < array_length && input[left] < input[max]) {
        max = left;
    }

    if (right < array_length && input[right] < input[max])     {
        max = right;
    }

    if (max != i) {
        swap(input, i, max);
        heap_root(input, max);
    }
}

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

function heapSort(input) {

    array_length = input.length;

    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
        heap_root(input, i);
      }

    for (i = input.length - 1; i > 0; i--) {
        swap(input, 0, i);
        array_length--;

        heap_root(input, 0);
    }
}

var temp = readline().split(" ").map(v => +v);
var n = temp[0];
var s = temp[1];

var b = readline().split(" ").map(v => +v);
var c = readline().split("");

var o = [];
var w = [];
var r = [];

for(var i = 0; i < b.length; i++){
    if(c[i] === "R") r.push(b[i]);
    else if(c[i] === "W") w.push(b[i]);
    else if(c[i] === "O") o.push(b[i]);
}

heapSort(r);
heapSort(w);
heapSort(o);

var sum_r = 0;
var sum_w = 0;
var white = w.length + o.length >= s;
var red = r.length + o.length >= s;

var wi = 0;
var ri = 0;
var oi = 0;
var ori = 0;

if((!white && !red) || o.length === 0 || (o.length > 0 && r.length === 0 && red) || (o.length > 0 && w.length === 0 && white)){
    print(-1);
}else{
    for(var i = 0; i < s; i++){
        if(white){
            if(w[wi] !== undefined && o[oi] !== undefined){
                if(w[wi] > o[oi]){
                    sum_w +=w[wi++];
                }else{
                    sum_w +=o[oi++];
                }
            }else if(w[wi] !== undefined){
                sum_w +=w[wi++];
            }else{
                sum_w +=o[oi++];
            }
        }

        if(red){
            if(r[ri] !== undefined && o[ori] !== undefined){
                if(r[ri] > o[ori]){
                    sum_r +=r[ri++];
                }else{
                    sum_r +=o[ori++];
                }
            }else if(r[ri] !== undefined){
                sum_r +=r[ri++];
            }else{
                sum_r +=o[ori++];
            }
        }

    }

    print(sum_r > sum_w ? sum_r : sum_w);
}

var array_length;

function heap_root(input, i) {
    var left = 2 * i + 1;
    var right = 2 * i + 2;
    var max = i;

    if (left < array_length && input[left] < input[max]) {
        max = left;
    }

    if (right < array_length && input[right] < input[max])     {
        max = right;
    }

    if (max != i) {
        swap(input, i, max);
        heap_root(input, max);
    }
}

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

function heapSort(input) {

    array_length = input.length;

    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
        heap_root(input, i);
      }

    for (i = input.length - 1; i > 0; i--) {
        swap(input, 0, i);
        array_length--;

        heap_root(input, 0);
    }
}

var temp = readline().split(" ").map(v => +v);
var n = temp[0];
var s = temp[1];

var b = readline().split(" ").map(v => +v);
var c = readline().split("");

var o = [];
var w = [];
var r = [];

for(var i = 0; i < b.length; i++){
    if(c[i] === "R") r.push(b[i]);
    else if(c[i] === "W") w.push(b[i]);
    else if(c[i] === "O") o.push(b[i]);
}

var sum_r = 0;
var sum_w = 0;
var white = w.length + o.length >= s;
var red = r.length + o.length >= s;

if((!white && !red) || o.length === 0 || (r.length === 0 && red) || (w.length === 0 && white)){
    print(-1);
}else{
    heapSort(r);
    heapSort(w);
    heapSort(o);

    var wi = 0;
    var ri = 0;
    var oi = 0;
    var ori = 0;

    for(var i = 0; i < s; i++){
        if(white){
            if(w[wi] !== undefined && o[oi] !== undefined){
                if(w[wi] > o[oi]){
                    sum_w +=w[wi++];
                }else{
                    sum_w +=o[oi++];
                }
            }else if(w[wi] !== undefined){
                sum_w +=w[wi++];
            }else{
                sum_w +=o[oi++];
            }
        }

        if(red){
            if(r[ri] !== undefined && o[ori] !== undefined){
                if(r[ri] > o[ori]){
                    sum_r +=r[ri++];
                }else{
                    sum_r +=o[ori++];
                }
            }else if(r[ri] !== undefined){
                sum_r +=r[ri++];
            }else{
                sum_r +=o[ori++];
            }
        }

    }

    print(sum_r > sum_w ? sum_r : sum_w);
}

var array_length;

function heap_root(input, i) {
    var left = 2 * i + 1;
    var right = 2 * i + 2;
    var max = i;

    if (left < array_length && input[left] < input[max]) {
        max = left;
    }

    if (right < array_length && input[right] < input[max])     {
        max = right;
    }

    if (max != i) {
        swap(input, i, max);
        heap_root(input, max);
    }
}

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

function heapSort(input) {

    array_length = input.length;

    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
        heap_root(input, i);
      }

    for (i = input.length - 1; i > 0; i--) {
        swap(input, 0, i);
        array_length--;

        heap_root(input, 0);
    }
}

var temp = readline().split(" ").map(v => +v);
var n = temp[0];
var s = temp[1];

var b = readline().split(" ").map(v => +v);
var c = readline().split("");

var o = [];
var w = [];
var r = [];

for(var i = 0; i < b.length; i++){
    c[i] = c[i].trim();
    if(c[i] === "R") r.push(b[i]);
    else if(c[i] === "W") w.push(b[i]);
    else if(c[i] === "O") o.push(b[i]);
}

var sum_r = 0;
var sum_w = 0;
var white = w.length + o.length >= s && w.length > 0 && o.length > 0;
var red = r.length + o.length >= s && r.length > 0 && o.length > 0;

if((w.length === 0 && r.length === 0) || o.length === 0){
    print(-1);
}else{

    var wi = 0;
    var ri = 0;
    var oi = 0;
    var ori = 0;

    heapSort(r);
    heapSort(w);
    heapSort(o);

    if(white){
        sum_w +=o[oi++];
        sum_w +=w[wi++];
    }

    if(red){
        sum_r +=o[ori++];
        sum_r +=r[ri++];
    }

    for(var i = 1; i < s; i++){
        if(white){
            if(wi < w.length && oi < o.length){
                if(w[wi] > o[oi]){
                    sum_w +=w[wi++];
                }else{
                    sum_w +=o[oi++];
                }
            }else if(wi < w.length){
                sum_w +=w[wi++];
            }else if(oi < o.length){
                sum_w +=o[oi++];
            }
        }

        if(red){
            if(ri < r.length && ori < o.length){
                if(r[ri] > o[ori]){
                    sum_r +=r[ri++];
                }else{
                    sum_r +=o[ori++];
                }
            }else if(ri < r.length){
                sum_r +=r[ri++];
            }else if(ori < o.length){
                sum_r +=o[ori++];
            }
        }
    }

    print(sum_r > sum_w ? sum_r : sum_w);
}


Hosssam decided to sneak into Hemose's room while he is sleeping and change his laptop's password. He already knows the password, which is a string $$$s$$$ of length $$$n$$$. He also knows that there are $$$k$$$ special letters of the alphabet: $$$c_1,c_2,\ldots, c_k$$$.Hosssam made a program that can do the following.  The program considers the current password $$$s$$$ of some length $$$m$$$.  Then it finds all positions $$$i$$$ ($$$1\le i<m$$$) such that $$$s_{i+1}$$$ is one of the $$$k$$$ special letters.  Then it deletes all of those positions from the password $$$s$$$ even if $$$s_{i}$$$ is a special character. If there are no positions to delete, then the program displays an error message which has a very loud sound. For example, suppose the string $$$s$$$ is "abcdef" and the special characters are 'b' and 'd'. If he runs the program once, the positions $$$1$$$ and $$$3$$$ will be deleted as they come before special characters, so the password becomes "bdef". If he runs the program again, it deletes position $$$1$$$, and the password becomes "def". If he is wise, he won't run it a third time.Hosssam wants to know how many times he can run the program on Hemose's laptop without waking him up from the sound of the error message. Can you help him?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the initial length of the password. The next line contains a string $$$s$$$ consisting of $$$n$$$ lowercase English letters — the initial password. The next line contains an integer $$$k$$$ ($$$1 \le k \le 26$$$), followed by $$$k$$$ distinct lowercase letters $$$c_1,c_2,\ldots,c_k$$$ — the special letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print the maximum number of times Hosssam can run the program without displaying the error message, on a new line.

10

9

iloveslim

1 s

7

joobeel

2 o e

7

basiozi

2 s i

6

khater

1 r

7

abobeih

6 a b e h i o

5

zondl

5 a b c e f

6

shoman

2 a h

7

shetwey

2 h y

5

samez

1 m

6

mouraz

1 m

NoteIn the first test case, the program can run $$$5$$$ times as follows: $$$\text{iloveslim} \to \text{ilovslim} \to \text{iloslim} \to \text{ilslim} \to \text{islim} \to \text{slim}$$$In the second test case, the program can run $$$2$$$ times as follows: $$$\text{joobeel} \to \text{oel} \to \text{el}$$$In the third test case, the program can run $$$3$$$ times as follows: $$$\text{basiozi} \to \text{bioi} \to \text{ii} \to \text{i}$$$.In the fourth test case, the program can run $$$5$$$ times as follows: $$$\text{khater} \to \text{khatr} \to \text{khar} \to \text{khr} \to \text{kr} \to \text{r}$$$In the fifth test case, the program can run only once as follows: $$$\text{abobeih} \to \text{h}$$$In the sixth test case, the program cannot run as none of the characters in the password is a special character.

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

function solve(n, str, arr) {
    const map = arr.reduce((o, x) => {
        o.set(x, 1)
        return o
    }, new Map())
    let last = -1
    let ans = 0
    for (let i = str.length - 1; i >= 0; i--) {
        ans = Math.max(ans, last < 0 ? -Infinity : last - i)
        if (map.get(str[i])) last = i
    }
    return ans
}

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

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

/*---------------------------------------------------*/

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

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

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

/*---------------------------------------------------*/

const calc = (n, s, a)=>{
    let res = 0;

    let map = new Set(a);

    let prev = -1;
    for (let i = 0; i < n - 1; i++) {
        if (map.has(s[i + 1])) {
            res = Math.max(res, i - prev);
            prev = i;
        }
    }

    return res;
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let s = readline();
        let a = readline().split(' ').slice(1);
        out.push(calc(n, s, a));
        // console.log(`${calc(n, s, k, a)}`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}
//var alpha = []
var num = []
function alph() {
  var g = []
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var g = []
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  for(var x=0;x<f.length;x++) {
    num[f[x]] = x+1;
    alpha[x+1] = f[x];
  }
  //return g;
}
function max(x,y) {
  return x >=y ? x : y;
}
var T = readline();
for(var q=1;q<=T;q++) {
  var n = readline();
  var s = readline();
  var r = readline().split(' ');
  var alpha = alph();
  var spec = []
  var id = 0;
  var move = 0;
  var m = new Map();
  for(var i=0;i<26;i++) {
    m.set(alpha[i], false);
  }
  for(var i=1;i<=r[0];i++) {
    m.set(r[i], true);
  }
  //console.log(m)

  for(var i=1;i<n;i++) {
    if(m.get(s[i]) === true) {
      if(i-id > move) {
        move = max(move, i-id);
        id = i;
      } else {
        id = i;
      }
    }
  }
  console.log(move);
  //fs.appendFileSync('output.txt', move+'\r\n');

  //os.EOL
}

'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 = ()=>{
  let RESULT = [];
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      RESULT.push(calc(T));
  } else
   pcalc();
   process.stdout.write(RESULT.join('\n')+'\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(`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] = ra();
  let s = readline();
  let K = readline().split(' ');
  let k = +K[0];
  K = new Set(K.slice(1));
  LT({n, s, k, K});
  // PROCESSING:
  let lastPos = -1;
  for (let i=n-1; i>=0; i--){
    if (K.has(s[i])){
      lastPos = i;
      break;
    }
  }
  if (lastPos==-1)
    return 0;
  let cnt = 0;
  let max = 0;
  for (let i=lastPos-1; i>=0; i--){
    if (K.has(s[i+1]))
      cnt = 1;
    else
      cnt++;
    max = Math.max(max, cnt)
  }
  return max
};

'use strict';

var readline = require('readline');

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

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

function solve(n, s, k, b) {
  let pre = 0,
      max = 0;
  const set = new Set(b);
  for (let i = 0; i < n; i++) {
    if (set.has(s[i])) {
      max = Math.max(i - pre, max);
      pre = i;
    }
  }
  return max;
}

async function main(read) {
  let t = Number(await read());
  let res = [];
  while (t--) {
    const n = Number(await read());
    const s = await read();
    const s2 = await read();
    const k = Number(s2[0]);
    const b = s2.slice(2).split(' ');
    res.push(solve(n, s, k, b));
  }
  console.log(res.join('\n'));
}

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

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

function solve(n, str, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i += 2) {
        map[arr[i]] = 1
    }
    // const map = arr.reduce((o, x) => {
    //     o[x] = 1
    //     return o
    // }, {})
    let last = -1
    let ans = 0
    for (let i = str.length - 1; i >= 0; i--) {
        ans = Math.max(ans, last < 0 ? -Infinity : last - i)
        if (map[str[i]]) last = i
        // if (last >= 0 && last <= ans) break
    }
    return 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 = +lines[l++]
        const str = lines[l++]
        const arr = lines[l++]//.trim().split(' ')
        output[i] = solve(n, str, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, str, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i += 2) {
        map[arr[i]] = 1
    }
    // const map = arr.reduce((o, x) => {
    //     o[x] = 1
    //     return o
    // }, {})
    let last = -1
    let ans = 0
    for (let i = str.length - 1; i >= 0; i--) {
        ans = Math.max(ans, last < 0 ? -Infinity : last - i)
        if (map[str[i]]) last = i
        // if (last >= 0 && last <= ans) break
    }
    return 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 = +lines[l++]
        const str = lines[l++]
        const arr = lines[l++].trim()//.split(' ')
        output[i] = solve(n, str, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, str, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i += 2) {
        map[arr[i]] = 1
    }
    // console.log(map)
    let last = -Infinity
    let ans = 0
    for (let i = str.length - 1; i >= 0; i--) {
        if (last - i > ans) {
            ans = last - i
        }
        // ans = Math.max(ans, last < 0 ? -Infinity : last - i)
        if (map[str[i]]) last = i
        // if (last >= 0 && last <= ans) break
    }
    return 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 = +lines[l++]
        const str = lines[l++]
        const arr = lines[l++]//.trim().split(' ')
        output[i] = solve(n, str, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, str, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i += 2) {
        map[arr[i]] = 1
    }
    // console.log(map)
    let last = -Infinity
    let ans = 0
    for (let i = str.length - 1; i >= 0; i--) {
        // if (last - i > ans) {
        //     ans = last - i
        // }
        ans = Math.max(ans, last < 0 ? -Infinity : last - i)
        if (map[str[i]]) last = i
        // if (last >= 0 && last <= ans) break
    }
    return 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 = +lines[l++]
        const str = lines[l++]
        const arr = lines[l++]//.trim().split(' ')
        output[i] = solve(n, str, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, str, arr) {
    const map = {}
    for (let i = 0; i < arr.length; i += 2) {
        map[arr[i]] = 1
    }
    // console.log(map)
    let last = -Infinity
    let ans = 0
    for (let i = str.length - 1; i >= 0; i--) {
        if (last - i > ans) {
            ans = last - i
        }
        // ans = Math.max(ans, last < 0 ? -Infinity : last - i)
        if (map[str[i]]) last = i
        // if (last >= 0 && last <= ans) break
    }
    return ans
}