Monocarp had a tree which consisted of $$$n$$$ vertices and was rooted at vertex $$$1$$$. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:a = [] # the order in which vertices were processedq = Queue()q.put(1) # place the root at the end of the queuewhile not q.empty():    k = q.pop() # retrieve the first vertex from the queue    a.append(k) # append k to the end of the sequence in which vertices were visited    for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order        q.put(y)Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.Monocarp knows that there are many trees (in the general case) with the same visiting order $$$a$$$, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all root's children are $$$1$$$.Help Monocarp to find any tree with given visiting order $$$a$$$ and minimum height.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$; $$$a_i \neq a_j$$$; $$$a_1 = 1$$$) — the order in which the vertices were visited by the BFS algorithm. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print the minimum possible height of a tree with the given visiting order $$$a$$$.

NoteIn the first test case, there is only one tree with the given visiting order:   In the second test case, there is only one tree with the given visiting order as well:   In the third test case, an optimal tree with the given visiting order is shown below:

function D1437(array) {
  var partition = [];
  var current = [];
  var n = array.length;
  current.push(array[0]);

  for (var i = 1; i < n; i++) {
    if (array[i] < array[i - 1] || i === 1) {
      partition.push(current);
      current = [];
    }

    current.push(array[i]);
  }

  partition.push(current);
  var k = partition.length;
  var depth = Array(k).fill(null);
  depth[0] = 0;
  var cp = 0,
      cov = 1;

  while (cov < k) {
    var cl = partition[cp].length;

    for (var _i = cov; _i < Math.min(cov + cl, k); _i++) {
      depth[_i] = depth[cp] + 1;
    }

    cp++;
    cov += cl;
  }

  return depth[k - 1];
}

function execute(readline, print) {
  var iter = {
    next: function next() {
      return readline().trim();
    }
  };

  var split = function split(string) {
    return string.split(' ').map(Number);
  };

  var t = Number(iter.next());

  while (t--) {
    iter.next();
    var arr = split(iter.next());
    print(D1437(arr));
  }
}

execute(readline, print)

var tc = parseInt(readline());
for (; tc--;){
    var n = parseInt(readline());
    var ar = readline().split(' ').map(x => parseInt(x));

    var level = 1;
    var ans = 0;
    var current = 0;

    for (var i = 1; i < n; i++){
        if (ar[i] < ar[i - 1]) {
            level--;
            if (level == 0) {
                ans++;
                level = current;
                current = 0;
            }
        }
        current++;
    }
    ans++; // root node
    print(ans);
}

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

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

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine().split(" ").map(Number);
    let [node, map, result] = [1, new Map([[1, 0]]), 0];
    const queue = [];

    for (let i = 1; i < arr.length; i++) {
      const [prev, curr] = [arr[i - 1], arr[i]];
      if (curr < prev) {
        node = queue.shift();
      }
      queue.push(curr);
      map.set(curr, map.get(node) + 1);
      result = Math.max(result, map.get(curr));
    }

    console.log(result);
  }
}

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

    D();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function D(){
    let t = pi(readline());
    while(t){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        let q = [a[0], null];
        let p = 1;
        let h = 0;
        while(q.length > 0 && p < n){
            let node = q.shift();
            if(node !== null){
                let x = p+1;
                while(x < n && a[x] >= a[x-1]){
                    q.push(x-1);
                    x++;
                }
                q.push(p);
                p = x;
            }else{
                h++;
                if(q.length > 0){
                    q.push(null);
                }
            }
        }

        if(q.length > 0)
            h++;

        console.log(h);
    }
}

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

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

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine().split(" ").map(Number);
    let count = 0;

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

    console.log(count);
  }
}

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

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

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine().split(" ").map(Number);
    let count = 0;

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

    console.log(count);
  }
}


The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.A Bitlandish string is a string made only of characters "0" and "1".BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string a, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as x and the other one as y. Then he calculates two values p and q: p = x xor y, q = x or y. Then he replaces one of the two taken characters by p and the other one by q.The xor operation means the bitwise excluding OR operation. The or operation is the bitwise OR operation.So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.You've got two Bitlandish strings a and b. Your task is to check if it is possible for BitHaval to transform string a to string b in several (possibly zero) described operations.

The first line contains Bitlandish string a, the second line contains Bitlandish string b. The strings can have different lengths. It is guaranteed that the given strings only consist of characters "0" and "1". The strings are not empty, their length doesn't exceed 106.

Print "YES" if a can be transformed into b, otherwise print "NO". Please do not print the quotes.

print(function(a, b) {
  if (a.length != b.length) return 'NO';
  if (a.length === 1 && a !== b) return 'NO'
  if (a.indexOf(1) > -1 !== b.indexOf(1) > -1) return 'NO';
  return 'YES';
}(readline(), readline()));

function main(){
    var a = readline(),
        b = readline();
    if ( a.length != b.length ){
        print("NO");
        return;
    }
    if ( a == b ){
        print("YES");
        return;
    }
    if ( a.match(/1/) && b.match(/1/) ){
        print("YES");
    }
    else{
        print("NO");
    }
}

main();

function main()
{
    var a = readline(),
        b = readline();
    if ( a.length != b.length )
    {
        print("NO");
        return;
    }
    if ( a == b )
    {
        print("YES");
        return;
    }
    var cnt1 = 0,
        cnt2 = 0;
    for ( var i = 0; i < a.length; i++ )
    {
        if ( a[i] == "1" )
        {
            cnt1++;
        }
        if ( b[i] == "1" )
        {
            cnt2++;
        }
    }
    if ( cnt1 <= 0 || cnt2 <= 0 )
    {
        print("NO");
    }
    else
    {
        print("YES");
    }
}

main();

function main()
{
    var a = readline(),
        b = readline();
    if ( a.length != b.length )
    {
        print("NO");
        return;
    }
    if ( a == b )
    {
        print("YES");
        return;
    }
    if ( a.match(/1/) && b.match(/1/) )
    {
        print("YES");
    }
    else
    {
        print("NO");
    }
}

main();

var x = readline();
var y = readline();

if ((x.length != y.length || x.search("1") == "-1" || y.search("1") == "-1") && x != y) {
	print("NO");
} else {
	print("YES");
}

(function main() {
    var s1 = readline();
    var s2 = readline();
    if (s1.length != s2.length) {
        print('NO');
        return;
    }
    if (s1 == s2 || s1.match(/1/) && s2.match(/1/))
        print('YES');
    else
        print('NO');
})();

