One day Prof. Slim decided to leave the kingdom of the GUC to join the kingdom of the GIU. He was given an easy online assessment to solve before joining the GIU. Citizens of the GUC were happy sad to see the prof leaving, so they decided to hack into the system and change the online assessment into a harder one so that he stays at the GUC. After a long argument, they decided to change it into the following problem.Given an array of $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$, where $$$a_{i} \neq 0$$$, check if you can make this array sorted by using the following operation any number of times (possibly zero). An array is sorted if its elements are arranged in a non-decreasing order.  select two indices $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$) such that $$$a_i$$$ and $$$a_j$$$ have different signs. In other words, one must be positive and one must be negative.  swap the signs of $$$a_{i}$$$ and $$$a_{j}$$$. For example if you select $$$a_i=3$$$ and $$$a_j=-2$$$, then they will change to $$$a_i=-3$$$ and $$$a_j=2$$$. Prof. Slim saw that the problem is still too easy and isn't worth his time, so he decided to give it to you to solve.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the length of the array $$$a$$$. The next line contain $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_{i} \le 10^9$$$, $$$a_{i} \neq 0$$$) separated by spaces describing elements of the array $$$a$$$.  It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, print "YES" if the array can be sorted in the non-decreasing order, otherwise print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test case, there is no way to make the array sorted using the operation any number of times.In the second test case, the array is already sorted.In the third test case, we can swap the sign of the $$$1$$$-st element with the sign of the $$$5$$$-th element, and the sign of the $$$3$$$-rd element with the sign of the $$$6$$$-th element, this way the array will be sorted.In the fourth test case, there is no way to make the array sorted using the operation any number of times.

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() {
  let t = parseInt(readLine());

  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let arr = readLine().split(" ").map(Number);

    let cntNegative = 0,
      ispresent = 0;
    for (let x of arr) {
      if (x < 0) {
        cntNegative++;
        ispresent = 1;
      }
    }

    let j = 0;
    for (let i = 0; i < arr.length; i++) {
      if (cntNegative > 0 && arr[i] > 0) {
        arr[i] *= -1;
        cntNegative--;
        j = i;
      } else if (cntNegative > 0 && arr[i] < 0) {
        cntNegative--;
        j = i;
      }
    }

    for (let k = j + 1; ispresent && k < arr.length; k++) {
      if (arr[k] < 0) {
        arr[k] *= -1;
      }
    }
    let flag = 0;
    for (let i = 1; i < arr.length; i++) {
      if (arr[i - 1] > arr[i]) {
        console.log("NO");
        flag = 1;
        break;
      }
    }

    if (flag == 0) {
      console.log("YES");
    }
  }
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}
var alpha = []
var num = []
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 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;
}
var T = readline();
for(var q=1;q<=T;q++) {
  var n = readline();
  //var n = a.length;
  var a = readline().split(' ').map((x)=> parseInt(x))
  var j = 0;
  for(var i=n-1;i>=0 && i>j;i--) {
    if(a[i] < 0) {
      if(a[j] > 0) {
        a[j] = a[j] * (-1);
        a[i] = a[i] * (-1)
        j++;
      } else {
        //if(q == 3) console.log([a[i],a[j]])
        while(a[j] < 0 && j < n) j++;
        if(i <= j) continue;
        if(j < n && a[j] > 0) {
          //if(q == 3) console.log([a[i],a[j]])
          a[j] = a[j] * (-1)
          a[i] = a[i] * (-1)
          j++;
        }

      }
    }
  }
  var ok = true;
  for(var i=1;i<n;i++) {
    if(a[i] < a[i-1]) {
      ok = false;
      break;
    }
  }
  var ans = ok ? 'YES' : 'NO';
  console.log(ans);
  //fs.appendFileSync('output.txt', ans+'\r\n');

  //os.EOL
}

'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, a) {
  for (let i = n - 1, j = n - 2; i >= 0; i--) {
    var _a2;
    if (a[i] < 0) {
      var _a;
      if (Math.abs(a[i]) <= ((_a = a[i + 1]) !== null && _a !== void 0 ? _a : Infinity)) {
        if (j >= i) j = i - 1;
        while (j >= 0 && a[j] < 0) {
          j--;
        }
        if (j >= 0) {
          a[i] = -a[i];
          a[j] = -a[j];
        }
      }
    }
    if (a[i] > ((_a2 = a[i + 1]) !== null && _a2 !== void 0 ? _a2 : Infinity)) {
      console.log('NO');
      return;
    }
  }
  console.log('YES');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

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

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

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

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);

        let neg = arr.filter(n => n < 0).length;

        const getNum = k => {
            let num = Math.abs(arr[k]);
            if (k < neg) {
                num = -num;
            }
            return num;
        }

        let no = false;
        for (let i = 0; i < arr.length; i++) {
            let num = getNum(i);
            if (i > 0 && num < getNum(i - 1)) {
                no = true;
                break;
            }
        }

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

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

function solve(n, arr) {
    let i = 0
    let j = n - 1
    while (i < j) {
        while (i < j) {
            if (arr[i] > 0) break
            i++
        }
        while (i < j) {
            if (arr[j] < 0) break
            j--
        }
        if (i > j) break
        arr[i] = -arr[i]
        arr[j] = -arr[j]
        i++; j--
    }
// console.log(arr)
    for (i = 1; i < arr.length; i++) {
        if (arr[i] < arr[i - 1]) return 'NO'
    }
    return 'YES'
}

/*
 * File Created: Thursday, 11th February 2021 1:42:08 pm
 * Author: Lukas Rimkus
 */
'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const n = data.shift();
        const arr = data.shift().split(' ').map(Number);

        console.log(a(n,arr));
    }
});

function get_ints() {
    return data[currentLine++].split(' ').map(Number);
}

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

function a(n,arr){
    let k = 0;
    let j = 0;
    for(let i = 0 ; i < n; i++){
        if(arr[i] < 0){
            arr[j++] *= -1;
            arr[i] *= -1;
        }
    }
    if(isSorted(arr)) {
        return 'YES';
    } else {
        return 'NO'
    }
}

function isSorted(arr){
    for(let i = 0 ; i < arr.length - 1; i++){
        if(arr[i] > arr[i+1]) return false;
    }
    return true;
}

module.exports = a;

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

let ls = [];

function solve() {
    let l = 0;
    let t = parseInt(ls[l++]);
    for (; t > 0; t--){
        const n = parseInt(ls[l++]);
        const a = ls[l++].split(' ').map(it => parseInt(it));
        let j = 0;
        for (let i = 0; i < n; i++){
            if (a[i] < 0){
                a[j++] *= -1;
                a[i] *= -1;
            }
        }

        let isSorted = true;
        for (let i = 1; i < n; i++){
            if (a[i] < a[i - 1]){
                isSorted = false;
                break;
            }
        }

        if (isSorted){
            console.log('YES');
        }
        else{
            console.log('NO');
        }
    }
}

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

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, a)=>{
    let neg = 0;
    let pos = 0;

    for (let i = 0; i < n; i++) {
        if (a[i] < 0) neg++;
        else pos++;
    }

    for (let i = 0; i < n; i++) {
        if (i < neg && a[i] > 0) {
            a[i] = -a[i];
        }
        if (i >= neg && a[i] < 0) {
            a[i] = -a[i];
        }
        if (i > 0 && a[i] < a[i - 1]) return 'NO';
    }

    return 'YES';
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        // let [n, k] = ra();
        let a = ra();
        console.log(`${calc(n, a)}`);
    }
}

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

function Main(){
    // input in nodeJs
	var t = nextInt();
	while(hasNext()){
		solve();
	}
}

function solve() {
    const size = nextInt();
    const arr = nextIntArray(size);

    let negative = 0;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] < 0) {
            negative++;
        }
    }

    for (let i = 0; i < arr.length; i++) {

        if (negative > 0) {
            arr[i] = -Math.abs(arr[i]);
            negative--;
        } else if (negative === 0) {
            arr[i] = Math.abs(arr[i]);
        }
    }

    for (let i = 0; i < arr.length-1; i++) {
        if (arr[i] > arr[i+1]) {
            myout("NO");
            return;
        }
    }

    myout("YES")
}