print(function(a, b) {
  if (a.length != b.length) return 'NO';
  if (a.length === 1 && a !== b) return 'NO'
  if (a.indexOf(1) === -1 && b.indexOf(1) > -1) return 'NO';
  return 'YES';
}(readline(), readline()));

print(function(a, b) {
  if (a.length != b.length) return 'NO';
  if (a.indexOf(1) === -1 && b.indexOf(1) > -1) return 'NO';
  return 'YES';
}(readline(), readline()));

function main()
{
    var a = readline(),
        b = readline();
    if ( a.length != b.length )
    {
        print("NO");
        return;
    }
    var cnt1 = 0,
        cnt2 = 0;
    for ( var i = 0; i < a.length; i++ )
    {
        if ( a[i] == "1" )
        {
            cnt1++;
        }
        if ( b[i] == "1" )
        {
            cnt2++;
        }
    }
    if ( cnt1 >= cnt2 )
    {
        print("YES");
    }
    else
    {
        print("NO");
    }
}

main();

function main()
{
    var a = readline(),
        b = readline();
    if ( a.length != b.length )
    {
        print("NO");
        return;
    }
    if ( a == b )
    {
        print("YES");
        return;
    }
    var cnt1 = 0,
        cnt2 = 0;
    for ( var i = 0; i < a.length; i++ )
    {
        if ( a[i] == "1" )
        {
            cnt1++;
        }
        if ( b[i] == "1" )
        {
            cnt2++;
        }
    }
    if ( cnt1 <= 0 && cnt2 <= 0 )
    {
        print("NO");
    }
    else
    {
        print("YES");
    }
}

main();

var x = readline();
var y = readline();

if (x.length != y.length || x.search("1") == "-1" || y.search("1") == "-1") {
	print("NO");
} else {
	print("YES");
}

function count(l) {
    if (l)
        return l.length;
    return 0;
}

(function main() {
    var s1 = readline();
    var s2 = readline();
    if (s1.length != s2.length) {
        print('NO');
        return;
    }
    var n1 = count(s1.match(/1/g));
    var n2 = count(s2.match(/1/g));
    if (n1 >= n2)
        print('YES');
    else
        print('NO');
})();


Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?

The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.

Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.

const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, k, m], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
let start = 0;
let end = n - 1;
let endCount = 0;

arr.sort((eleA, eleB) => eleA - eleB);

let avg = arr.reduce((ac, c) => ac + c) / n;

if (n <= m) {
    console.log(Math.min(m - n + 1, k) + arr[n - 1]);
} else {
    for (let i = 0; i < m; i++) {
        if (end < start) {
           // console.log('Too much');

            break;
        }

        let newAvg1 = ((n - start) * avg - arr[start]) / (n - start - 1);
        const newAvg2 = avg + 1 / (n - start);

        if (end === start) {
            newAvg1 = 0;
        }

        //console.log('NEW avg', avg, newAvg1, newAvg2);

        if (avg >= newAvg1 && avg >= newAvg2) {
          //  console.log('Worse');
            break;
        }

        if (newAvg1 < newAvg2) {
            endCount++;
            if (endCount === k) {
                end--;
                endCount = 0;
            }

            avg = newAvg2;

            //console.log('Choose 2');
        } else {
            start++;
            avg = newAvg1;

           // console.log('Choose 1');
        }
    }

    console.log(avg);
}

const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, k, m], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
let start = 0;
let end = n - 1;
let endCount = 0;

arr.sort((eleA, eleB) => eleA - eleB);

if (n <= m) {
    console.log(Math.min(m - n + 1, k) + arr[n - 1]);
} else {
    let i;
    let same = 0;

    for (i = 0; i < m; i++) {
        if (arr[i] === arr[n - 1]) {
            same = 1;
            break;
        }
    }

    if (same) {
        console.log(arr[i] + (m - i) / (n - i));
    } else {
        console.log(arr.slice(m).reduce((acc, c) => acc + c) / (n - m));
    }

}

const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, k, m], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
let start = 0;
let end = n - 1;
let endCount = 0;

arr.sort((eleA, eleB) => eleA - eleB);

if (n <= m) {
    console.log(Math.min(m - n + 1, k) + arr[n - 1]);
} else {
    let i;

    for (i = 0; i < m; i++) {
        if (arr[i] === arr[n - 1]) {
            break;
        }
    }

    console.log(arr[i] + (m - i) / (n - i));
}

const fs = require('fs');
const stdinBuffer = fs.readFileSync(0).toString('utf8');
const [[n, k, m], arr] = stdinBuffer.split('\n').map((line) =>
    line.split(' ').map((ele) => parseInt(ele))
);
let start = 0;
let end = n - 1;
let endCount = 0;

arr.sort((eleA, eleB) => eleA - eleB);

let avg = arr.reduce((ac, c) => ac + c) / n;

for (let i = 0; i < m; i++) {
    if (end < start) {
       // console.log('Too much');

        break;
    }

    let newAvg1 = ((n - start) * avg - arr[start]) / (n - start - 1);
    const newAvg2 = avg + 1 / (n - start);

    if (end === start) {
        newAvg1 = 0;
    }

    //console.log('NEW avg', avg, newAvg1, newAvg2);

    if (avg >= newAvg1 && avg >= newAvg2) {
      //  console.log('Worse');
        break;
    }

    if (newAvg1 < newAvg2) {
        endCount++;
        if (endCount === k) {
            end--;
            endCount = 0;
        }

        avg = newAvg2;

        //console.log('Choose 2');
    } else {
        start++;
        avg = newAvg1;

       // console.log('Choose 1');
    }
}

console.log(avg);


Kuznecov likes art, poetry, and music. And strings consisting of lowercase English letters.Recently, Kuznecov has found two strings, $$$a$$$ and $$$b$$$, of lengths $$$n$$$ and $$$m$$$ respectively. They consist of lowercase English letters and no character is contained in both strings. Let another string $$$c$$$ be initially empty. Kuznecov can do the following two types of operations:  Choose any character from the string $$$a$$$, remove it from $$$a$$$, and add it to the end of $$$c$$$.  Choose any character from the string $$$b$$$, remove it from $$$b$$$, and add it to the end of $$$c$$$. But, he can not do more than $$$k$$$ operations of the same type in a row. He must perform operations until either $$$a$$$ or $$$b$$$ becomes empty. What is the lexicographically smallest possible value of $$$c$$$ after he finishes?A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \neq y$$$;  in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1\leq n,m,k \leq 100$$$) — parameters from the statement. The second line of each test case contains the string $$$a$$$ of length $$$n$$$. The third line of each test case contains the string $$$b$$$ of length $$$m$$$.  The strings contain only lowercase English letters. It is guaranteed that no symbol appears in $$$a$$$ and $$$b$$$ simultaneously.