'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] = ra();
  let A = ra();
  LT({n, A});

  // PROCESSING:
  let minuses = 0;
  for (let i=0; i<n; i++)
    if (A[i]<0)
      minuses++;
  for (let i=0; i<n; i++){
    if (i<minuses){
      A[i] = -Math.abs(A[i])
    } else
      A[i] = Math.abs(A[i])
  }
  for (let i=0; i<n-1; i++){
    if (A[i]>A[i+1])
      return 'NO'
  }
  return 'YES';
};

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() {
  let t = parseInt(readLine());

  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let arr = readLine().split(" ").map(Number);

    let cntNegative = 0,
      ispresent = 0;
    for (let x of arr) {
      if (x < 0) {
        cntNegative++;
        ispresent = 1;
      }
    }

    let j = 0;
    for (let i = 0; i < arr.length; i++) {
      if (cntNegative > 0 && arr[i] > 0) {
        arr[i] *= -1;
        cntNegative--;
        j = i;
      } else if (cntNegative > 0 && arr[i] < 0) {
        cntNegative--;
        j = i;
      }
    }

    for (let k = j + 1; ispresent && k < arr.length; k++) {
      if (arr[i] < 0) {
        arr[k] *= -1;
      }
    }
    let flag = 0;
    for (let i = 1; i < arr.length; i++) {
      if (arr[i - 1] > arr[i]) {
        console.log("NO");
        flag = 1;
        break;
      }
    }

    if (flag == 0) {
      console.log("YES");
    }
  }
}

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() {
  let t = parseInt(readLine());

  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let arr = readLine().split(" ").map(Number);

    let cntNegative = 0,
      ispresent = 0;
    for (let x of arr) {
      if (x < 0) {
        cntNegative++;
        ispresent = 1;
      }
    }

    let j = 0;
    for (let i = 0; i < arr.length; i++) {
      if (cntNegative > 0 && arr[i] > 0) {
        arr[i] *= -1;
        cntNegative--;
        j = i;
      } else if (cntNegative > 0 && arr[i] < 0) {
        cntNegative--;
        j = i;
      }
    }

    for (let k = j + 1; ispresent && k < arr.length; k++) {
      arr[k] *= -1;
    }
    let flag = 0;
    for (let i = 1; i < arr.length; i++) {
      if (arr[i - 1] > arr[i]) {
        console.log("NO");
        flag = 1;
        break;
      }
    }

    if (flag == 0) {
      console.log("YES");
    }
  }
}

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';
  for(var x=0;x<f.length;x++) {
    num[f[x]] = x+1;
    alpha[x+1] = f[x]
  }
  //return g;
}
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;
}
var T = readline();
for(var q=1;q<=T;q++) {
  var n = readline();
  //var n = a.length;
  var a = readline().split(' ').map((x)=> parseInt(x))
  var j = 0;
  for(var i=n-1;i>=0 && i>j;i--) {
    if(a[i] < 0) {
      if(a[j] > 0) {
        a[j] = a[j] * (-1);
        a[i] = a[i] * (-1)
        j++;
      } else {
        //if(q == 3) console.log([a[i],a[j]])
        while(a[j] < 0 && j < n) j++;
        if(j < n && a[j] > 0) {
          //if(q == 3) console.log([a[i],a[j]])
          a[j] = a[j] * (-1)
          a[i] = a[i] * (-1)
          j++;
        }
      }
    }
  }
  var ok = true;
  for(var i=1;i<n;i++) {
    if(a[i] < a[i-1]) {
      ok = false;
      break;
    }
  }
  var ans = ok ? 'YES' : 'NO';
  console.log(ans);
  //fs.appendFileSync('output.txt', ans+'\r\n');

  //os.EOL
}

'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, a) {
  for (let i = n - 1, j = n - 2; i >= 0; i--) {
    var _a2;
    if (a[i] < 0) {
      var _a;
      if (Math.abs(a[i]) < ((_a = a[i + 1]) !== null && _a !== void 0 ? _a : Infinity)) {
        if (j >= i) j = i - 1;
        while (j >= 0 && a[j] < 0) {
          j--;
        }
        if (j >= 0) {
          a[i] = -a[i];
          a[j] = -a[j];
        }
      }
    }
    if (a[i] > ((_a2 = a[i + 1]) !== null && _a2 !== void 0 ? _a2 : Infinity)) {
      console.log('NO');
      return;
    }
  }
  console.log('YES');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = (await read()).split(' ').map(Number);
    solve(n, a);
  }
}

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


The cuteness of a binary string is the number of $$$\texttt{1}$$$s divided by the length of the string. For example, the cuteness of $$$\texttt{01101}$$$ is $$$\frac{3}{5}$$$.Juju has a binary string $$$s$$$ of length $$$n$$$. She wants to choose some non-intersecting subsegments of $$$s$$$ such that their concatenation has length $$$m$$$ and it has the same cuteness as the string $$$s$$$. More specifically, she wants to find two arrays $$$l$$$ and $$$r$$$ of equal length $$$k$$$ such that $$$1 \leq l_1 \leq r_1 < l_2 \leq r_2 < \ldots < l_k \leq r_k \leq n$$$, and also:  $$$\sum\limits_{i=1}^k (r_i - l_i + 1) = m$$$;  The cuteness of $$$s[l_1,r_1]+s[l_2,r_2]+\ldots+s[l_k,r_k]$$$ is equal to the cuteness of $$$s$$$, where $$$s[x, y]$$$ denotes the subsegment $$$s_x s_{x+1} \ldots s_y$$$, and $$$+$$$ denotes string concatenation. Juju does not like splitting the string into many parts, so she also wants to minimize the value of $$$k$$$. Find the minimum value of $$$k$$$ such that there exist $$$l$$$ and $$$r$$$ that satisfy the constraints above or determine that it is impossible to find such $$$l$$$ and $$$r$$$ for any $$$k$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq m \leq n \leq 2 \cdot 10^5$$$). The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, if there is no valid pair of $$$l$$$ and $$$r$$$, print $$$-1$$$.  Otherwise, print $$$k + 1$$$ lines. In the first line, print a number $$$k$$$ ($$$1 \leq k \leq m$$$) — the minimum number of subsegments required. Then print $$$k$$$ lines, the $$$i$$$-th should contain $$$l_i$$$ and $$$r_i$$$ ($$$1 \leq l_i \leq r_i \leq n$$$) — the range of the $$$i$$$-th subsegment. Note that you should output the subsegments such that the inequality $$$l_1 \leq r_1 < l_2 \leq r_2 < \ldots < l_k \leq r_k$$$ is true.

NoteIn the first example, the cuteness of $$$\texttt{0011}$$$ is the same as the cuteness of $$$\texttt{01}$$$.In the second example, the cuteness of $$$\texttt{11000011}$$$ is $$$\frac{1}{2}$$$ and there is no subsegment of size $$$6$$$ with the same cuteness. So we must use $$$2$$$ disjoint subsegments $$$\texttt{10}$$$ and $$$\texttt{0011}$$$.In the third example, there are $$$8$$$ ways to split the string such that $$$\sum\limits_{i=1}^k (r_i - l_i + 1) = 3$$$ but none of them has the same cuteness as $$$\texttt{0101}$$$.In the last example, we don't have to split the string.

'use strict';

var fs = require('fs');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(n, m, str) {
  let s = str + str;
  const one = str.split('').filter(s => s === '1').length;

  if (one * m % n !== 0) {
    console.log(-1);
    return;
  }

  const t = one * m / n;
  let sum = 0;

  for (let i = 0; i < s.length; i++) {
    sum += s[i] === '1' ? 1 : 0;
    if (i >= m) sum -= s[i - m] === '1' ? 1 : 0;

    if (i >= m - 1) {
      if (sum === t) {
        if (i >= n) {
          console.log(2);
          console.log(`1 ${i - n + 1}`);
          console.log(`${i - m + 2} ${n}`);
        } else {
          console.log(1);
          console.log(`${i - m + 2} ${i + 1}`);
        }

        return;
      }
    }
  }
}

// const inputs = fs.readFileSync(path.join(__dirname, './codeforces.test.txt'), 'utf-8').split('\n')

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split('\n');
void function main() {
  const _ = Number(inputs[0]);

  for (let __ = 0; __ < _; __++) {
    const [n, m] = inputs[__ * 2 + 1].trim().split(' ').map(Number);
    const str = inputs[__ * 2 + 2].trim();
    solve(n, m, str);
  }
}();


The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring.String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r.Help the bear cope with the given problem.

The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters.

Print a single number — the answer to the problem.

var s=readline();
var l=s.length-3;
if(l<0){
	print(0);
}else{

var n=l*(l+1)/2;

var a=[];
for(var i=0;i<s.length;i++){
	if(s.substring(i,i+4)=='bear'){
		a.push(i);
	}
}

if(a.hasOwnProperty(0)){

for(var i=1;i<a.length;i++){
	l=a[i]-a[i-1]-1;
	n-=l*(l+1)/2;
}

l=a[0];
n-=l*(l+1)/2;
l=s.length-a[a.length-1]-4;
n-=l*(l+1)/2;

print(n)

}else{
	print(0);
}

}

;(function () {

	print((function () {
		var s = readline(), n = s.length, p = s.indexOf('bear'), l = 0, k = -1;

		while (p !== -1) {
			l += Math.max(p - k, 1) * (n - p - 3);
			k = p; p = s.indexOf('bear', p + 1);
		}

		return l;
	})());

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

function main() {
	var s = trim(readline());

	var bearIndices = [];
	var isBearIndex = new Array(s.length);
	var startIndex = 0;
	while (true) {
		var foundIndex = s.indexOf("bear", startIndex);
		if (foundIndex == -1) {
			break;
		}
		bearIndices.push(foundIndex);
		isBearIndex[foundIndex] = true;
		startIndex = foundIndex+1;
	}

	var count = 0;
	for (var pos = 0; pos < s.length; pos += 1) {
		var found = false;
		for (var seek = pos; seek < s.length; seek += 1) {
			if (isBearIndex[seek]) {
				found = true;
				break;
			}
		}
		if (found) {
			count += s.length-seek-3;
		}
	}

	print(count);
}

main();

var line = readline();
var P=[];
var n = 0;

var subline = line;

while(subline.match("bear")){
    var pos = subline.search("bear");
    if(P.length>0){P.push(P[P.length-1]+4+pos);}
    else{P.push(pos)}
    subline = subline.substring(pos+4,subline.length);
}

if(P.length>0){
  n = (P[0]+1)*(line.length -P[0]-3);
  for(var i=1;i<P.length;i++){
    n = n + (P[i]-P[i-1])*(line.length-P[i]-3);
  }

}

print(n);

var line = readline();
var result = 0;
var occurrences = [];

var foundBears = [];
for (var i = 0; i < line.length; i++) {
  if (line.slice(i, i + 4) == "bear") {
    result += line.length - (i + 3);
    // print(i, result);
    result += i * (line.length - (i + 3));
    // print(i, result);

    if (foundBears.length > 0) {
      var lastBear = foundBears[foundBears.length - 1];
      result -= (lastBear + 1) * (line.length - (i + 3));
    }

    foundBears.push(i);
    // print(i, result);
    // print();
  }
}

print(result);

var s=readline();
var l=s.length-3;
if(l<0){
	print(0);
}else{

var n=l*(l+1)/2;

var a=[];
for(var i=0;i<s.length;i++){
	if(s.substring(i,i+4)=='bear'){
		a.push(i);
	}
}

if(a[0]){

for(var i=1;i<a.length;i++){
	l=a[i]-a[i-1]-1;
	n-=l*(l+1)/2;
}

l=a[0];
n-=l*(l+1)/2;
l=s.length-a[a.length-1]-4;
n-=l*(l+1)/2;

print(n)

}else{
	print(n);
}

}

var s=readline();
var l=s.length-3;
if(l<0){
	print(0);
}else{

var n=l*(l+1)/2;

var a=[];
for(var i=0;i<s.length;i++){
	if(s.substring(i,i+4)=='bear'){
		a.push(i);
	}
}

for(var i=1;i<a.length;i++){
	l=a[i]-a[i-1]-1;
	n-=l*(l+1)/2;
}

l=a[0];
n-=l*(l+1)/2;
l=s.length-a[a.length-1]-4;
n-=l*(l+1)/2;

print(n)

}

var s=readline();
var l=s.length-3;
if(l<0){
	print(0);
}else{

var n=l*(l+1)/2;

var a=[];
for(var i=0;i<s.length;i++){
	if(s.substring(i,i+4)=='bear'){
		a.push(i);
	}
}

if(a.hasOwnProperty(0)){

for(var i=1;i<a.length;i++){
	l=a[i]-a[i-1]-1;
	n-=l*(l+1)/2;
}

l=a[0];
n-=l*(l+1)/2;
l=s.length-a[a.length-1]-4;
n-=l*(l+1)/2;

print(n)

}else{
	print(n);
}

}

var s=readline();
var l=s.length-3;
if(l<0){
	print(0);
}else{

var n=l*(l+1)/2;

var a=[];
for(var i=0;i<s.length;i++){
	if(s.substring(i,i+4)=='bear'){
		a.push(i);
	}
}

for(var i=1;i<a.length;i++){
	l=a[i]-a[i-1]-1;
	n-=l*(l+1)/2;
}

l=a[0];
n-=l*(l+1)/2;
print(n)
l=s.length-a[a.length-1]-4;
n-=l*(l+1)/2;

print(n)

}

;(function () {

	var s = readline(), n = s.length, r = /bear/, k = 4, l = 0, i, j;

	for (i = 0; i < n - k; i++)
		for (j = i + k; j <= n; j++)
			l += r.test(s.slice(i, j));

	print(l);

}).call(this)


You are given a sorted array $$$a_1, a_2, \dots, a_n$$$ (for each index $$$i > 1$$$ condition $$$a_i \ge a_{i-1}$$$ holds) and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$max(i)$$$ be equal to the maximum in the $$$i$$$-th subarray, and $$$min(i)$$$ be equal to the minimum in the $$$i$$$-th subarray. The cost of division is equal to $$$\sum\limits_{i=1}^{k} (max(i) - min(i))$$$. For example, if $$$a = [2, 4, 5, 5, 8, 11, 19]$$$ and we divide it into $$$3$$$ subarrays in the following way: $$$[2, 4], [5, 5], [8, 11, 19]$$$, then the cost of division is equal to $$$(4 - 2) + (5 - 5) + (19 - 8) = 13$$$.Calculate the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ 1 \le a_i \le 10^9$$$, $$$a_i \ge a_{i-1}$$$).

Print the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays.

NoteIn the first test we can divide array $$$a$$$ in the following way: $$$[4, 8, 15, 16], [23], [42]$$$.

Я=readline().split(' ')
бьенториш=+Я[0]
чукча=+Я[1]
цваф=readline().split(' ').map(function(щшо){return +щшо})
ногнг=new Array(бьенториш-1)
for (и=1;и<бьенториш;и++)
    ногнг[и-1]=цваф[и]-цваф[и-1]

function срака(елда,манда)
{
    if (елда>манда)
    return -1
    if (елда==манда)
    return 0
    return 1
}

ногнг.sort(срака)
чукча-=1
ответ=цваф[бьенториш-1]-цваф[0]
for (i=0;i<чукча;i++)
ответ-=ногнг[i]

print(ответ)

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {
    var input = rdAr();
    var n = input[0];
    var k = input[1];
    var A = rdAr();
    var U = Array.from(new Set(A));
    if (U.length <= k) {
        wr(0);
    } else {
        var D = [];
        for (var i = 1; i < U.length; ++i) {
            D.push(U[i] - U[i - 1]);
        }
        D.sortLt();
        var res = 0;
        for (var i = 0; i < D.length - (k-1); ++i) {
            res += D[i];
        }
        wr(res);
    }
};

if (INPUT) {
INPUT = INPUT.split('\n').reverse();
readline = () => INPUT.pop();
write = (s) => {OUTPUT += s};
print = (s) => {OUTPUT += s + '\n'};
}
const rd = readline;
const wr = write;
const pr = print;
const rdAr = () => rd().split(' ').map(v => +v);
const prAr = (a) => pr(a.join(' '));
const cmpLt = (a, b) => a - b;
const cmpGt = (a, b) => b - a;
Array.prototype.sortLt = function() { return this.sort(cmpLt); };
Array.prototype.sortGt = function() { return this.sort(cmpGt); };
const crAr = function(length, ...fillArgs) { return new Array(length).fill(...fillArgs); };
const getPrimes = function(n){var sieve=crAr(n+1,true);for(var i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}var primes=[];for(var i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;};

try {main();}finally{return OUTPUT;}
})();


There is a pyramid which consists of $$$n$$$ floors. The floors are numbered from top to bottom in increasing order. In the pyramid, the $$$i$$$-th floor consists of $$$i$$$ rooms.Denote the $$$j$$$-th room on the $$$i$$$-th floor as $$$(i,j)$$$. For all positive integers $$$i$$$ and $$$j$$$ such that $$$1 \le j \le i < n$$$, there are $$$2$$$ one-way staircases which lead from $$$(i,j)$$$ to $$$(i+1,j)$$$ and from $$$(i,j)$$$ to $$$(i+1,j+1)$$$ respectively.In each room you can either put a torch or leave it empty. Define the brightness of a room $$$(i, j)$$$ to be the number of rooms with a torch from which you can reach the room $$$(i, j)$$$ through a non-negative number of staircases.For example, when $$$n=5$$$ and torches are placed in the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,2)$$$, $$$(4,1)$$$, $$$(4,3)$$$, and $$$(5,3)$$$, the pyramid can be illustrated as follows:  In the above picture, rooms with torches are colored in yellow, and empty rooms are white. The blue numbers in the bottom-right corner indicate the brightness of the rooms.The room $$$(4,2)$$$ (the room with a star) has brightness $$$3$$$. In the picture below, the rooms from where you can reach $$$(4,2)$$$ have red border. The brightness is $$$3$$$ since there are three torches among these rooms.  The pyramid is called nice if and only if for all floors, all rooms in the floor have the same brightness.Define the brilliance of a nice pyramid to be the sum of brightness over the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,1)$$$, ..., $$$(n,1)$$$.Find an arrangement of torches in the pyramid, such that the resulting pyramid is nice and its brilliance is maximized.We can show that an answer always exists. If there are multiple answers, output any one of them.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains a single positive integer $$$n$$$ ($$$1 \le n \le 500$$$) — the number of floors in the pyramid. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$500$$$.

For each test case, output $$$n$$$ lines, the arrangement of torches in the pyramid. The $$$i$$$-th line should contain $$$i$$$ integers, each separated with a space. The $$$j$$$-th integer on the $$$i$$$-th line should be $$$1$$$ if room $$$(i,j)$$$ has a torch, and $$$0$$$ otherwise. We can show that an answer always exists. If there are multiple answers, output any one of them.

NoteIn the third test case, torches are placed in $$$(1,1)$$$, $$$(2,1)$$$, $$$(2,2)$$$, $$$(3,1)$$$, and $$$(3,3)$$$.  The pyramid is nice as rooms on each floor have the same brightness. For example, all rooms on the third floor have brightness $$$3$$$.The brilliance of the pyramid is $$$1+2+3 = 6$$$. It can be shown that no arrangements with $$$n=3$$$ will have a greater brilliance.

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    for(i = 1; i <= t; i++){
        var a = lines[i];
        for(l = 1; l <= a; l++){
            var ans = '';
            for(j = 1; j <= l; j++){
                if(j == 1 || j == l){
                    ans += 1 + ' ';
                }else{
                    ans += 0 + ' ';
                }
            }
            console.log(ans);
        }
    }
});