In each test case, output a single string $$$c$$$ — the answer to the problem.

3

6 4 2

aaaaaa

bbbb

5 9 3

caaca

bedededeb

7 7 1

noskill

wxhtzdy

NoteIn the first test case, it is optimal to take two 'a's from the string $$$a$$$ and add them to the string $$$c$$$. Then it is forbidden to take more characters from $$$a$$$, hence one character 'b' from the string $$$b$$$ has to be taken. Following that logic, we end up with $$$c$$$ being 'aabaabaa' when string $$$a$$$ is emptied.In the second test case it is optimal to take as many 'a's from string $$$a$$$ as possible, then take as many 'b's as possible from string $$$b$$$. In the end, we take two 'c's from the string $$$a$$$ emptying it.

process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let iter = parseInt(readline());
  for (let i = 0; i < iter; i++) {
    let nmk = readline().split(" ").map(Number);
    let a = readline().split("").sort();
    let b = readline().split("").sort();
    print(DistinctC(a, b, nmk[2]));
  }
}

function DistinctC(a, b, k) {
  let taken_a = 0;
  let taken_b = 0;
  let i = 0;
  let j = 0;
  let c = "";
  while (i < a.length && j < b.length) {
    if (taken_a < k && taken_b < k) {
      if (a[i] < b[j]) {
        c += a[i];
        i++;
        taken_a++;
        taken_b = 0;
      } else {
        c += b[j];
        j++;
        taken_b++;
        taken_a = 0;
      }
    } else if (taken_a == k) {
      c += b[j];
      j++;
      taken_b++;
      taken_a = 0;
    } else {
      c += a[i];
      i++;
      taken_a++;
      taken_b = 0;
    }
  }
  return c;
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');

let currentline = 0;
function readline(){
    return input[currentline++];
}
let t = +readline();

while(t--){
    let [n,m,k] = readline().split(' ').map(x => +x);
    let a = readline().trim().split('').sort();
    let b = readline().trim().split('').sort();
    console.log(`${solve(a, b, n, m, k)}`)
}

function solve(str1, str2, n, m, k){
    let result = '';
    let idx1 = 0;
    let idx2 = 0;
    let count = k;
    let next;

    if(str1[idx1] < str2[idx2]){
        result += str1[idx1]
        idx1++;
        next = 'b';
    }else{
        result += str2[idx2]
        idx2++;
        next = 'a';
    }

    while(idx1 < n && idx2 < m){
        if(str1[idx1] <= str2[idx2] && next === 'a'){
            result += str1[idx1];
            idx1++;
            next = 'b';
            count = k;
        }else if(str2[idx2] <= str1[idx1] && next === 'b'){
            result += str2[idx2]
            idx2++;
            next = 'a';
            count = k;
        }else{
            if(str1[idx1] <= str2[idx2] && count > 1){
                result += str1[idx1];
                idx1++;
                count--;
                next = 'b';
            }else if(str2[idx2] <= str1[idx1] && count >1){
                result += str2[idx2]
                idx2++;
                next = 'a';
                count--;
            }else{
                if(next === 'a'){
                result += str1[idx1];
                idx1++;
                next = 'b';
                count = k;
             }else{
                result += str2[idx2]
                idx2++;
                next = 'a';
                count = k;
                }
            }
        }
    }
    return result;
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function 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, m, k] = readline().split(' ').map(Number);
        let a = readline().split('').sort().join('');;
        let b = readline().split('').sort().join('');;
        let c = '';
        let pA = 0;
        let pB = 0;
        let opA = 0;
        let opB = 0;

        while (pA < a.length && pB < b.length) {
            if (a[pA] < b[pB] && opA < k) {
                c += a[pA];
                opB = 0;
                pA++;
                opA++;
            } else if (opB < k) {
                opA = 0;
                c += b[pB];
                pB++;
                opB++
            } else {
                c += a[pA];
                opB = 0;
                pA++;
                opA++;
            }
        }

        output(c);
    }
}

'use strict';

function solve(n, m, k, a, b) {
  a.sort((a, b) => b - a);
  b.sort((a, b) => b - a);
  const res = [];
  let pre = 0,
      count = 0;
  while (a.length && b.length) {
    if (a[a.length - 1] < b[b.length - 1]) {
      if (pre === 0 && count === k) {
        res.push(b.pop());
        pre = 1;
        count = 1;
      } else {
        if (pre === 1) {
          pre = 0;
          count = 0;
        }
        count++;
        res.push(a.pop());
      }
    } else {
      if (pre === 1 && count === k) {
        res.push(a.pop());
        pre = 0;
        count = 1;
      } else {
        if (pre === 0) {
          pre = 1;
          count = 0;
        }
        count++;
        res.push(b.pop());
      }
    }
  }
  return res.map(num => String.fromCharCode(num + 97)).join('');
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const [n, m, k] = (await read()).split(' ').map(Number);
      const a = (await read()).split('').map(ch => ch.charCodeAt(0) - 97);
      const b = (await read()).split('').map(ch => ch.charCodeAt(0) - 97);
      res.push(solve(n, m, k, a, b));
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

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

let lines = -1,
  n,
  m,
  k,
  a,
  b;

const solve = (a, b, n, m, k) => {
  let temp_a = k,
    temp_b = k,
    sort_a = a.sort(),
    sort_b = b.sort(),
    c = [],
    i = 0;

  while (n > 0 && m > 0) {
    if ((sort_a[i] < sort_b[i] && temp_a !== 0) || temp_b === 0) {
      c.push(sort_a.shift());
      n--;
      temp_a--;
      temp_b = k;
    } else {
      c.push(sort_b.shift());
      m--;
      temp_b--;
      temp_a = k;
    }
  }
  console.log(c.join(""));
};

rl.on("line", function (line) {
  if (lines !== -1) {
    if (lines % 3 === 0) {
      [n, m, k] = line.split(" ").map(Number);
    }
    if (lines % 3 === 1) {
      a = line.split("");
    }
    if (lines % 3 === 2) {
      b = line.split("");
      // console.log(a, b, n, m, k);
      solve(a, b, n, m, k);
    }
  }
  lines++;
});

//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(){
    // test case in nodeJs
	var t = nextInt();
	while(hasNext()){
		solve();
	}
}