let readline = require("readline");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);

  if (input.length === +input[0] + 1) {
    // call your function here

    solve(input);
    rl.close();
  }
});

let solve = (input) => {
  for (let i = 1; i < input.length; i++) {
    let ans = ["1", "1 1"];
    if (+input[i] === 1) {
      console.log(ans[0]);
      continue;
    } else if (+input[i] === 2) {
      console.log(ans[0]);
      console.log(ans[1]);
      continue;
    }
    let n = +input[i];
    let x = 3;
    while (x <= n) {
      ans.push("1 " + "0 ".repeat(x - 2) + "1");
      x++;
    }

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

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
     let t = parseInt(readline());
     while(t--){
          let n = parseInt(readline());
          let res = [];
          for(let i=0;i<n;i++){
               if(i===0) res.push([1]);
               else if(i===1) res.push([1,1]);
               else if(i===2) res.push([1,0,1]);
               else{
                    let k = []
                    for(let j=0;j<i+1;j++){
                              if(j===0 || j===i) k.push(1);
                              else k.push(0);
                         }
                    res.push(k);
               }
          }
          for(let i=0;i<res.length;i++) console.log(res[i].join(" "));
     }
};
solve();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

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

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        for (let i = 1; i <= n; i++) {
            if (i === 1) {
                output(1);
            } else if (i===2) {
                output('1 1');
            } else {
                output('1 ' + (new Array(i - 2).fill(0).join(' ')) + ' 1');
            }
        }
    }
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    for(i = 1; i <= t; i++){
        var a = lines[i];
        console.log(1);
        var ans = '';
        for(j = 0; j < a - 1; j++){
            ans += j === 0 ? 1 + ' ' : 0 + ' ';
        }
        ans += 1 + ' ';
        console.log(ans);
    }
});

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    for(i = 1; i <= t; i++){
        var a = lines[i];
        var ans = 1 + ' ';
        console.log(1);
        if(a == 1){
            console.log(ans);
        }else{
            for(j = 0; j < a - 2; j++){
                ans += 0 + ' ';
            }
            ans += 1;
            console.log(ans);
        }
    }
});

let readline = require("readline");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);

  if (input.length === +input[0][0] + 1) {
    // call your function here
    solve(input);
    rl.close();
  }
});

let solve = (input) => {
  for (let i = 1; i < input.length; i++) {
    let n = input[i];

    for (let j = 0; j < n; j++) {
      for (let k = 0; k < j + 1; k++) {
        if (k === 0 || k == j) {
          process.stdout.write("1 ");
        } else {
          process.stdout.write("0 ");
        }
      }
      process.stdout.write("\n");
    }
  }
};

let readline = require("readline");

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

let input = [];
rl.on("line", function (line) {
  input.push(line);

  if (input.length === +input[0][0] + 1) {
    // call your function here
    solve(input);
    rl.close();
  }
});

let solve = (input) => {
  for (let i = 1; i < input.length; i++) {
    let ans = ["1", "1 1"];
    if (+input[i] === 1) {
      console.log(ans[0]);
      continue;
    } else if (+input[i] === 2) {
      console.log(ans[0]);
      console.log(ans[1]);
      continue;
    }
    let n = +input[i];
    let x = 3;
    while (x <= n) {
      ans.push("1 " + "0 ".repeat(x - 2) + "1");
      x++;
    }

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

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
     let t = parseInt(readline());
     while(t--){
          let n = parseInt(readline());
          let res = [];
          for(let i=0;i<n;i++){
               if(i===0) res.push([1]);
               else{
                    let k = [];
                    if((i+1)%2===0){
                         for(let j=0;j<i+1;j++) k.push(1);
                    }
                    else{
                         for(let j=0;j<i+1;j++){
                              if(j===0 || j===i) k.push(1);
                              else k.push(0);
                         }
                    }
                    res.push(k);
               }
          }
          for(let i=0;i<res.length;i++) console.log(res[i].join(" "));
     }
};
solve();


You are given a string $$$a$$$, consisting of $$$n$$$ characters, $$$n$$$ is even. For each $$$i$$$ from $$$1$$$ to $$$n$$$ $$$a_i$$$ is one of 'A', 'B' or 'C'.A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You want to find a string $$$b$$$ that consists of $$$n$$$ characters such that:   $$$b$$$ is a regular bracket sequence;  if for some $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$. In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.Your task is to determine if such a string $$$b$$$ exists.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$a$$$. $$$a$$$ consists only of uppercase letters 'A', 'B' and 'C'. Let $$$n$$$ be the length of $$$a$$$. It is guaranteed that $$$n$$$ is even and $$$2 \le n \le 50$$$.

For each testcase print "YES" if there exists such a string $$$b$$$ that:    $$$b$$$ is a regular bracket sequence;  if for some $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$.  Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first testcase one of the possible strings $$$b$$$ is "(())()".In the second testcase one of the possible strings $$$b$$$ is "()()".

let raw = ''
process.stdin.on('data', it => (raw += it)).on('end', () => {
const arr = raw.replace(/\r/g, '').trim().split('\n');
for (let i = 0, all = +arr.shift(); i < all; i++) {
  let s = arr[i]
  if (s[0] == s[s.length - 1]) {
    console.log('NO')
    continue
  }
  const obj = {}
  let max = 0, ch
  for (const it of s) if (max < (++obj[it] || (obj[it] = 1))) {
    max = obj[it]
    ch = it
  }
  const f = s[0] == ch
  s = s.replace(new RegExp(ch, 'g'), f ? '(' : ')')
  for (const it in obj) if (it !== ch) s = s.replace(new RegExp(it, 'g'), f ? ')' : '(')
  let t = s
  while ((s = t.replace(/\(\)/g, '')) != t) t = s
  console.log(s ? 'NO' : 'YES')
}
});

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

let standardInputString = "";
let currentLine = 0;

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

process.stdin.on("data", rawData => {
    standardInputString += rawData;
});

process.stdin.on("end", _ => {
    standardInputString = standardInputString.trim().split("\n").map(line => {
        return line.trim();
    })
    main();
});

function main() {
    let t = parseInt(readline());
    while (t--) {
        let line = readline().split("");
        console.log(processExpression(line));
    }
}
function processExpression(exp) {
    const escenarios = [
        ["(", "(", ")"],
        ["(", ")", "("],
        ["(", ")", ")"],
        [")", "(", "("],
        [")", "(", ")"],
        [")", ")", "("]
    ];
    for (const escenario of escenarios) {
        let bracket = assignBracket(exp, ...escenario).split("");
        if (isValidExpression(bracket)) {
            return "YES";
        }
    }
    return "NO";
}
function assignBracket(exp, A, B, C) {
    let newExp = "";
    for (let i = 0; i < exp.length; i++) {
        if (exp[i] == "A") {
            newExp += A;
        }
        else if (exp[i] == "B") {
            newExp += B;
        }
        else if (exp[i] == "C") {
            newExp += C;
        }
    }
    return newExp;
}
function isValidExpression(bracket) {
    for (let i = 0; i < bracket.length - 1; i++) {
        if (bracket[i] == "(" && bracket[i + 1] == ")") {
            bracket.splice(i, 2);
            return isValidExpression(bracket);
        }
    }
    return bracket.length == 0;
}

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const a = readLine();

        const res = main(a);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function main(a){
    let cnt_A = 0;
    let cnt_B = 0;
    let cnt_C = 0;
    let arr = [];
    for(let i= 0 ; i < a.length; i++){
        if(a[i] === 'A') cnt_A++;
        if(a[i] === 'B') cnt_B++;
        if(a[i] === 'C') cnt_C++;
    }
    arr.push(['A', cnt_A]);
    arr.push(['B', cnt_B]);
    arr.push(['C', cnt_C]);
    arr.sort((a,b) => a[1] - b[1]);
    let sum = 0;
    let opn = a[0];
    if(opn === arr[arr.length - 1][0]){
        // the other two are closing brackets
        for(let i = 0 ; i < a.length ; i++){
            if(a[i] === opn){
                sum++;
            } else {
                sum--;
            }
            if(sum < 0){
                return 'NO';
            }
        }
    } else {
        // opn and arr[0] || arr[1] is opening and arr[arr.length - 1] are closing
        for(let i = 0 ; i < a.length ; i++){
            if(a[i] === opn || a[i] === arr[0][0] || a[i] === arr[1][0]){
                sum++;
            } else {
                sum--;
            }
            if(sum < 0){
                return 'NO';
            }
        }
    }

    if(sum !== 0){
        return 'NO'
    } else{
        return 'YES'
    }
}

module.exports = main;

/*
Functions used for getting input from the console

To get the next line of input when it is received use 'await getNextLine()' inside of an async function
*/

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

let input = [];
let currentLine = 0;

//adds next line to input array
process.stdin.on('data', function(inputStdin)
{
    const newIn = inputStdin.split("\n")
    for (let i of newIn)
    {
        if (i.length > 0) input.push(i.trim());
    }
});

//returns the next line of unprocessed input
function readLine()
{
    if (!isNewInput()) return "";

    return input[currentLine++];
}

//checks if any new input has been added
function isNewInput()
{
    return currentLine < input.length;
}

//waits 'ms' milliseconds
function sleep(ms)
{
    return new Promise((resolve) =>
    {
        setTimeout(resolve, ms);
    });
}

//returns the next line of unprocessed input once it is available
async function getNextLine()
{
    while(!isNewInput()) await sleep(5);
    return readLine();
}
//----------------------------------------------------

//main
main();
async function main()
{
    const testCases = Number(await getNextLine());
    for (let t = 0; t < testCases; t++)
    {
        const abc = await getNextLine();
        if (isValid(abc, ["A"], ["B", "C"]))
        {
            console.log("YES");
            //console.log("1");
            continue;
        }

        if (isValid(abc, ["B"], ["A", "C"]))
        {
            console.log("YES");
            //console.log("2");
            continue;
        }

        if (isValid(abc, ["C"], ["A", "B"]))
        {
            console.log("YES");
            //console.log("3");
            continue;
        }

        if (isValid(abc, ["A", "B"], ["C"]))
        {
            console.log("YES");
            //console.log("4");
            continue;
        }

        if (isValid(abc, ["A", "C"], ["B"]))
        {
            console.log("YES");
            //console.log("5");
            continue;
        }

        if (isValid(abc, ["C", "B"], ["A"]))
        {
            console.log("YES");
            //console.log("6");
            continue;
        }

        console.log("NO");
    }
    process.exit();
}

function isValid(seq, open, close)
{
    let count = 0;
    const arr = seq.split("");
    for (let c of arr)
    {
        if (open.includes(c))
        {
            count++;
        }
        else if (close.includes(c))
        {
            count--;
        }
        if (count < 0) return false;
    }
    return count == 0;
}

const correctBracket = str => {
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === "(") count += 1;
    else count -= 1;
    if (count < 0) return false;
  }
  return count === 0;
};