function solve() {
    let n = nextInt();
    let m = nextInt();
    let k = nextInt();
    let stringOne = nextCharArray().sort();
    let stringTwo = nextCharArray().sort();
    let c = [];
    let i = 0, j = 0, counter =[0 ,0];
    while(i < n && j < m) {
        if (stringOne[i].localeCompare(stringTwo[j]) < 0) {
            if (counter[0] < k) {
                c.push(stringOne[i]);
                i++;
                counter[0]++;
                counter[1]=0;
            } else {
                c.push(stringTwo[j]);
                j++;
                counter[0] = 0;
                counter[1]++;
            }
        } else {
            if (counter[1] < k) {
                c.push(stringTwo[j]);
                j++;
                counter[1]++;
                counter[0]=0;
            } else {
                c.push(stringOne[i]);
                i++;
                counter[1] = 0;
                counter[0]++;
            }
        }
    }

    myout(c.join(""));
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
function readLine() {
    return inputString[currentLine++];
};
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
    // cmd(not powershell): node cp.js < input.txt
});

function main() {
    let t = parseInt(readLine());
    while (t-- > 0) {
        console.log(solve());
    }
}
function solve() {
    let res = "";
    const [m, n, k] = readLine().split(" ").map(i => parseInt(i));
    let A = readLine().split("").sort((a, b) => a.localeCompare(b));
    let B = readLine().split("").sort((a, b) => a.localeCompare(b));
    let x = 0, y = 0, xb = 0, yb = 0;
    while (x < A.length && y < B.length) {
        if (((xb < k) && (A[x] < B[y]) || yb >= k)) {
            res += A[x++];
            xb++;
            yb = 0;
        } else {
            res += B[y++];
            yb++;
            xb = 0
        }
    }
    return res;
}

const fs = require('fs');
//const { addLeadingSlash } = require('history/PathUtils');
const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}

function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
function abs(x) {
  return x < 0 ? x*(-1) : x;
}
var T = readline();
for(var qe=1;qe<=T;qe++) {
  var [n, m, k] = readline().split(' ').map((x) => parseInt(x));
  var a = readline().split('');
  var b = readline().split('');
  a.sort();
  b.sort();

  var c = []
  var i = 0, j=0, cntA = 0, cntB = 0;
  while(i<a.length && j<b.length) {

    if(a[i]<=b[j] && cntA < k) {

      while(a[i]<=b[j] && cntA < k) {
        c.push(a[i]);
        i++;
        cntA++;
      }
      cntB = 0;
      continue;
    }
    if(a[i] > b[j] && cntB < k) {

      while(a[i] > b[j] && cntB < k) {
        c.push(b[j]);
        j++;
        cntB++;
      }
      cntA = 0;
      continue;
    }
    if(cntA == k) {
      c.push(b[j]);
      cntA = 0;
      j++
    }
    if(cntB == k) {
      c.push(a[i])
      cntB = 0;
      i++
    }

  }
  var ans = c.join('')

  console.log(ans);
  //fs.appendFileSync('output.txt', ans+'\r\n');

}
//

process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let iter = parseInt(readline());
  for (let i = 0; i < iter; i++) {
    let nmk = readline().split(" ").map(Number);
    let a = readline().split("").sort();
    let b = readline().split("").sort();
    print(DistinctC(a, b, nmk[2]));
  }
}

function DistinctC(a, b, k) {
  let taken_a = 0;
  let taken_b = 0;
  let i = 0;
  let j = 0;
  let c = "";
  while (i < a.length && j < b.length) {
    if (taken_a < k && taken_b < k) {
      if (a[i] < b[j]) {
        c += a[i];
        i++;
        taken_a++;
      } else {
        c += b[j];
        j++;
        taken_b++;
      }
    } else if (taken_a == k) {
      c += b[j];
      j++;
      taken_b=1;
      taken_a = 0;
    } else {
      c += a[i];
      i++;
      taken_a=1;
      taken_b = 0;
    }
  }
  return c;
}

process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let iter = parseInt(readline());
  for (let i = 0; i < iter; i++) {
    let nmk = readline().split(" ").map(Number);
    let a = readline().split("").sort();
    let b = readline().split("").sort();
    print(DistinctC(a.join(""), b.join(""), nmk[2]));
  }
}

function DistinctC(a, b, k) {
  let taken_a = 0;
  let taken_b = 0;
  let i = 0;
  let j = 0;
  let c = "";
  while (i < a.length && j < b.length) {
    if (taken_a < k && taken_b < k) {
      if (a[i] < b[j]) {
        c += a[i];
        i++;
        taken_a++;
      } else {
        c += b[j];
        j++;
        taken_b++;
      }
    } else if (taken_a == k) {
      c += b[j];
      j++;
      taken_b++;
      taken_a = 0;
    } else {
      c += a[i];
      i++;
      taken_a++;
      taken_b = 0;
    }
  }
  return c;
}

process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let iter = parseInt(readline());
  for (let i = 0; i < iter; i++) {
    let nmk = readline().split(" ").map(Number);
    let a = readline().split("").sort();
    let b = readline().split("").sort();
    DistinctC(a, b, nmk[2]);
  }
}

function DistinctC(a, b, k) {
  let taken_a = 0;
  let taken_b = 0;
  let i = 0;
  let j = 0;
  let c = "";
  while (i < a.length && j < b.length) {
    if (taken_a < k && taken_b < k) {
      if (a[i] < b[j]) {
        c += a[i];
        i++;
        taken_a++;
      } else {
        c += b[j];
        j++;
        taken_b++;
      }
    } else if (taken_a == k) {
      c += b[j];
      j++;
      taken_b++;
      taken_a = 0;
    } else {
      c += a[i];
      i++;
      taken_a++;
      taken_b = 0;
    }
  }
  print(c);
}

process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let iter = parseInt(readline());
  for (let i = 0; i < iter; i++) {
    let nmk = readline().split(" ").map(Number);
    let a = readline().split("").sort();
    let b = readline().split("").sort();
    print(DistinctC(a, b, nmk[2]));
  }
}

function DistinctC(a, b, k) {
  let taken_a = 0;
  let taken_b = 0;
  let i = 0;
  let j = 0;
  let c = "";
  while (i < a.length && j < b.length) {
    if (taken_a < k && taken_b < k) {
      if (a[i] < b[j]) {
        c += a[i];
        i++;
        taken_a++;
      } else {
        c += b[j];
        j++;
        taken_b++;
      }
    } else if (taken_a == k) {
      c += b[j];
      j++;
      taken_b++;
      taken_a = 0;
    } else {
      c += a[i];
      i++;
      taken_a++;
      taken_b = 0;
    }
  }
  return c;
}


In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor.On the current level, the hero is facing $$$n$$$ caves. To pass the level, the hero must enter all the caves in some order, each cave exactly once, and exit every cave safe and sound. When the hero enters cave $$$i$$$, he will have to fight $$$k_i$$$ monsters in a row: first a monster with armor $$$a_{i, 1}$$$, then a monster with armor $$$a_{i, 2}$$$ and so on, finally, a monster with armor $$$a_{i, k_i}$$$.The hero can beat a monster if and only if the hero's power is strictly greater than the monster's armor. If the hero can't beat the monster he's fighting, the game ends and the player loses. Note that once the hero enters a cave, he can't exit it before he fights all the monsters in it, strictly in the given order.Each time the hero beats a monster, the hero's power increases by $$$1$$$.Find the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of caves. The $$$i$$$-th of the next $$$n$$$ lines contains an integer $$$k_i$$$ ($$$1 \le k_i \le 10^5$$$) — the number of monsters in the $$$i$$$-th cave, followed by $$$k_i$$$ integers $$$a_{i, 1}, a_{i, 2}, \ldots, a_{i, k_i}$$$ ($$$1 \le a_{i, j} \le 10^9$$$) — armor levels of the monsters in cave $$$i$$$ in order the hero has to fight them. It is guaranteed that the sum of $$$k_i$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.

NoteIn the first test case, the hero has to beat a single monster with armor $$$42$$$, it's enough to have power $$$43$$$ to achieve that.In the second test case, the hero can pass the level with initial power $$$13$$$ as follows:   enter cave $$$2$$$:   beat a monster with armor $$$12$$$, power increases to $$$14$$$;  beat a monster with armor $$$11$$$, power increases to $$$15$$$;   enter cave $$$1$$$:   beat a monster with armor $$$10$$$, power increases to $$$16$$$;  beat a monster with armor $$$15$$$, power increases to $$$17$$$;  beat a monster with armor $$$8$$$, power increases to $$$18$$$.

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = [];
    for (let i = 0; i < n; i++) {
      let [j, ...k] = iInpArr();
      arr.push(k);
    }
    let narr = [];
    for (let i = 0; i < n; i++) {
      let j = arr[i];
      let en = arr[i][0] + 1;
      for (let j = 1; j < arr[i].length; j++) {
        en = Math.max(en, arr[i][j] - j + 1);
      }
      narr.push([en, arr[i].length]);
    }
    narr.sort((a, b) => a[0] - b[0]);
    let ans = narr[0][0],
      to = narr[0][1];
    for (let i = 1; i < narr.length; i++) {
      let j = ans + to;
      if (j < narr[i][0]) ans = narr[i][0] - to;
      to += narr[i][1];
    }
    console.log(ans);
  }
};
solve();

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const k = [];
		for (let i = 0; i < n; i++) {
			k[i] = rna().slice(1);
		}

		const v = [];
		for (const cave of k) {
			let mxpw = 0;
			for (let i = 0; i < cave.length; i++) {
				mxpw = Math.max(mxpw, cave[i] - i);
			}
			v.push([mxpw + 1, mxpw + 1 + cave.length]);
		}
		v.sort((x, y) => x[0] - y[0]);

		let mxd = 0;
		for (let i = 0, curd = 0; i < n - 1; i++) {
			curd += v[i+1][0] - v[i][1];
			mxd = Math.max(mxd, curd);
		}

		const ans = v[0][0] + mxd;
		console.log(ans);
	}
}

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = [];
    for (let i = 0; i < n; i++) {
      let [j, ...k] = iInpArr();
      arr.push(k);
    }
    let narr = [];
    for (let i = 0; i < n; i++) {
      let j = arr[i];
      let en = arr[i][0] + 1;
      for (let j = 1; j < arr[i].length; j++) {
        en = Math.max(en, arr[i][j] - j);
      }
      narr.push([en, arr[i].length]);
    }
    narr.sort((a, b) => a[0] - b[0]);
    let ans = narr[0][0],
      to = narr[0][1];
    for (let i = 1; i < narr.length; i++) {
      let j = ans + to;
      if (j < narr[i][0]) ans = narr[i][0];
      to += narr[i][1];
    }
    console.log(ans);
  }
};
solve();

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const k = [];
		for (let i = 0; i < n; i++) {
			k[i] = rna().slice(1);
		}

		const v = [];
		for (const cave of k) {
			let mxpw = 0;
			for (let i = 0; i < cave.length; i++) {
				mxpw = Math.max(mxpw, cave[i] - i);
			}
			v.push([mxpw + 1, mxpw + 1 + cave.length]);
		}
		v.sort((x, y) => x[0] - y[0]);

		let mxd = 0;
		for (let i = 0; i < n - 1; i++) {
			mxd = Math.max(mxd, Math.max(0, v[i+1][0] - v[i][1]));
		}

		const ans = v[0][0] + mxd;
		console.log(ans);
	}
}


You are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root is vertex $$$1$$$. There is also a string $$$s$$$ denoting the color of each vertex: if $$$s_i = \texttt{B}$$$, then vertex $$$i$$$ is black, and if $$$s_i = \texttt{W}$$$, then vertex $$$i$$$ is white.A subtree of the tree is called balanced if the number of white vertices equals the number of black vertices. Count the number of balanced subtrees.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. In this problem, all trees have root $$$1$$$.The tree is specified by an array of parents $$$a_2, \dots, a_n$$$ containing $$$n-1$$$ numbers: $$$a_i$$$ is the parent of the vertex with the number $$$i$$$ for all $$$i = 2, \dots, n$$$. The parent of a vertex $$$u$$$ is a vertex that is the next vertex on a simple path from $$$u$$$ to the root.The subtree of a vertex $$$u$$$ is the set of all vertices that pass through $$$u$$$ on a simple path to the root. For example, in the picture below, $$$7$$$ is in the subtree of $$$3$$$ because the simple path $$$7 \to 5 \to 3 \to 1$$$ passes through $$$3$$$. Note that a vertex is included in its subtree, and the subtree of the root is the entire tree.  The picture shows the tree for $$$n=7$$$, $$$a=[1,1,2,3,3,5]$$$, and $$$s=\texttt{WBBWWBW}$$$. The subtree at the vertex $$$3$$$ is balanced.