const solve = str => {
  for (let i = 0; i < 2 ** 3; i++) {
    const check = correctBracket(
      str
        .replace(/A/g, (i & 1) === 1 ? "(" : ")")
        .replace(/B/g, ((i >> 1) & 1) === 1 ? "(" : ")")
        .replace(/C/g, ((i >> 2) & 1) === 1 ? "(" : ")")
    );
    if (check) return "YES";
  }
  return "NO";
};

const main = () => {
  let test = readInt();
  while (test--) {
    const str = readLine();
    console.log(solve(str));
  }
};

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

let inputString = "";
let currentLine = 0;

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

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

const readLine = () => {
  return inputString[currentLine++];
};

const readInt = () => {
  return parseInt(inputString[currentLine++]);
};

const readListInt = () => {
  return inputString[currentLine++].split(" ").map(s => parseInt(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++];
}

// Make a Snippet for the code above this and then write your logic in main();
var mod = 1000000000n + 7n
var maxN = 1002

function main() {
    const x = readline();
    //
    Array(Number(x)).fill(1).map((t, iii) => {
        // var n = parseInt(readline())
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })

        var a = readline().split('').map((x, iii) => {
            return x
        })

        var b = new Array(a.length)
        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = '('
            if (a[i] === 'B') b[i] = '('
            if (a[i] === 'C') b[i] = ')'
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = '('
            if (a[i] === 'B') b[i] = ')'
            if (a[i] === 'C') b[i] = ')'
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = ')'
            if (a[i] === 'B') b[i] = '('
            if (a[i] === 'C') b[i] = '('
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = '('
            if (a[i] === 'B') b[i] = ')'
            if (a[i] === 'C') b[i] = '('
        }

        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = ')'
            if (a[i] === 'B') b[i] = ')'
            if (a[i] === 'C') b[i] = '('
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = ')'
            if (a[i] === 'B') b[i] = '('
            if (a[i] === 'C') b[i] = ')'
        }
        if (checkString(b)) return console.log('YES')
        console.log('NO')
        // console.log(a)

    })
}

function checkString(a) {
    // console.log(a)
    var count = 0
    var res = true
    for (let i = 0; i < a.length; i++) {
        if (a[i] === '(') count++
        else {
            count--
            if (count < 0) res = false
        }
    }
    if (count !== 0) res = false

    return res

}

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 s = rl();

		let ans;
		for (let i = 0; i < 2; i++) {
			for (let j = 0; j < 2; j++) {
				for (let k = 0; k < 2; k++) {
					const ss = [];
					for (const c of s) {
						if (c == 'A') ss.push(i ? '(' : ')');
						if (c == 'B') ss.push(j ? '(' : ')');
						if (c == 'C') ss.push(k ? '(' : ')');
					}
					ans |= check(ss);
				}
			}
		}

		function check (ss) {
			let cnt = 0;
			for (let i = 0; i < ss.length; i++) {
				if (ss[i] == '(') cnt++;
				else cnt --;
				if (cnt < 0) break;
			}
			return cnt == 0;
		}

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

//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{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
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();
	var key = ["A", "B", "C"];
	for(var i = 0; i < t; i++){
		var s = next();
		var isOK = false;
		for(var j = 0; j < (1 << (key.length)); j++){
			var map = {};
			for(var k = 0; k < key.length; k++){
				if((j & (1 << k)) != 0){
					map[key[k]] = "(";
				}else{
					map[key[k]] = ")";
				}
			}
			var v = [];
			for(var k = 0; k < s.length; k++){
				if(map[s[k]] == "("){
					v.push("(");
				}else if(v.length > 0 && v[v.length - 1] == "("){
					v.pop();
				}else{
					v.push(")");
				}
			}
			if(v.length == 0){
				isOK = true;
				break;
			}
		}
		if(isOK){
			myout("YES");
		}else{
			myout("NO");
		}
	}
}

const { SSL_OP_TLS_ROLLBACK_BUG } = require("constants");
const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
let input = [];
rl.on('line', line => {
    input.push(line);
})
rl.on('close', line => {
   var n = Number(input[0]);
   for (var m = 1; m < input.length; m++) {
       var str = input[m];
    //    ["(((", "(()", "()(", "())", ")((", ")()", "))(", ")))"];
       var patterns = ["(()", "()(", "())", ")((", ")()", "))("];
       var flag = false;
       for (let pattern of patterns) {
           var count = 0;
           var i;
           for (i = 0; i < str.length; i++) {
                var c;
                if (str[i] === "A") {
                    c = pattern[0];
                } else if (str[i] === "B") {
                    c = pattern[1];
                } else {
                    c = pattern[2];
                }
                if (c === "(") {
                    count++;
                } else {
                    count--;
                }
                if (count < 0) {
                    break;
                }
           }
           if (i === str.length && count === 0) {
               flag = true;
           }
       }
       if (flag) {
           console.log("YES");
       } else {
           console.log("NO");
       }
   }
})

const T = parseInt(readline());

for (t = 0; t < T; t++) {
	var s = readline();

	var any = false;
	for (a = -1; a < 2; a += 2) {
		for (b = -1; b < 2; b += 2) {
			for (c = -1; c < 2; c += 2) {
				var cur = 0;
				var ok = true;
				for (i = 0; i < s.length; i++) {
					if (s[i] === 'A') cur += a;
					if (s[i] === 'B') cur += b;
					if (s[i] === 'C') cur += c;
					if (cur < 0) ok = false;
				}
				if (ok && cur === 0) {
					any = true;
				}
			}
		}
	}
	print(any ? "YES" : "NO");
}

let raw = ''
process.stdin.on('data', it => (raw += it)).on('end', () => {
const arr = raw.replace(/\r/g, '').trim().split('\n');
for (let i = 0, all = +arr.shift(); i < all; i++) {
  const s = arr[i]
  if (s.length <= 1) {
    console.log('NO')
    continue
  }
  const obj = {}
  let max = 0, ch, cnt = 0
  for (const it of s) if (max < (++obj[it] || (obj[it] = 1))) {
    max = obj[it]
    ch = it
  }
  for (const it in obj) if (it !== ch) cnt += obj[it]
  console.log(max == cnt && s[0] != s[s.length -1] && !(s[0] !== ch && s[s.length - 1] !== ch) ? 'YES' : 'NO')
}
});

let raw = [];
process.stdin.on('data', it => raw.push(it)).on('end', () => {
  const arr = Buffer.concat(raw).toString().replace(/\r/g, '').trim().split('\n');
  for (let i = 0, all = +arr.shift(); i < all; i++) {
    if (arr[i][0] == arr[i][arr[i].length - 1]) {
      console.log('NO')
      continue
    }
    const obj = {}
    let max = 0, ch, cnt = 0
    for (const it of arr[i]) if (max < (++obj[it] || (obj[it] = 1))) {
      max = obj[it]
      ch = it
    }
    for (const it in obj) if (it !== ch) cnt += obj[it]
    console.log(max == cnt ? 'YES' : 'NO')
  }
})

let raw = '';
process.stdin.on('data', it => (raw += it)).on('end', () => {
  const arr = raw.replace(/\r/g, '').trim().split('\n');
  for (let i = 0, all = +arr.shift(); i < all; i++) {
    if (arr[i][0] == arr[i][arr[i].length - 1]) {
      console.log('NO')
      continue
    }
    const obj = {}
    let max = 0, ch, cnt = 0
    for (const it of arr[i]) if (max < (++obj[it] || (obj[it] = 1))) {
      max = obj[it]
      ch = it
    }
    for (const it in obj) if (it !== ch) cnt += obj[it]
    console.log(max == cnt ? 'YES' : 'NO')
  }
})