The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 4000$$$) — the number of vertices in the tree. The second line of each test case contains $$$n-1$$$ integers $$$a_2, \dots, a_n$$$ ($$$1 \le a_i < i$$$) — the parents of the vertices $$$2, \dots, n$$$. The third line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of the characters $$$\texttt{B}$$$ and $$$\texttt{W}$$$ — the coloring of the tree. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of balanced subtrees.

NoteThe first test case is pictured in the statement. Only the subtrees at vertices $$$2$$$ and $$$3$$$ are balanced.In the second test case, only the subtree at vertex $$$1$$$ is balanced.In the third test case, only the subtrees at vertices $$$1$$$, $$$3$$$, $$$5$$$, and $$$7$$$ are balanced.

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
class graph {
  constructor() {
    this.list = {};
  }
  add(v) {
    if (this.list[v] !== undefined) return false;
    this.list[v] = [];
    return true;
  }
  addE(v, e) {
    this.list[v].push(e);
  }
}
let global = 0;
const dfs = (g, c) => {
  const helper = (v) => {
    if (g.list[v] === undefined) {
      if (c[v - 1] === "W") return [0, 1];
      else return [1, 0];
    }
    let b = 0,
      w = 0;
    let arr = g.list[v];
    for (let i = 0; i < arr.length; i++) {
      let k = helper(arr[i]);
      b += k[0];
      w += k[1];
    }
    if (c[v - 1] === "W") w++;
    else b++;
    if (b === w) global++;
    return [b, w];
  };
  helper(1);
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    let colour = stringArr();
    let g = new graph();
    g.add(1);
    for (let i = 0, j = 2; i < n - 1; i++, j++) {
      g.add(arr[i]);
      g.addE(arr[i], j);
    }
    dfs(g, colour);
    console.log(global);
    global = 0;
  }
};
solve();

'use strict';
const readline = require('readline');
const util = require('util');
const lineReader = readline.createInterface({
    input: process.stdin,
});
let inputPos = 0;
const inputWords = [];
lineReader.on('line', (line) => {
    inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));
});
lineReader.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(inputWords[inputPos++]));
}
function nextStr() {
    return inputWords[inputPos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
const INF = Infinity;
let n;
let p;
let col;
let adjList;
let bc;
let cnt;
function f(u, par) {
    cnt[u] = 1;
    if (col[u - 1] == 'B') {
        bc[u] = 1;
    }
    for (let v of adjList[u]) {
        if (v == par) {
            continue;
        }
        f(v, u);
        bc[u] += bc[v];
        cnt[u] += cnt[v];
    }
}
function solve() {
    bc = af(n + 1).fill(0);
    cnt = af(n + 1).fill(0);
    f(1, INIT);
    let ans = 0;
    for (let u = 1; u <= n; u++) {
        if (bc[u] + bc[u] == cnt[u]) {
            ans++;
        }
    }
    // printf("%j\n%j\n", bc, cnt);
    return ans;
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        n = nextInt();
        p = af(n + 1);
        adjList = Array.from({ length: n + 1 });
        for (let i = 1; i <= n; i++) {
            adjList[i] = [];
        }
        for (let i = 2; i <= n; i++) {
            p[i] = nextInt();
            adjList[p[i]].push(i);
        }
        col = nextStr();
        printf("%d\n", solve());
    }
}

function solve(inp) {
  var t = inp.nextNum();

  while(t--) {
    const n = inp.nextNum();
    const tree = new Array(n + 1);
    for (let i = 1; i <= n; i++) tree[i] = [];
    const par = inp.nextNumArr();
    for(let i = 0; i < n - 1; i++) {
      const p = par[i];
      tree[p].push(i + 2);
    }
    const col = inp.nextLine();

    const dfs = (i) => {
      var w = col.charAt(i - 1) === 'B' ? 1 : -1;
      var c = 0;
      tree[i].forEach((j) => {
        const [cw, cc] = dfs(j);
        w += cw;
        c += cc;
      });
      if (w === 0) c++;
      return [w, c];
    }

    const [w, c] = dfs(1);
    console.log(c);
  }
}

class Input {
    constructor(lines) {
        this.lines = lines;
        this.next = 0;
    }

    addLine(line) {
        this.lines.push(line)
    }

    hasLine() {
       return this.lines.size() > 0;
    }

    nextLine() {
        const line = this.lines[this.next];
        if (line) {
            this.next++;
        }
        return line;
    }

    nextNum() {
      return Number(this.nextLine());
    }

    nextNumArr() {
      return inp.nextLine().split(" ").map(x => Number(x));
    }
}

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

const inp = new Input([]);

readline.on('line', line => {
    inp.addLine(line);
});

readline.on('close', () => {
    solve(inp);
});

'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, s) {
  const g = Array.from({
    length: n + 1
  }, () => []);
  for (let i = 0; i < n - 1; i++) {
    const u = a[i],
          v = i + 2;
    g[u].push(v);
  }
  let res = 0;
  const dfs = i => {
    let b = 0,
        w = 0;
    if (s[i - 1] === 'B') b++;else w++;
    for (let child of g[i]) {
      const [rb, rw] = dfs(child);
      b += rb;
      w += rw;
    }
    if (b === w) res++;
    return [b, w];
  };
  dfs(1);
  return res.toString();
}

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

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

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = new Array(N);
		for(var i = 0; i < N; i++){
			list[i] = {
				child : [],
				s : "",
				b : 0,
				w : 0
			};
		}
		for(var i = 1; i < N; i++){
			var p = nextInt() - 1;
			list[i].child.push(p);
			list[p].child.push(i);
		}
		var S = next();
		for(var i = 0; i < N; i++){
			list[i].s = S[i];
		}
		var output = 0;
		dfs(0, -1);
		myout(output);

		function dfs(now, parent){
			var b = 0;
			var w = 0;
			var child = list[now].child;
			for(var j = 0; j < child.length; j++){
				var nx = child[j];
				if(nx != parent){
					var ret = dfs(nx, now);
					b += ret.b;
					w += ret.w;
				}
			}
			if(list[now].s == "W"){
				w++;
			}else{
				b++;
			}
			if(b == w){
				output++;
			}
			return {
				b : b,
				w : w
			};
		}
	}
}

'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 P = ra();
  P = P.map(a=>a-1);
  let S = readline()
  // PROCESSING:
  let ans = 0;
  let G = {};
  for (let i=1; i<n; i++){
    if (!G[P[i-1]]) G[P[i-1]] = [];
    G[P[i-1]].push(i);
  }
  //LT({n, P, S, G});
  let dfs = (v)=>{
    let white = 0, black = 0;
    if (S[v]=='B') black++; else white++;
    let children = G[v]||[];
    //L({v, children})
    for (let i=0; i<children.length; i++){
      let res = dfs(children[i]);
      white += res.white
      black += res.black
    }
    if (white==black) ans++;
    return {white, black};
  };
  dfs(0);
  return ans;
};

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const ps = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++]
        output[i] = solve(n, ps, arr)
    }
    console.log(output.join('\n'))
// })()
})

class Queue {
    constructor() {
        this.map = {}
        this.first = 0
        this.last = -1
    }
    push(...args) {
        let i = 0
        if (!this.length) {
            this.first = this.last = 0
            this.map[this.first] = args[i++]
        }
        for (; i < args.length; i++) {
            this.map[++this.last] = args[i]
        }
    }
    unshift(...args) {
        let i = 0
        if (!this.length) {
            this.first = this.last = 0
            this.map[this.first] = args[i++]
        }
        for (; i < args.length; i++) {
            this.map[--this.first] = args[i]
        }
    }
    pop() {
        const r = this.map[this.last]
        delete this.map[this.last]
        this.last--
        return r
    }
    shift() {
        const r = this.map[this.first]
        delete this.map[this.first]
        this.first++
        return r
    }
    get length() {
        if (this.first > this.last) return 0
        return this.last - this.first + 1
    }
    getLast() {
        return this.map[this.last]
    }
}