let raw = '';
process.stdin.on('data', it => (raw += it)).on('end', () => {
  const arr = raw.trim().split('\n');
  for (let i = 0, all = +arr.shift(); i < all; i++) {
    if (arr[i][0] == arr[i][arr[i].length - 1]) {
      console.log('NO')
      continue
    }
    const obj = {}
    let max = 0, ch, cnt = 0
    for (const it of arr[i]) if (max < (++obj[it] || (obj[it] = 1))) {
      max = obj[it]
      ch = it
    }
    for (const it in obj) if (it !== ch) cnt += obj[it]
    console.log(max == cnt ? 'YES' : 'NO')
  }
})

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const a = readLine();

        const res = main(a);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function main(a){
    let cnt_A = 0;
    let cnt_B = 0;
    let cnt_C = 0;
    let arr = [];
    for(let i= 0 ; i < a.length; i++){
        if(a[i] === 'A') cnt_A++;
        if(a[i] === 'B') cnt_B++;
        if(a[i] === 'C') cnt_C++;
    }
    arr.push(['A', cnt_A]);
    arr.push(['B', cnt_B]);
    arr.push(['C', cnt_C]);
    arr.sort((a,b) => a[1] - b[1]);
    console.log(arr)
    let sum = 0;
    let opn = a[0];
    if(opn === arr[arr.length - 1][0]){
        // the other two are closing brackets
        for(let i = 0 ; i < a.length ; i++){
            if(a[i] === opn){
                sum++;
            } else {
                sum--;
            }
            if(sum < 0){
                return 'NO';
            }
        }
    } else {
        // opn and arr[0] || arr[1] is opening and arr[arr.length - 1] are closing
        for(let i = 0 ; i < a.length ; i++){
            if(a[i] === opn || a[i] === arr[0][0] || a[i] === arr[1][0]){
                sum++;
            } else {
                sum--;
            }
            if(sum < 0){
                return 'NO';
            }
        }
    }

    if(sum !== 0){
        return 'NO'
    } else{
        return 'YES'
    }
}

module.exports = main;

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const a = readLine();

        const res = main(a);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function main(a){
    let cnt_A = 0;
    let cnt_B = 0;
    let cnt_C = 0;
    let arr = [];
    for(let i= 0 ; i < a.length; i++){
        if(a[i] === 'A') cnt_A++;
        if(a[i] === 'B') cnt_B++;
        if(a[i] === 'C') cnt_C++;
    }
    arr.push(['A', cnt_A]);
    arr.push(['B', cnt_B]);
    arr.push(['C', cnt_C]);
    arr.sort((a,b) => a[1] - b[1]);
    let sum = 0;
    let opn = a[0];
    if(opn === arr[arr.length - 1][0]){
        // the other two are closing brackets
        for(let i = 0 ; i < a.length ; i++){
            if(a[i] === opn){
                sum++;
            } else {
                sum--;
            }
            if(sum < 0){
                return 'NO';
            }
        }
    } else {
        // opn and arr[0] || arr[1] is opening and arr[arr.length - 1] are closing
        for(let i = 0 ; i < a.length ; i++){
            if(a[i] === opn || a[i] === arr[0][0] || arr[1][0]){
                sum++;
            } else {
                sum--;
            }
            if(sum < 0){
                return 'NO';
            }
        }
    }

    if(sum !== 0){
        return 'NO'
    } else{
        return 'YES'
    }
}

module.exports = main;

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const a = readLine();

        const res = main(a);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function main(a){
    if(a.length % 2 === 1 || a[0] === a[a.length - 1]){
        return 'NO';
    }
    let count_a = 0;
    let count_b = 0;
    let count_c = 0;
    let arr = [];
    for(let i = 0 ; i < a.length; i++){
        if(a[i] === 'A') count_a++;
        if(a[i] === 'B') count_b++;
        if(a[i] === 'C') count_c++;
        if(i === a.length - 1){
            arr.push(count_a);
            arr.push(count_b);
            arr.push(count_c);
            arr.sort((a,b) => a - b);
        }
    }
    if(arr[2] === (arr[0] + arr[1])){
        return 'YES';
    } else {
        return 'NO';
    }
}

module.exports = main;

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const a = readLine();

        const res = main(a);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function main(a){
    if(a.length % 2 === 1){
        return 'NO';
    }
    let count_a = 0;
    let count_b = 0;
    let count_c = 0;
    for(let i = 0 ; i < a.length; i++){
        if(a[i] === 'A') count_a++;
        if(a[i] === 'B') count_b++;
        if(a[i] === 'C') count_c++;
    }
    const is_even_count_a = count_a % 2;
    const is_even_count_b = count_b % 2;
    const is_even_count_c = count_c % 2;
    const sum = is_even_count_a + is_even_count_b + is_even_count_c;
    if(sum === 3 || sum === 1){
        return 'NO'
    } else {
        return 'YES'
    }
}

/*
Functions used for getting input from the console

To get the next line of input when it is received use 'await getNextLine()' inside of an async function
*/

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

let input = [];
let currentLine = 0;

//adds next line to input array
process.stdin.on('data', function(inputStdin)
{
    const newIn = inputStdin.split("\n")
    for (let i of newIn)
    {
        if (i.length > 0) input.push(i.trim());
    }
});

//returns the next line of unprocessed input
function readLine()
{
    if (!isNewInput()) return "";

    return input[currentLine++];
}

//checks if any new input has been added
function isNewInput()
{
    return currentLine < input.length;
}

//waits 'ms' milliseconds
function sleep(ms)
{
    return new Promise((resolve) =>
    {
        setTimeout(resolve, ms);
    });
}

//returns the next line of unprocessed input once it is available
async function getNextLine()
{
    while(!isNewInput()) await sleep(5);
    return readLine();
}
//----------------------------------------------------

//main
main();
async function main()
{
    const testCases = Number(await getNextLine());
    for (let t = 0; t < testCases; t++)
    {
        const abc = await getNextLine();
        if (isValid(abc, ["A"], ["B", "C"]))
        {
            console.log("YES");
            continue;
        }

        if (isValid(abc, ["B"], ["A", "C"]))
        {
            console.log("YES");
            continue;
        }

        if (isValid(abc, ["C"], ["A", "C"]))
        {
            console.log("YES");
            continue;
        }

        if (isValid(abc, ["A", "B"], ["C"]))
        {
            console.log("YES");
            continue;
        }

        if (isValid(abc, ["A", "C"], ["B"]))
        {
            console.log("YES");
            continue;
        }

        if (isValid(abc, ["C", "B"], ["A"]))
        {
            console.log("YES");
            continue;
        }

        console.log("NO");
    }
    process.exit();
}

function isValid(seq, open, close)
{
    let count = 0;
    const arr = seq.split("");
    for (let c of arr)
    {
        if (open.includes(c))
        {
            count++;
        }
        else if (close.includes(c))
        {
            count--;
        }
        if (count < 0) return false;
    }
    return count == 0;
}

const correctBracket = str => {
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === "(") count += 1;
    else count -= 1;
    if (count < 0) return false;
  }
  return count === 0;
};

const solve = str => {
  const check =
    correctBracket(
      str
        .replace(/C/g, "A")
        .replace(/A/g, "(")
        .replace(/B/g, ")")
    ) ||
    correctBracket(
      str
        .replace(/C/g, "B")
        .replace(/A/g, "(")
        .replace(/B/g, ")")
    ) ||
    correctBracket(
      str
        .replace(/C/g, "A")
        .replace(/A/g, ")")
        .replace(/B/g, "(")
    ) ||
    correctBracket(
      str
        .replace(/C/g, "B")
        .replace(/A/g, ")")
        .replace(/B/g, "(")
    );
  if (check) return "YES";
  return "NO";
};

const main = () => {
  let test = readInt();
  while (test--) {
    const str = readLine();
    console.log(solve(str));
  }
};

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

let inputString = "";
let currentLine = 0;

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

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

const readLine = () => {
  return inputString[currentLine++];
};

const readInt = () => {
  return parseInt(inputString[currentLine++]);
};

const readListInt = () => {
  return inputString[currentLine++].split(" ").map(s => parseInt(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++];
}

// Make a Snippet for the code above this and then write your logic in main();
var mod = 1000000000n + 7n
var maxN = 1002

function main() {
    const x = readline();
    //
    Array(Number(x)).fill(1).map((t, iii) => {
        // var n = parseInt(readline())
        // var [n, u, v] = readline().split(' ').map((x, iii) => {
        //     return parseInt(x)
        // })

        var a = readline().split('').map((x, iii) => {
            return x
        })

        var b = new Array(a.length)
        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = '('
            if (a[i] === 'B') b[i] = '('
            if (a[i] === 'C') b[i] = ')'
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = '('
            if (a[i] === 'B') b[i] = ')'
            if (a[i] === 'C') b[i] = ')'
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = ')'
            if (a[i] === 'B') b[i] = '('
            if (a[i] === 'C') b[i] = '('
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = ')'
            if (a[i] === 'B') b[i] = ')'
            if (a[i] === 'C') b[i] = '('
        }
        if (checkString(b)) return console.log('YES')

        for (let i = 0; i < b.length; i++) {
            if (a[i] === 'A') b[i] = ')'
            if (a[i] === 'B') b[i] = '('
            if (a[i] === 'C') b[i] = ')'
        }
        if (checkString(b)) return console.log('YES')
        console.log('NO')
        // console.log(a)

    })
}

function checkString(a) {
    // console.log(a)
    var count = 0
    var res = true
    for (let i = 0; i < a.length; i++) {
        if (a[i] === '(') count++
        else {
            count--
            if (count < 0) res = false
        }
    }
    if (count !== 0) res = false

    return res

}


Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.You have to find the minimum number of digits in which these two numbers can differ.

The first line contains integer k (1 ≤ k ≤ 109). The second line contains integer n (1 ≤ n < 10100000). There are no leading zeros in n. It's guaranteed that this situation is possible.

Print the minimum number of digits in which the initial number and n can differ.

NoteIn the first example, the initial number could be 12.In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.

function resolve(k, n) {
  k = parseInt(k, 10);
  var sum = 0;
  for (var i = 0; i < n.length; i++) {
    sum += parseInt(n[i], 10);
  }
  if (sum >= k) {
    return 0;
  } else {
    var total = k - sum;
    var count = 0;
    var arr = n.split('').sort();
    for (var j = 0; j < arr.length; j++) {
      count++;
      total -= 9 - parseInt(arr[j], 10);
      if (total <= 0) {
        break;
      }
    }
    if (total > 0) {
      var q = Math.floor(total / 9);
      var r = total % 9;
      if (r === 0) {
        return q + count;
      } else {
        return q + count + 1;
      }
    } else {
      return count;
    }
  }
}

const k = readline();
const n = readline();

const result = resolve(k, n);

print(result + '\n');

function main() {
  var k = Number(readline());
  var n = readline();

  var sumOfN = n.split('').reduce((sum, i) => {
    return sum + Number(i);
  }, 0);

  if (sumOfN >= k) {
    return print(0);
  }

  var sortedN = n
    .split('')
    .sort()
    .join('');
  var changes = 0;

  for (var i = 0; i < sortedN.length; i++) {
    if (Number(sortedN[i]) !== 9) {
      sumOfN += 9 - Number(sortedN[i]);
      changes++;

      if (sumOfN >= k) {
        return print(changes);
      }
    }
  }

  print('Something went wrong');
}

main();

function resolve(k, n) {
  k = parseInt(k, 10);
  var sum = 0;
  for (var i = 0; i < n.length; i++) {
    sum += parseInt(n[i], 10);
  }
  if (sum >= k) {
    return 0;
  } else {
    var q = Math.floor((k - sum) / 9);
    var r = (k - sum) % 9;
    if (r === 0) {
      return q;
    } else {
      return q + 1;
    }
  }
}

const k = readline();
const n = readline();

const result = resolve(k, n);

print(result);

function sumDigits(number) {
  var total = 0;
  for (var i = 0; i < number.length; i++) {
    total += number[i];
  }
  return total;
}

function main() {
  var k = readline();
  var n = readline();

  var sumOfN = sumDigits(n);

  if (k < sumOfN) {
    return print(0);
  }

  var sortedN = n
    .split('')
    .sort()
    .join('');
  var newTotal = sumOfN;
  var changes = 0;

  for (var i = 0; i < sortedN.length; i++) {
    if (sortedN[i] !== '9') {
      newTotal += 9 - sortedN[i];
      changes++;
    }
  }

  print(changes);
}

main();

function main() {
  var k = readline();
  var n = readline();

  var sumOfN = n.split('').reduce((sum, i) => {
    return sum + i;
  }, 0);

  if (sumOfN >= k) {
    return print(0);
  }

  var sortedN = n
    .split('')
    .sort()
    .join('');
  var changes = 0;

  for (var i = 0; i < sortedN.length; i++) {
    if (sortedN[i] !== '9') {
      sumOfN += 9 - sortedN[i];
      changes++;

      if (sumOfN >= k) {
        return print(changes);
      }
    }
  }

  print(changes);
}

main();


Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.

The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 и s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.

If Vasya can write the given anonymous letter, print YES, otherwise print NO

Instead of dogging Your footsteps it disappears but you dont notice anything
where is your dog

Instead of dogging Your footsteps it disappears but you dont notice anything
Your dog is upstears

Instead of dogging your footsteps it disappears but you dont notice anything
Your dog is upstears

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

var ans = "YES", indicator = 0, myMap = {};

rl.on('line', (input) => {

    if (indicator == 0) {
        /*
        input.forEach(element => {
            if (element != ' ') {

                if (element in myMap)
                    myMap[element]++;
                else myMap[element] = 1;
            }
        });*/
        for (let i = 0; i < input.length; i++) {
            if (input[i] == ' ')
                continue;

            if (input[i] in myMap)
                myMap[input[i]]++;
            else myMap[input[i]] = 1;

        }
        indicator++;
    }
    else {

        for (let i = 0; i < input.length; i++) {
            if (input[i] == ' ')
                continue;
            if (myMap[input[i]] > 0)
                myMap[input[i]]--;
            else {
                ans = "NO";
                break;
            }
        }
        console.log(ans);
        rl.close();
    }
});

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

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

function main() {
  const str1 = readLine();
  const str2 = readLine().split(" ").join("").trim();
  const map = {};
  let ok = true;

  for (let i = 0; i < str1.length; i++) {
    const char = str1[i];
    if ((char >= "a" && char <= "z") || (char >= "A" && char <= "Z")) {
      map[char] = (map[char] || 0) + 1;
    }
  }

  for (let i = 0; i < str2.length; i++) {
    const char = str2[i];
    if (!map[char] || map[char] === 0) {
      console.log("NO");
      ok = false;
      break;
    }
    map[char]--;
  }

  ok && console.log("YES");
}

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function main() {
	let h = readLine().split('');
	let str = readLine().split('');

	let c = 0;

	for (let i = 0, l = str.length; i < l; i++) {
		let index = h.indexOf(str[i]);
		if (index > -1) {
			c++;
			if (str[i] !== ' ') h.splice(index, 1);
		}
	}

	if (c === str.length) console.log('YES');
	else console.log('NO');
}

var s = readline().trim().split(' ').filter((_s)=>_s!='').join('');
var t = readline().trim().split(' ').filter((_s)=>_s!='').join('');

var ss = {};
for(var i=0;i<s.length;i++){
    if(ss[s[i]]==undefined)
        ss[s[i]] = 0;

    ss[s[i]]++;
}
var tt = {};
for(var i=0;i<t.length;i++){
    if(tt[t[i]]==undefined)
        tt[t[i]] = 0;

     tt[t[i]]++;
}

var can = true;
for(var i in tt){
    if(tt[i]>(ss[i]==undefined?0:ss[i])){
        can = false;
        break;
    }
}

print(can?'YES':'NO')

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

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

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

var whitespaceGlobalRegex = /\s+/g;

function removeWhitespace(s) {
	return s.replace(whitespaceGlobalRegex, "");
}

function main() {
	var sourceText = removeWhitespace(readline()),
		targetText = removeWhitespace(readline());

	var characterCounts = {};
	for (var characterIndex = sourceText.length-1; characterIndex >= 0; --characterIndex) {
		var character = sourceText.charAt(characterIndex);
		if (characterCounts[character] === undefined) {
			characterCounts[character] = 1;
		}
		else {
			characterCounts[character] += 1;
		}
	}

	for (var characterIndex = targetText.length-1; characterIndex >= 0; --characterIndex) {
		var character = targetText.charAt(characterIndex);
		if (characterCounts[character] === undefined || characterCounts[character] == 0) {
			print("NO");
			return;
		}
		characterCounts[character] -= 1;
	}

	print("YES");
}

main();

'use strict'

let s1 = readline()
let s2 = readline()

let ls = {}

for (let i = 0; i < s1.length; i++) {
  let l = s1[i]
  if (l == ' ') continue
  ls[l] = ls[l] || 0
  ls[l]++
}
let r = true
for (let i = 0; i < s2.length; i++) {
  let l = s2[i]
  if (l == ' ') continue
  if (!ls[l]) {
    r = false
    break
  }
  ls[l]--
}

print(r ? 'YES' : 'NO')

var stZag, stText, stt;
var mask = new Array(300);

function r() {
    stZag = readline();
    stText = readline();
};

+function main() {
    for (var i = 0; i < 300; i++) {
        mask[i] = false;
    }

    r();
    stt = "";
    for (var i = 0; i < stText.length; ++i) {
        if (stText.charAt(i) != ' ' && stText.charAt(i) != '	') {
            stt += stText.charAt(i);
        }
    }

    stText = "";

    for (var i = 0; i < stt.length; ++i) {
        stText += stt.charAt(i);
    }

    stt = "";

    for (var i = 0; i < stZag.length ; ++i) {
        if (stZag.charAt(i) != ' ' && stZag.charAt(i) != '	') {
            stt += stZag.charAt(i);
        }
    }

    stZag = "";
    for (var i = 0; i < stt.length ; ++i) {
        stZag += stt.charAt(i);
    }
    stt = "";

    for (var i = 0; i < stText.length; ++i) {
        var tek = stText.charAt(i);

        for (var j = 0; j < stZag.length; ++j) {
            if (mask[j] != true) {
                if (tek == stZag.charAt(j)) {
                    mask[j] = true;
                    break;
                }
            }

            if (j == stZag.length - 1) {
                print("NO\n");
                // cout << "NO" << endl;
                return 0;
            }
        }
    }

    print("YES\n");
    return 0;
}();