function solve(n, ps, arr) {
    const adj = {}
    ps.forEach((p, i) => {
        const a = i + 2
        const b = p
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
    return dfs(adj, 1, arr)
}
function dfs(adj, r, arr) {
    // const stack = [[r, 0, -1]]
    const stack = new Queue()
    stack.push([r, 0, -1])
    const bs = []
    const ws = []
    let ans = 0
    while (stack.length) {
        const [u, i, p] = stack.getLast()// stack[stack.length - 1]
        // visited[u] = 1

        const nb = adj[u] || []
        if (!i) {
            // first visited
        }
        if (i < nb.length) {
            // stack[stack.length - 1][1]++
            stack.getLast()[1]++
            const v = nb[i]
            // if (!visited[v]) { // has circle
            if (v !== p) {
                stack.push([v, 0, u])
            }
        } else {
            // last visited
            stack.pop()
            bs[u] = arr[u - 1] === 'B' ? 1 : 0
            ws[u] = arr[u - 1] === 'W' ? 1 : 0
            ;(adj[u] || []).forEach(v => {
                if (v === p) return
                bs[u] += bs[v]
                ws[u] += ws[v]
            })
            if (bs[u] === ws[u]) ans++
        }
    }
    // console.log(bs, ws)
    return ans
}

//let { readline, print } = require('@ip-algorithmics/codeforces-io');
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var t = +readline();
while (t--) {
    var n = readline().split(' ').map(function (v) { return +v; })[0];
    var a = __spreadArray([0, 0], readline().split(' ').map(function (v) { return +v; }), true);
    var s = readline().split('');
    var c = Array(n + 1);
    for (var i = 0; i <= n; i++) {
        c[i] = [];
    }
    for (var i = 1; i <= n; i++) {
        c[a[i]].push(i);
    }
    /*
    function f (v) {
        let balance = 0, count = 0;
        for (let i=0; i<c[v].length; i++) {
            let res = f(c[v][i]);
            balance += res[0];
            count += res[1];
        }
        balance += s[v-1] === 'B' ? 1 : -1;
        count += +!balance;

        return [balance, count];
    }
    */
    var ba = Array(n + 1).fill(0);
    var co = Array(n + 1).fill(0);
    var st = Array(n + 1).fill(0);
    var sti = Array(n + 1).fill(0);
    var d = 0;
    st[d] = 1;
    root: while (true) {
        ba[d] = co[d] = sti[d] = 0;
        loop: while (true) {
            if (sti[d] < c[st[d]].length) {
                st[d + 1] = c[st[d]][sti[d]];
                d++;
                continue root;
            }
            ba[d] += s[st[d] - 1] === 'B' ? 1 : -1;
            co[d] += +!ba[d];
            if (!d)
                break root;
            d--;
            ba[d] += ba[d + 1];
            co[d] += co[d + 1];
            sti[d]++;
        }
    }
    var ans = co[0];
    //let ans = f(1)[1];
    print(ans);
}

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var t = +readline();
var _loop_1 = function () {
    var n = readline().split(' ').map(function (v) { return +v; })[0];
    var a = __spreadArray([0, 0], readline().split(' ').map(function (v) { return +v; }), true);
    var s = readline().split('');
    var c = Array(n + 1);
    for (var i = 0; i <= n; i++) {
        c[i] = [];
    }
    for (var i = 1; i <= n; i++) {
        c[a[i]].push(i);
    }
    function f(v) {
        var balance = 0, count = 0;
        for (var i = 0; i < c[v].length; i++) {
            var res = f(c[v][i]);
            balance += res[0];
            count += res[1];
        }
        balance += s[v - 1] === 'B' ? 1 : -1;
        count += +!balance;
        return [balance, count];
    }
    var ans = f(1)[1];
    print(ans);
};
while (t--) {
    _loop_1();
}


You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.

The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.

Print the minimum non-zero element before each operation in a new line.

NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.

ip = readline().split(' ');
n = +ip[0], k = +ip[1];
sub = 0;
count = 0;
res = '';
ar = readline().split(' ').map(Number).sort((a,b)=>a-b);

for (i = 0; i < n; i++){
    if (ar[i] - sub > 0){
        res += (ar[i] - sub)+'\n';
        sub = ar[i];
        count++;
    }
    if (count === k) break;
}

for (;count < k;count++){
    res += '0\n';
}
print(res);

function swap(items, firstIndex, secondIndex){
    const temp = items[firstIndex];
    items[firstIndex] = items[secondIndex];
    items[secondIndex] = temp;
}
function partition(items, left, right) {
    var pivot   = items[Math.floor((right + left) / 2)],
        i       = left,
        j       = right;

    while (i <= j) {
        while (items[i] < pivot) {
            i++;
        }
        while (items[j] > pivot) {
            j--;
        }
        if (i <= j) {
            swap(items, i, j);
            i++;
            j--;
        }
    }
    return i;
}
function quickSort(items, left, right) {
    var index;
    if (items.length > 1) {
        left = typeof left != "number" ? 0 : left;
        right = typeof right != "number" ? items.length - 1 : right;
        index = partition(items, left, right);
        if (left < index - 1) {
            quickSort(items, left, index - 1);
        }
        if (index < right) {
            quickSort(items, index, right);
        }
    }
    return items;
}

function unique(arr) {
  var obj = {};

  for (var i = 0; i < arr.length; i++) {
    var str = arr[i];
    obj[str] = true;
  }

  return Object.keys(obj); // или собрать ключи перебором для IE8-
}

function main(r) {
    var k = r().split(' ');
    var n = +k[0];
    k = +k[1];
    var a = r().split(' ').map(v => +v)
    a = quickSort(a);
    a = unique(a)
    var t = 0;
    for(var i = 0 ; i < k; i++) {
        if(a[i]){
            print(a[i] - t);
            t += a[i] - t;
        }
        else{
            print(0);
        }
    }

}
main(readline);

function doIt() {
    var repeats = readline().split(' ').map(v=>+v)[1];
    var arr = readline().split(' ').sort((a, b) => a - b);

    var prev = 0;

    for(var i = 0; i < arr.length; i++) {
        var v = arr[i];
        if(v === prev) continue;

        print(v - prev);
        if(!(--repeats)) break;

        prev = v;
    }

    while(repeats--) print(0);
}

doIt();

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

let l = 0;
let op = []
let array = []

rl.on('line', (input) => {
    if (l === 0) {
        op = input.split(' ').map(function (item) {
            return parseInt(item, 10);
        });
    } else if (l === 1) {
        rl.close();

        array = input.split(' ').map(function (item) {
            return parseInt(item, 10);
        });

        array.sort(function sortNumber(a, b) {
            return a - b;
        })
        let mn = array[0]
        console.log(mn)
        let amm=mn;
        let st=0
        let res=''
        for (let i = 0; i < op[1] - 1; i++) {
            let min = mn
            if (mn > 0) {
                mn = -1
                for (let j = st; j < array.length&&mn==-1; j++) {
                    array[j] -= amm;
                    if (array[j] > 0 && mn === -1) {
                        mn = array[j]
                        amm+=mn
                        res+=mn+'\n'
                    } else if(mn==-1){
                        st++
                    }
                }
            }
            if (mn === -1) {
                res+='0'+'\n'
            }
        }
        console.log(res)
    }
    l++
});

function swap(items, firstIndex, secondIndex){
    const temp = items[firstIndex];
    items[firstIndex] = items[secondIndex];
    items[secondIndex] = temp;
}
function partition(items, left, right) {
    var pivot   = items[Math.floor((right + left) / 2)],
        i       = left,
        j       = right;

    while (i <= j) {
        while (items[i] < pivot) {
            i++;
        }
        while (items[j] > pivot) {
            j--;
        }
        if (i <= j) {
            swap(items, i, j);
            i++;
            j--;
        }
    }
    return i;
}
function quickSort(items, left, right) {
    var index;
    if (items.length > 1) {
        left = typeof left != "number" ? 0 : left;
        right = typeof right != "number" ? items.length - 1 : right;
        index = partition(items, left, right);
        if (left < index - 1) {
            quickSort(items, left, index - 1);
        }
        if (index < right) {
            quickSort(items, index, right);
        }
    }
    return items;
}

function unique(arr) {
  var obj = {};

  for (var i = 0; i < arr.length; i++) {
    var str = arr[i];
    obj[str] = true;
  }

  return Object.keys(obj); // или собрать ключи перебором для IE8-
}

function main(r) {
    var k = r().split(' ');
    var n = +k[0];
    k = +k[1];
    var a = r().split(' ').map(v => +v)
    a = quickSort(a);
    a = unique(a)
    print(a)
    var t = 0;
    for(var i = 0 ; i < k; i++) {
        if(a[i]){
            print(a[i] - t);
            t += a[i] - t;
        }
        else{
            print(0);
        }
    }

}
main(readline);


Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!The computers bought for the room were different. Some of them had only USB ports, some — only PS/2 ports, and some had both options.You have found a price list of a certain computer shop. In it, for m mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.

The first line contains three integers a, b and c (0 ≤ a, b, c ≤ 105)  — the number of computers that only have USB ports, the number of computers, that only have PS/2 ports, and the number of computers, that have both options, respectively. The next line contains one integer m (0 ≤ m ≤ 3·105)  — the number of mouses in the price list. The next m lines each describe another mouse. The i-th line contains first integer vali (1 ≤ vali ≤ 109)  — the cost of the i-th mouse, then the type of port (USB or PS/2) that is required to plug the mouse in.

Output two integers separated by space — the number of equipped computers and the total cost of the mouses you will buy.

NoteIn the first example you can buy the first three mouses. This way you will equip one of the computers that has only a USB port with a USB mouse, and the two PS/2 mouses you will plug into the computer with PS/2 port and the computer with both ports.

function main() {
    var data = readline().split(' ').map(Number);
    var a = data[0];
    var b = data[1];
    var c = data[2];

    var m = Number(readline());

    var arr = [];
    for(var i=0;i<m;i++){
        var line = readline().split(' ');
        arr.push({
            price: Number(line[0]),
            type: line[1]
        });
    }
    arr.sort((a, b) => a.price - b.price);
    var resNumber = 0;
    var resPrice = 0;

    for(var i=0;i<arr.length;i++){
        var current = arr[i];
        if(a > 0 && current.type=="USB"){
            a--;
            resNumber++;
            resPrice += current.price;
        } else if(b>0 && current.type == "PS/2"){
            b--;
            resNumber++;
            resPrice += current.price;
        } else if(c>0){
            c--;
            resNumber++;
            resPrice += current.price;
        }
    }

    print(resNumber + " " + resPrice);
}

main()

function main() {
    var data = readline().split(' ').map(Number);
    var a = data[0];
    var b = data[1];
    var c = data[2];

    var m = Number(readline());

    var arr = [];
    for(var i=0;i<m;i++){
        var line = readline().split(' ');
        arr.push({
            price: Number(line[0]),
            type: line[1]
        });
    }
    arr.sort((a, b) => a.price > b.price);
    var resNumber = 0;
    var resPrice = 0;

    for(var i=0;i<arr.length;i++){
        var current = arr[i];
        if(a > 0 && current.type=="USB"){
            a--;
            resNumber++;
            resPrice += current.price;
        } else if(b>0 && current.type == "PS/2"){
            b--;
            resNumber++;
            resPrice += current.price;
        } else if(c>0){
            c--;
            resNumber++;
            resPrice += current.price;
        }
    }

    print(resNumber + " " + resPrice);
}

main()