function checkAnonymousLetter (title, letter) {
  var index = {},
      canMakeLetter = true;

  debugger

  title.replace(/\s/g, "").split("").forEach(function (item) {
    if (index[item] === undefined) {
      index[item] = 1;
    } else {
      index[item]++;
    }
  });

  letter.replace(/\s/g, "").split("").forEach(function (item) {
    if (index[item] && canMakeLetter) {
      if (index[item] === 0) {
        canMakeLetter = false;
      } else {
        index[item]--;
      }
    } else {
      canMakeLetter = false;
    }
  });

  return canMakeLetter;
}

var title = readline(),
    letter = readline();

var output = checkAnonymousLetter.call(null, title, letter) ? "YES" : "NO";

write(output);

var header = readline().replace(/ /g,'');
var text = readline().replace(/ /g,'');
var hash = {};

for (var i = 0; i < header.length; i++) {
	if (hash.hasOwnProperty(header[i])) {
		hash[header[i]]++;
	} else {
		hash[header[i]] = 1;
	}
}

function isPossible() {
	for (var j = 0; j < text.length; j++) {
		if (hash[text[j]]) {
			hash[text[j]]--;
		} else {
			return 'NO';
		}
	}
	return 'YES';
}

print(isPossible());

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function main() {
	let h = readLine().split('');
	let str = readLine().split('');

	let c = 0;

	for (let i = 0, l = str.length; i < l; i++) {
		let index = h.indexOf(str[i]);
		if (index > -1) {
			c++;
			h.splice(index, 1);
		}
	}

	if (c === str.length) console.log('YES');
	else console.log('NO');
}

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function main() {
	let h = readLine().split('');
	let str = readLine().split('');

	let c = 0;

	for (let i = 0, l = str.length; i < l; i++) {
		if (h.indexOf(str[i]) > -1) c++;
	}

	if (c === str.length) console.log('YES');
	else console.log('NO');
}

var stZag, stText, stt;
var mask = new Array(300);

function r() {
    stZag = readline();
    stText = readline();
};

+function main() {
    for (var i = 0; i < 300; i++) {
        mask[i] = false;
    }

    r();
    stt = "";
    for (var i = 0; i < stText.length; ++i) {
        if (stText.charAt(i) != ' ' && stText.charAt(i) != '	') {
            stt += stText.charAt(i);
        }
    }

    stText = "";

    for (var i = 0; i < stt.length; ++i) {
        stText += stt.charAt(i);
    }

    stt = "";

    for (var i = 0; i < stZag.length ; ++i) {
        if (stZag.charAt(i) != ' ' && stZag.charAt(i) != '	') {
            stt += stZag.charAt(i);
        }
    }

    stZag = "";
    for (var i = 0; i < stt.length ; ++i) {
        stZag += stt.charAt(i);
    }
    stt = "";

    print(stZag);
    print(stText);

    for (var i = 0; i < stText.length; ++i) {
        var tek = stText.charAt(i);

        for (var j = 0; j < stZag.length; ++j) {
            if (mask[j] != true) {
                if (tek == stZag.charAt(j)) {
                    mask[j] = true;
                    break;
                }
            }

            if (j == stZag.length - 1) {
                print("NO\n");
                // cout << "NO" << endl;
                return 0;
            }
        }
    }

    print("YES\n");
    return 0;
}();


Petya organized a strange birthday party. He invited $$$n$$$ friends and assigned an integer $$$k_i$$$ to the $$$i$$$-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are $$$m$$$ unique presents available, the $$$j$$$-th present costs $$$c_j$$$ dollars ($$$1 \le c_1 \le c_2 \le \ldots \le c_m$$$). It's not allowed to buy a single present more than once.For the $$$i$$$-th friend Petya can either buy them a present $$$j \le k_i$$$, which costs $$$c_j$$$ dollars, or just give them $$$c_{k_i}$$$ dollars directly.Help Petya determine the minimum total cost of hosting his party.

The first input line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 3 \cdot 10^5$$$) — the number of friends, and the number of unique presents available. The following line contains $$$n$$$ integers $$$k_1, k_2, \ldots, k_n$$$ ($$$1 \leq k_i \leq m$$$), assigned by Petya to his friends.  The next line contains $$$m$$$ integers $$$c_1, c_2, \ldots, c_m$$$ ($$$1 \le c_1 \le c_2 \le \ldots \le c_m \le 10^9$$$) — the prices of the presents. It is guaranteed that sum of values $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of values $$$m$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case output a single integer — the minimum cost of the party.

NoteIn the first example, there are two test cases. In the first one, Petya has $$$5$$$ friends and $$$4$$$ available presents. Petya can spend only $$$30$$$ dollars if he gives  $$$5$$$ dollars to the first friend.  A present that costs $$$12$$$ dollars to the second friend.  A present that costs $$$5$$$ dollars to the third friend.  A present that costs $$$3$$$ dollars to the fourth friend.  $$$5$$$ dollars to the fifth friend. In the second one, Petya has $$$5$$$ and $$$5$$$ available presents. Petya can spend only $$$190$$$ dollars if he gives  A present that costs $$$10$$$ dollars to the first friend.  A present that costs $$$40$$$ dollars to the second friend.  $$$90$$$ dollars to the third friend.  $$$40$$$ dollars to the fourth friend.  $$$10$$$ dollars to the fifth friend.

var limit = parseInt(readline());
    for (var i = 0; i < limit; i++) {
        var caseConstraints = readline().split(" ");
        var guestLength = parseInt(caseConstraints[0]);
        var giftLength = parseInt(caseConstraints[1]);
        var guestArray = readline().split(" ");
        var giftArray = readline().split(" ");
        var guestIntArray = new Array();
        for (var _i = 0, guestArray_1 = guestArray; _i < guestArray_1.length; _i++) {
            var element = guestArray_1[_i];
            guestIntArray.push(parseInt(element));
        }
        guestIntArray.sort(function (a, b) { return b - a; });
        var total = 0;
        var flag = true;
        for (var j = 0; j < guestLength; j++) {
            if (j < giftLength) {
                if (guestIntArray[j] - 1 < giftLength) {
                    if (parseInt(giftArray[guestIntArray[j] - 1]) < parseInt(giftArray[j])) {
                        flag = false;
                    }
                }
                total += (flag) ? parseInt(giftArray[j]) : parseInt(giftArray[guestIntArray[j] - 1]);
            }
            else {
                total += parseInt(giftArray[guestIntArray[j] - 1]);
            }
        }
        print(total);
    }

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

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

		let ans = 0, l = 0;
		for (const i of k) {
			if (c[l] < c[i-1]) {
				ans += c[l]; l++;
			} else {
				ans += c[i-1];
			}
		}

		console.log(ans);
	}
}

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

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

		let ans = 0;
		const st = c.slice().reverse();
		for (let i = 0; i < n; i++) {
			if (st.length && st[st.length-1] < c[k[i]-1]) {
				ans += st.pop();
			} else {
				ans += c[k[i]-1];
			}
		}

		console.log(ans);
	}
}

/*
 * File Created: Wednesday, 6th January 2021 9:38:39 pm
 * Author: Lukas Rimkus
 */

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(readLine(), 10);

    while(testCases--) {

        const [n, m ] = readLine().split(' ').map(Number);

        const k = readLine().split(' ').map(Number);

        const c = readLine().split(' ').map(Number);

        const res = a(n,m,k,c);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function a(n,m,guests,c){
    let count = 0;
    guests.sort((a,b) => b - a);
    for(let i = 0; i < guests.length; i++){
        const gift = c[guests[i] - 1];
        const money = c[i];
        count += Math.min(gift, money ? money : gift);
        // console.log('gift = ', gift, 'money = ', money, 'count = ', count);
    }
    return count;
}

module.exports =  a;

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

// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var answer = []

    // console.log(Number(x))
    // 1 1 7
    // 6 9, 15, 18
    Array(Number(x)).fill(1).map((t, i) => {
        var [n, m] = readline().split(' ').map(x => Number(x));
        var sum = 0
        var sum2 = 0
        var array2 = []
        var k = readline().split(' ').map(x => {
            return Number(x) - 1
        });
        var c = readline().split(' ').map(x => {
            return Number(x)
        });
        k = k.sort((a, b) => b - a)
        var sum = 0
        var j = 0
        k.map((x, i) => {
            if (c[j] < c[x]) {
                sum += c[j]
                j++
            } else {
                sum += c[x]
            }

            // console.log(sum)

        })

        console.log(sum)

    })

}

let i = '';

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

    const t = parseInt(lines[0]);

    for (let i = 1; i <= t * 3; i += 3) {
        let split = lines[i].split(' ');
        const n = parseInt(split[0]);
        const m = parseInt(split[1]);

        const k = lines[i + 1].split(' ').map(num => parseInt(num));
        const c = lines[i + 2].split(' ').map(num => parseInt(num));

        const result = solve(n, m, k, c);

        console.log(result);
    }
});

function solve(n, m, k, c) {
    let sum = 0;

    k.sort((a, b) => b - a);

    let j = 1;

    for (let i = 0; i < n; i++) {
        if (j < k[i]) {
            sum += c[j - 1];
            j++;
        } else {
            sum += c[k[i] - 1];
        }
    }

    return sum;
}