Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 people. Of course, each of n candidates can settle in only one of the cities. Thus, first some subset of candidates of size n1 settle in the first city and then some subset of size n2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home.To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth ai among all its residents divided by the number of them (n1 or n2 depending on the city). The division should be done in real numbers without any rounding.Please, help authorities find the optimal way to pick residents for two cities.

The first line of the input contains three integers n, n1 and n2 (1 ≤ n, n1, n2 ≤ 100 000, n1 + n2 ≤ n) — the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), the i-th of them is equal to the wealth of the i-th candidate.

Print one real value — the maximum possible sum of arithmetic means of wealth of cities' residents. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first sample, one of the optimal solutions is to move candidate 1 to the first city and candidate 2 to the second.In the second sample, the optimal solution is to pick candidates 3 and 4 for the first city, and candidate 2 for the second one. Thus we obtain (a3 + a4) / 2 + a2 = (3 + 2) / 2 + 4 = 6.5

"use strict";

/*
let kk = 0;
let readline = function() {
	switch(kk++) {
		case 0: return '4 2 1';
		case 1: return '1 4 2 3';
	}
};
let write = console.log.bind();
*/

Array.prototype.sum = function(arr) {
	let s = 0;
	for ( let i = 0; i < this.length; i++ )
		s += this[i];

	return s;
};

let input = readline().split(' ').map(e => +e),
	n = input[0],
	n1 = input[1],
	n2 = input[2],
	A = readline().split(' ').map(e => +e).sort((a, b) => a - b),
	min = Math.min(n1, n2),
	max = n1 === min ? n2 : n1;

let opti = A.splice(-min).sum()/min;
opti += A.splice(-max).sum()/max;
write(opti.toFixed(6))

var mainFunc = function(arr, amount1, amount2)
	{
		var sum = function(arr, amount)
		{
			var sumIn = 0;
			for (var i = 0; i <= amount - 1; i++)
			{
				sumIn += arr[i];
			}
			sumIn /= amount;
			return sumIn;
		}
		arr = arr.slice(0, amount1 + amount2 + 1);
		if (amount1 < amount2)
			{
				var sumAmount1 = sum(arr, amount1);
				arr = arr.slice(amount1, arr.length);
				var sumAmount2 = sum(arr, amount2);
				return sumAmount1 + sumAmount2;
			}
		else
			{
				var sumAmount1 = sum(arr, amount2);
				arr = arr.slice(amount2, arr.length);
				var sumAmount2 = sum(arr, amount1);
				return sumAmount1 + sumAmount2;
			}
	}

var decrease = function(a,b)
	{
		return b - a;
	}
var toArrayNumber = function(arr)
	{
		for (var i = 0; i <= arr.length - 1; i++)
		{
			arr[i] = +arr[i];
		}
		return arr;
	}

{
var input1 = readline();
input1 = input1.split(' ');
var num1 = +input1[1], num2 = +input1[2];
var input2 = readline();
input2 = input2.split(' ');
input2 = toArrayNumber(input2);
input2 = input2.sort(decrease);
print(mainFunc(input2, num1, num2).toFixed(8));

}

function sortNumber(a,b) {
    return a - b;
}

    function sa(){
        var firstLine =readline().split(" ");
        var n1 = Math.min(Number(firstLine[1]), Number(firstLine[2]));
        var n2 = Math.max(Number(firstLine[1]), Number(firstLine[2]));
        var n = Number(firstLine[1]) + Number(firstLine[2]);
        var data = readline().split(" ").map(Number);
        data.sort(sortNumber).reverse();
        var sum = 0;
        var sum1 = 0;
        var sum2 = 0;
        for(var i=0;i<n;i++){
            if(i<n1){
                sum1 += data[i];
            } else {
                sum2 += data[i];
            }
        }

        print(sum1/n1 + sum2/n2)
    }
    sa();

function main() {
    var number1 = readline().split(' ');
    var a = readline().split(' ').map(function(val){return val * 1;});
    var n = number1[0], n1 = number1[1], n2 = number1[2];
    a.sort(function(a, b){return a - b});

    var sum1 = 0;
    for (var i = a.length - 1; i >= a.length - Math.min(n1, n2); --i) {
        sum1 += a[i];
    }

    var sum2 = 0;
    for (var j = a.length - 1 - Math.min(n1, n2); j >= a.length - n1 - n2; --j) {
        sum2 += a[j];
    }

    print(sum1 / Math.min(n1, n2) + sum2 / Math.max(n1, n2));
}

main();

function main(){
    var numbers = readline().split(" ");
    var max = Math.max(numbers[1],numbers[2]);
    var min = Math.min(numbers[1],numbers[2]);

    var vals = readline()
        .split(" ")
        .map(function(a){return a*1})
        .sort(function(a,b){return b-a});

    //print(JSON.stringify(vals))

    var avg1 = 0;
    var avg2 = 0;

    for(var i=0;i<min;i++){
        avg1+= vals.shift()/min;
    }

    for(i=0;i<max;i++){
        avg2+= vals.shift()/max;
    }

    // print(avg1/min+avg2/max,avg1,avg2,min,max);
    print(avg1+avg2);
}

main();

var maxAveragesSum = function( n1, n2, a ) {
  a.sort( (a, b) => b - a );
  var sum;
  if ( n1 < n2 ) {
    sum = a.slice( 0, n1 ).reduce( (a,b) => a + b, 0 ) / n1 + a.slice( n1, n2 + n1 ).reduce( (a,b) => a + b, 0 ) / n2;
  } else {
    sum = a.slice( 0, n2 ).reduce( (a,b) => a + b, 0 ) / n2 + a.slice( n2, n1 + n2 ).reduce( (a,b) => a + b, 0 ) / n1;
  }
  return sum;
};

var input = readline().split( " " ).map( i => parseInt( i, 10 ) );
var n = input[ 0 ];
var n1 = input[ 1 ];
var n2 = input[ 2 ];
var a = readline().split( " " ).map( i => parseInt( i, 10 ) );

print( maxAveragesSum( n1, n2, a ) );

var mainFunc = function(arr, amount1, amount2)
	{
		var sum = function(arr, amount)
		{
			var sumIn = 0;
			for (var i = 0; i <= amount - 1; i++)
			{
				sumIn += arr[i];
			}
			sumIn /= amount;
			return sumIn;
		}
		arr = arr.slice(0, amount1 + amount2 + 1);
		if (amount1 < amount2)
			{
				var sumAmount1 = sum(arr, amount1);
				arr = arr.slice(amount1 + 1, arr.length - 1);
				var sumAmount2 = sum(arr, amount2);
				return sumAmount1 + sumAmount2;
			}
		else
			{
				var sumAmount1 = sum(arr, amount2);
				arr = arr.slice(amount2, arr.length);
				var sumAmount2 = sum(arr, amount1);
				return sumAmount1 + sumAmount2;
			}
	}

var decrease = function(a,b)
	{
		return b - a;
	}
var toArrayNumber = function(arr)
	{
		for (var i = 0; i <= arr.length - 1; i++)
		{
			arr[i] = +arr[i];
		}
		return arr;
	}

{
var input1 = readline();
input1 = input1.split(' ');
var num1 = +input1[1], num2 = +input1[2];
var input2 = readline();
input2 = input2.split(' ');
input2 = toArrayNumber(input2);
input2 = input2.sort(decrease);
print(mainFunc(input2, num1, num2).toFixed(8));

}

    function sa(){
        var firstLine =readline().split(" ");
        var n1 = Math.min(Number(firstLine[1]), Number(firstLine[2]));
        var n2 = Math.max(Number(firstLine[1]), Number(firstLine[2]));
        var n = Number(firstLine[1]) + Number(firstLine[2]);
        var data = readline().split(" ").map(Number);
        data.sort().reverse();
        print(data);
        var sum = 0;
        var sum1 = 0;
        var sum2 = 0;
        for(var i=0;i<n;i++){
            if(i<n1){
                sum1 += data[i];
            } else {
                sum2 += data[i];
            }
        }

        print(sum1/n1 + sum2/n2)
    }
    sa();

    function sa(){
        var firstLine =readline().split(" ");
        var n1 = Math.min(Number(firstLine[1]), Number(firstLine[2]));
        var n2 = Math.max(Number(firstLine[1]), Number(firstLine[2]));
        var n = Number(firstLine[1]) + Number(firstLine[2]);
        var data = readline().split(" ").map(Number);
        data.sort().reverse();
        var sum = 0;
        var sum1 = 0;
        var sum2 = 0;
        for(var i=0;i<n;i++){
            if(i<n1){
                sum1 += data[i];
            } else {
                sum2 += data[i];
            }
        }

        print(sum1/n1 + sum2/n2)
    }
    sa();

function main() {
    var number1 = readline().split(' ');
    var a = readline().split(' ');
    var n = number1[0], n1 = number1[1], n2 = number1[2];
    a.sort();

    var sum1 = 0;
    for (var i = a.length - 1; i >= a.length - Math.min(n1, n2); --i) {
        sum1 += a[i] * 1;
    }

    var sum2 = 0;
    for (var i = a.length - 1 - Math.min(n1, n2); i >= a.length - n1 - n2; --i) {
        sum2 += a[i] * 1;
    }

    print(sum1, sum2);
    print(sum1 / Math.min(n1, n2) + sum2 / Math.max(n1, n2));
}

main();

function main() {
    var number1 = readline().split(' ');
    var a = readline().split(' ');
    var n = number1[0], n1 = number1[1], n2 = number1[2];
    a.sort();

    var sum1 = 0;
    for (var i = a.length - 1; i >= a.length - Math.min(n1, n2); --i) {
        sum1 += a[i] * 1;
    }

    var sum2 = 0;
    for (var j = a.length - 1 - Math.min(n1, n2); j >= a.length - n1 - n2; --j) {
        sum2 += a[j] * 1;
    }

    print(sum1 / Math.min(n1, n2) + sum2 / Math.max(n1, n2));
}

main();

function main() {
    var number1 = readline().split(' ');
    var a = readline().split(' ').map(function(val){return val * 1;});
    var n = number1[0], n1 = number1[1], n2 = number1[2];
    a.sort();

    var sum1 = 0;
    for (var i = a.length - 1; i >= a.length - Math.min(n1, n2); --i) {
        sum1 += a[i];
    }

    var sum2 = 0;
    for (var j = a.length - 1 - Math.min(n1, n2); j >= a.length - n1 - n2; --j) {
        sum2 += a[j];
    }

    print(sum1 / Math.min(n1, n2) + sum2 / Math.max(n1, n2));
}

main();

function main(){
    var numbers = readline().split(" ");
    var max = Math.max(numbers[1],numbers[2]);
    var min = Math.min(numbers[1],numbers[2]);

    var vals = readline().split(" ").map(function(a){return a*1}).sort(function(a,b){return a<b});

    var avg1 = 0;
    var avg2 = 0;

    for(var i=0;i<min;i++){
        avg1+=vals.shift()/min;
    }

    for(i=0;i<max;i++){
        avg2+=vals.shift()/max;
    }

    // print(avg1/min+avg2/max,avg1,avg2,min,max);
    print(avg1+avg2);
}

main();

function main(){
    var numbers = readline().split(" ");
    var max = Math.max(numbers[1],numbers[2]);
    var min = Math.min(numbers[1],numbers[2]);

    var vals = readline().split(" ").map(function(a){return a*1}).sort(function(a,b){return a<b});

    var avg1 = 0;
    var avg2 = 0;

    for(var i=0;i<min;i++){
        avg1+=vals.shift();
    }

    for(i=0;i<max;i++){
        avg2+=vals.shift();
    }

    // print(avg1/min+avg2/max,avg1,avg2,min,max);
    print(avg1/min+avg2/max);
}

main();

"use strict";
/*
let kk = 0;
let readline = function() {
	switch(kk++) {
		case 0: return '4 2 1';
		case 1: return '1 4 2 3';
	}
};
let write = console.log.bind();
*/

Array.prototype.sum = function(arr) {
	let s = 0;
	for ( let i = 0; i < this.length; i++ )
		s += this[i];

	return s;
};

let input = readline().split(' ').map(e => +e),
	n = input[0],
	n1 = input[1],
	n2 = input[2],
	A = readline().split(' ').map(e => +e).sort(),
	min = Math.min(n1, n2),
	max = n1 === min ? n2 : n1;

let opti = A.splice(-min).sum()/min;
opti += A.splice(-max).sum()/max;

write(opti)


You are the owner of a harvesting field which can be modeled as an infinite line, whose positions are identified by integers.It will rain for the next $$$n$$$ days. On the $$$i$$$-th day, the rain will be centered at position $$$x_i$$$ and it will have intensity $$$p_i$$$. Due to these rains, some rainfall will accumulate; let $$$a_j$$$ be the amount of rainfall accumulated at integer position $$$j$$$. Initially $$$a_j$$$ is $$$0$$$, and it will increase by $$$\max(0,p_i-|x_i-j|)$$$ after the $$$i$$$-th day's rain.A flood will hit your field if, at any moment, there is a position $$$j$$$ with accumulated rainfall $$$a_j>m$$$.You can use a magical spell to erase exactly one day's rain, i.e., setting $$$p_i=0$$$. For each $$$i$$$ from $$$1$$$ to $$$n$$$, check whether in case of erasing the $$$i$$$-th day's rain there is no flood.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq m \leq 10^9$$$) — the number of rainy days and the maximal accumulated rainfall with no flood occurring. Then $$$n$$$ lines follow. The $$$i$$$-th of these lines contains two integers $$$x_i$$$ and $$$p_i$$$ ($$$1 \leq x_i,p_i \leq 10^9$$$) — the position and intensity of the $$$i$$$-th day's rain. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a binary string $$$s$$$ length of $$$n$$$. The $$$i$$$-th character of $$$s$$$ is 1 if after erasing the $$$i$$$-th day's rain there is no flood, while it is 0, if after erasing the $$$i$$$-th day's rain the flood still happens.

NoteIn the first test case, if we do not use the spell, the accumulated rainfall distribution will be like this:  If we erase the third day's rain, the flood is avoided and the accumulated rainfall distribution looks like this:  In the second test case, since initially the flood will not happen, we can erase any day's rain.In the third test case, there is no way to avoid the flood.

'use strict';

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(n, m, a) {
  a = a.map((arr, i) => [...arr, i]);
  a.sort((a, b) => a[0] - b[0]);
  const sum = [];
  {
    const bst = new BinarySearchTree((i, j) => a[i][1] - a[i][0] - (a[j][1] - a[j][0]));
    let pre = 0;
    for (let i = n - 1; i >= 0; i--) {
      if (i < n - 1) {
        let min = bst.getMin();
        while (bst.size() && a[min][1] <= a[min][0] - a[i][0]) {
          bst.delete(min);
          pre -= a[min][1] - (a[min][0] - a[i + 1][0]);
          min = bst.getMin();
        }
        pre -= bst.size() * (a[i + 1][0] - a[i][0]);
      }
      const [x, y] = a[i];
      sum[i] = pre;
      pre += y;
      bst.insert(i);
    }
    {
      pre = 0;
      const bst = new BinarySearchTree((i, j) => a[i][1] + a[i][0] - (a[j][1] + a[j][0]));
      for (let i = 0; i < n; i++) {
        if (i > 0) {
          let min = bst.getMin();
          while (bst.size() && a[min][1] <= a[i][0] - a[min][0]) {
            bst.delete(min);
            pre -= a[min][1] - (a[i - 1][0] - a[min][0]);
            min = bst.getMin();
          }
          pre -= bst.size() * (a[i][0] - a[i - 1][0]);
        }
        const [x, y] = a[i];
        pre += y;
        sum[i] += pre;
        bst.insert(i);
      }
    }
  }
  const cnt = new Array(n).fill(0);
  {
    const bst = new BinarySearchTree();
    for (let i = 0; i < n; i++) {
      if (sum[i] > m) bst.insert(sum[i] - a[i][0]);
      cnt[a[i][2]] = bst.size() - bst.countGreaterThanEq(m + a[i][1] - a[i][0] + 1);
    }
    {
      const bst = new BinarySearchTree();
      for (let i = n - 1; i >= 0; i--) {
        cnt[a[i][2]] += bst.size() - bst.countGreaterThanEq(m + a[i][0] + a[i][1] + 1);
        if (sum[i] > m) bst.insert(sum[i] + a[i][0]);
      }
    }
  }
  let ans = 0;
  for (let i = 0; i < n; i++) if (sum[i] <= m) ans++;
  const res = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    if (cnt[i] + ans >= n) res[i] = 1;
  }
  return res.join('');
}
class BinarySearchTree {
  constructor(_compare = (a, b) => a - b) {
    _defineProperty(this, "root", null);
    _defineProperty(this, "length", 0);
    _defineProperty(this, "min", null);
    _defineProperty(this, "max", null);
    _defineProperty(this, "minCache", true);
    _defineProperty(this, "maxCache", true);
    this._compare = _compare;
    this.compare = this.compare.bind(this);
  }
  isT(t) {
    return t !== undefined && t !== null;
  }
  compare(a, b) {
    const {
      isT
    } = this;
    if (isT(a) && isT(b)) return this._compare(a, b);
    if (isT(a)) return 1;
    if (isT(b)) return -1;
    return 0;
  }
  isEmpty() {
    return !this.root;
  }
  size() {
    return this.root ? this.root.size : 0;
  }
  getRoot() {
    return this.root;
  }
  getMin() {
    if (this.minCache) {
      return this.min;
    }
    const min = this.searchKth(this.size());
    this.min = min;
    this.minCache = true;
    return min;
  }
  getMax() {
    if (this.maxCache) {
      return this.max;
    }
    const max = this.searchKth(1);
    this.max = max;
    this.maxCache = true;
    return max;
  }
  balance(node) {
    node.height = this.getHeight(node);
    const blance = this.getBalance(node);
    let res;
    if (Math.abs(blance) === 2) {
      if (blance > 0) {
        var _node$left$left$heigh, _node$left, _node$left$left, _node$left$right$heig, _node$left2, _node$left2$right;
        const heightDif = ((_node$left$left$heigh = (_node$left = node.left) === null || _node$left === void 0 ? void 0 : (_node$left$left = _node$left.left) === null || _node$left$left === void 0 ? void 0 : _node$left$left.height) !== null && _node$left$left$heigh !== void 0 ? _node$left$left$heigh : 0) - ((_node$left$right$heig = (_node$left2 = node.left) === null || _node$left2 === void 0 ? void 0 : (_node$left2$right = _node$left2.right) === null || _node$left2$right === void 0 ? void 0 : _node$left2$right.height) !== null && _node$left$right$heig !== void 0 ? _node$left$right$heig : 0);
        if (heightDif > 0) {
          res = this.rotateRight(node);
        } else if (heightDif < 0) {
          res = this.rotateLeftRight(node);
        }
      } else {
        var _node$right$left$heig, _node$right, _node$right$left, _node$right$right$hei, _node$right2, _node$right2$right;
        const heightDif = ((_node$right$left$heig = (_node$right = node.right) === null || _node$right === void 0 ? void 0 : (_node$right$left = _node$right.left) === null || _node$right$left === void 0 ? void 0 : _node$right$left.height) !== null && _node$right$left$heig !== void 0 ? _node$right$left$heig : 0) - ((_node$right$right$hei = (_node$right2 = node.right) === null || _node$right2 === void 0 ? void 0 : (_node$right2$right = _node$right2.right) === null || _node$right2$right === void 0 ? void 0 : _node$right2$right.height) !== null && _node$right$right$hei !== void 0 ? _node$right$right$hei : 0);
        if (heightDif > 0) {
          res = this.rotateRightLeft(node);
        } else if (heightDif < 0) {
          res = this.rotateLeft(node);
        }
      }
    }
    return res ? res : node;
  }
  rotateRight(node) {
    const left = node.left;
    const leftRight = left.right;
    left.right = node;
    node.left = leftRight;
    node.height = this.getHeight(node);
    left.height = this.getHeight(left);
    node.size = this.getSize(node);
    left.size = this.getSize(left);
    return left;
  }
  rotateLeft(node) {
    const right = node.right;
    const rightLeft = right.left;
    right.left = node;
    node.right = rightLeft;
    node.height = this.getHeight(node);
    right.height = this.getHeight(right);
    node.size = this.getSize(node);
    right.size = this.getSize(right);
    return right;
  }
  rotateLeftRight(node) {
    node.left = this.rotateLeft(node.left);
    return this.rotateRight(node);
  }
  rotateRightLeft(node) {
    node.right = this.rotateRight(node.right);
    return this.rotateLeft(node);
  }
  getBalance(node) {
    return this.getHeight(node.left) - this.getHeight(node.right);
  }
  getHeight(node) {
    var _node$left$height, _node$left3, _node$right$height, _node$right3;
    if (!node) return 0;
    return Math.max((_node$left$height = (_node$left3 = node.left) === null || _node$left3 === void 0 ? void 0 : _node$left3.height) !== null && _node$left$height !== void 0 ? _node$left$height : 0, (_node$right$height = (_node$right3 = node.right) === null || _node$right3 === void 0 ? void 0 : _node$right3.height) !== null && _node$right$height !== void 0 ? _node$right$height : 0) + 1;
  }
  getSize(node) {
    var _node$left$size, _node$left4, _node$right$size, _node$right4;
    if (!node) return 0;
    return ((_node$left$size = (_node$left4 = node.left) === null || _node$left4 === void 0 ? void 0 : _node$left4.size) !== null && _node$left$size !== void 0 ? _node$left$size : 0) + ((_node$right$size = (_node$right4 = node.right) === null || _node$right4 === void 0 ? void 0 : _node$right4.size) !== null && _node$right$size !== void 0 ? _node$right$size : 0) + node.count;
  }
  createNode(val) {
    return {
      id: Math.random() * new Date().valueOf(),
      val,
      left: null,
      right: null,
      size: 1,
      height: 1,
      count: 1
    };
  }
  insert(val) {
    let cur = this.createNode(val);
    if (this.isEmpty()) {
      this.root = cur;
      this.length++;
    } else {
      [, cur] = this.insertNode(this.root, cur);
    }
    if (this.min === null || this.compare(this.min, val) > 0) {
      this.min = val;
    }
    if (this.max === null || this.compare(this.max, val) < 0) {
      this.max = val;
    }
  }
  insertNode(node, cur, parent = null) {
    node.size++;
    const compareResult = this.compare(cur.val, node.val);
    let res;
    if (compareResult === 0) {
      node.count++;
      return [false, node];
    } else if (compareResult > 0) {
      if (node.right) {
        res = this.insertNode(node.right, cur, node);
        if (!res[0]) return res;
      } else {
        node.right = cur;
        this.length++;
        res = [true, cur];
      }
    } else {
      if (node.left) {
        res = this.insertNode(node.left, cur, node);
        if (!res[0]) return res;
      } else {
        node.left = cur;
        this.length++;
        res = [true, cur];
      }
    }
    let preHeight = node.height;
    const newNode = this.balance(node);
    if (newNode === node && node.height === preHeight) {
      res = [false, res[1]];
    } else if (newNode !== node) {
      if (parent) {
        parent.left === node ? parent.left = newNode : parent.right = newNode;
      } else {
        this.root = newNode;
      }
      res = [false, res[1]];
    }
    return res;
  }
  delete(val) {
    if (!this.root) return;
    this.deleteNode(val, this.root, null);
  }
  deleteNode(val, node, parent) {
    if (!node) return null;
    let res = this.compare(val, node.val);
    if (res === 0) {
      node.count--;
      node.size--;
      if (node.count > 0) return node;
      if (!node.left || !node.right) {
        if (this.min === val) {
          this.minCache = false;
        }
        if (this.max === val) {
          this.maxCache = false;
        }
        this.length--;
        if (!parent) {
          var _node$left5;
          this.root = (_node$left5 = node.left) !== null && _node$left5 !== void 0 ? _node$left5 : node.right;
          return this.root;
        } else {
          var _node$left6;
          return (_node$left6 = node.left) !== null && _node$left6 !== void 0 ? _node$left6 : node.right;
        }
      } else {
        const selectLeft = node.left.height > node.right.height;
        let replaceNode = selectLeft ? this.pre(node) : this.next(node),
            name = selectLeft ? 'left' : 'right';
        node.val = replaceNode.val;
        node.count = replaceNode.count;
        replaceNode.count = 0;
        node[name] = this.deleteNode(replaceNode.val, node[name], node);
      }
    } else if (res > 0) {
      node.right = this.deleteNode(val, node.right, node);
    } else {
      node.left = this.deleteNode(val, node.left, node);
    }
    node.size = this.getSize(node);
    node.height;
    const newNode = this.balance(node);
    if (parent) {
      parent.left === node ? parent.left = newNode : parent.right = newNode;
    } else {
      this.root = newNode;
    }
    return newNode;
  }
  next(node) {
    let next = node.right;
    while ((_next = next) !== null && _next !== void 0 && _next.left) {
      var _next;
      next = next.left;
    }
    return next;
  }
  pre(node) {
    let pre = node.left;
    while ((_pre = pre) !== null && _pre !== void 0 && _pre.right) {
      var _pre;
      pre = pre.right;
    }
    return pre;
  }
  search(val, compare) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, compare !== null && compare !== void 0 ? compare : this.compare);
    return node.val;
  }
  searchCeilingNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        return this.searchCeilingNode(node.right, val, compare, node);
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        const [p, value] = this.searchCeilingNode(node.left, val, compare, node);
        if (compare(value.val, val) < 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    }
  }
  ceiling(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, this.compare);
    return this.compare(node.val, val) >= 0 ? node.val : null;
  }
  searchFloorNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        const [p, value] = this.searchFloorNode(node.right, val, compare, node);
        if (compare(value.val, val) > 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        return this.searchFloorNode(node.left, val, compare, node);
      } else {
        return [parent, node];
      }
    }
  }
  floor(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchFloorNode(this.root, val, this.compare);
    return this.compare(node.val, val) <= 0 ? node.val : null;
  }
  searchKth(k) {
    if (this.isEmpty()) {
      return null;
    }
    if (k <= 0 || k > this.size()) {
      return null;
    }
    const node = this.searchNodeKth(this.root, k);
    return node.val;
  }
  searchNodeKth(node, k) {
    var _node$right$size2, _node$right5, _node$right$size3, _node$right6;
    const rSize = (_node$right$size2 = (_node$right5 = node.right) === null || _node$right5 === void 0 ? void 0 : _node$right5.size) !== null && _node$right$size2 !== void 0 ? _node$right$size2 : 0;
    if (rSize === k - 1 || rSize < k && rSize + node.count >= k) return node;
    if (node.right && rSize > k - 1) return this.searchNodeKth(node.right, k);else return this.searchNodeKth(node.left, k - ((_node$right$size3 = (_node$right6 = node.right) === null || _node$right6 === void 0 ? void 0 : _node$right6.size) !== null && _node$right$size3 !== void 0 ? _node$right$size3 : 0) - node.count);
  }
  countGreaterThanEq(val) {
    if (!this.root) return 0;
    return this.countCompare(val, (a, b) => this._compare(a, b), this.root);
  }
  countCompare(val, compare, node, pre = 0) {
    const res = compare(val, node.val);
    if (res === 0) {
      var _node$right$size4, _node$right7;
      return pre + ((_node$right$size4 = (_node$right7 = node.right) === null || _node$right7 === void 0 ? void 0 : _node$right7.size) !== null && _node$right$size4 !== void 0 ? _node$right$size4 : 0) + node.count;
    } else if (res > 0) {
      if (node.right) {
        return this.countCompare(val, compare, node.right, pre);
      } else {
        return pre;
      }
    } else {
      var _node$right$size5, _node$right8;
      let count = pre + ((_node$right$size5 = (_node$right8 = node.right) === null || _node$right8 === void 0 ? void 0 : _node$right8.size) !== null && _node$right$size5 !== void 0 ? _node$right$size5 : 0) + node.count;
      if (node.left) {
        return this.countCompare(val, compare, node.left, count);
      } else {
        return count;
      }
    }
  }
  toArray() {
    if (!this.root) return [];
    const res = [];
    const dfs = node => {
      if (node.left) dfs(node.left);
      res.push(node.val);
      if (node.right) dfs(node.right);
    };
    dfs(this.root);
    return res;
  }
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = [];
      let tmp = n;
      while (tmp--) {
        a.push((await read()).split(' ').map(Number));
      }
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function solve(n, m, a) {
  a = a.map((arr, i) => [...arr, i]);
  a.sort((a, b) => a[0] - b[0]);
  const sum = [];
  const flag = new Array(n);
  const cnt = new Array(n).fill(0);
  {
    const bst = new BinarySearchTree((i, j) => a[i][1] - a[i][0] - (a[j][1] - a[j][0]));
    let pre = 0;
    for (let i = n - 1; i >= 0; i--) {
      if (i < n - 1) {
        let min = bst.getMin();
        while (bst.size() && a[min][1] <= a[min][0] - a[i][0]) {
          bst.delete(min);
          pre -= a[min][1] - (a[min][0] - a[i + 1][0]);
          min = bst.getMin();
        }
        pre -= bst.size() * (a[i + 1][0] - a[i][0]);
      }
      const [x, y] = a[i];
      sum[i] = pre;
      pre += y;
      bst.insert(i);
    }
    {
      pre = 0;
      const bst = new BinarySearchTree((i, j) => a[i][1] + a[i][0] - (a[j][1] + a[j][0]));
      for (let i = 0; i < n; i++) {
        if (i > 0) {
          let min = bst.getMin();
          while (bst.size() && a[min][1] <= a[i][0] - a[min][0]) {
            bst.delete(min);
            pre -= a[min][1] - (a[i - 1][0] - a[min][0]);
            min = bst.getMin();
          }
          pre -= bst.size() * (a[i][0] - a[i - 1][0]);
        }
        const [x, y] = a[i];
        pre += y;
        sum[i] += pre;
        bst.insert(i);
        const dif = sum[i] - m;
        if (dif > 0) {
          flag[i] = 1;
          const max = bst.getMax();
          if (bst.size() && a[max][1] - (a[i][0] - a[max][0]) >= dif) {
            const queue = [bst.getRoot()];
            for (let node of queue) {
              const j = node.val;
              if (a[j][1] - (a[i][0] - a[j][0]) >= dif) {
                cnt[a[j][2]]++;
                if (node.left) queue.push(node.left);
                if (node.right) queue.push(node.right);
              } else {
                if (node.right) queue.push(node.right);
              }
            }
          }
        }
      }
    }
  }
  {
    const bst = new BinarySearchTree((i, j) => a[i][1] - a[i][0] - (a[j][1] - a[j][0]));
    for (let i = n - 1; i >= 0; i--) {
      const dif = sum[i] - m;
      if (dif > 0) {
        flag[i] = 1;
        const max = bst.getMax();
        if (bst.size() && a[max][1] - (a[max][0] - a[i][0]) >= dif) {
          const queue = [bst.getRoot()];
          for (let node of queue) {
            const j = node.val;
            if (a[j][1] - (a[j][0] - a[i][0]) >= dif) {
              cnt[a[j][2]]++;
              if (node.left) queue.push(node.left);
              if (node.right) queue.push(node.right);
            } else {
              if (node.right) queue.push(node.right);
            }
          }
        }
      }
      bst.insert(i);
    }
  }
  let ans = 0;
  for (let i = 0; i < n; i++) if (!flag[i]) ans++;
  const res = new Array(n).fill(0);
  for (let i = 0; i < n; i++) {
    if (cnt[i] + ans === n) res[i] = 1;
  }
  return res.join('');
}
class BinarySearchTree {
  constructor(_compare = (a, b) => a - b) {
    _defineProperty(this, "root", null);
    _defineProperty(this, "length", 0);
    _defineProperty(this, "min", null);
    _defineProperty(this, "max", null);
    _defineProperty(this, "minCache", true);
    _defineProperty(this, "maxCache", true);
    this._compare = _compare;
    this.compare = this.compare.bind(this);
  }
  isT(t) {
    return t !== undefined && t !== null;
  }
  compare(a, b) {
    const {
      isT
    } = this;
    if (isT(a) && isT(b)) return this._compare(a, b);
    if (isT(a)) return 1;
    if (isT(b)) return -1;
    return 0;
  }
  isEmpty() {
    return !this.root;
  }
  size() {
    return this.root ? this.root.size : 0;
  }
  getRoot() {
    return this.root;
  }
  getMin() {
    if (this.minCache) {
      return this.min;
    }
    const min = this.searchKth(this.size());
    this.min = min;
    this.minCache = true;
    return min;
  }
  getMax() {
    if (this.maxCache) {
      return this.max;
    }
    const max = this.searchKth(1);
    this.max = max;
    this.maxCache = true;
    return max;
  }
  balance(node) {
    node.height = this.getHeight(node);
    const blance = this.getBalance(node);
    let res;
    if (Math.abs(blance) === 2) {
      if (blance > 0) {
        var _node$left$left$heigh, _node$left, _node$left$left, _node$left$right$heig, _node$left2, _node$left2$right;
        const heightDif = ((_node$left$left$heigh = (_node$left = node.left) === null || _node$left === void 0 ? void 0 : (_node$left$left = _node$left.left) === null || _node$left$left === void 0 ? void 0 : _node$left$left.height) !== null && _node$left$left$heigh !== void 0 ? _node$left$left$heigh : 0) - ((_node$left$right$heig = (_node$left2 = node.left) === null || _node$left2 === void 0 ? void 0 : (_node$left2$right = _node$left2.right) === null || _node$left2$right === void 0 ? void 0 : _node$left2$right.height) !== null && _node$left$right$heig !== void 0 ? _node$left$right$heig : 0);
        if (heightDif > 0) {
          res = this.rotateRight(node);
        } else if (heightDif < 0) {
          res = this.rotateLeftRight(node);
        }
      } else {
        var _node$right$left$heig, _node$right, _node$right$left, _node$right$right$hei, _node$right2, _node$right2$right;
        const heightDif = ((_node$right$left$heig = (_node$right = node.right) === null || _node$right === void 0 ? void 0 : (_node$right$left = _node$right.left) === null || _node$right$left === void 0 ? void 0 : _node$right$left.height) !== null && _node$right$left$heig !== void 0 ? _node$right$left$heig : 0) - ((_node$right$right$hei = (_node$right2 = node.right) === null || _node$right2 === void 0 ? void 0 : (_node$right2$right = _node$right2.right) === null || _node$right2$right === void 0 ? void 0 : _node$right2$right.height) !== null && _node$right$right$hei !== void 0 ? _node$right$right$hei : 0);
        if (heightDif > 0) {
          res = this.rotateRightLeft(node);
        } else if (heightDif < 0) {
          res = this.rotateLeft(node);
        }
      }
    }
    return res ? res : node;
  }
  rotateRight(node) {
    const left = node.left;
    const leftRight = left.right;
    left.right = node;
    node.left = leftRight;
    node.height = this.getHeight(node);
    left.height = this.getHeight(left);
    node.size = this.getSize(node);
    left.size = this.getSize(left);
    return left;
  }
  rotateLeft(node) {
    const right = node.right;
    const rightLeft = right.left;
    right.left = node;
    node.right = rightLeft;
    node.height = this.getHeight(node);
    right.height = this.getHeight(right);
    node.size = this.getSize(node);
    right.size = this.getSize(right);
    return right;
  }
  rotateLeftRight(node) {
    node.left = this.rotateLeft(node.left);
    return this.rotateRight(node);
  }
  rotateRightLeft(node) {
    node.right = this.rotateRight(node.right);
    return this.rotateLeft(node);
  }
  getBalance(node) {
    return this.getHeight(node.left) - this.getHeight(node.right);
  }
  getHeight(node) {
    var _node$left$height, _node$left3, _node$right$height, _node$right3;
    if (!node) return 0;
    return Math.max((_node$left$height = (_node$left3 = node.left) === null || _node$left3 === void 0 ? void 0 : _node$left3.height) !== null && _node$left$height !== void 0 ? _node$left$height : 0, (_node$right$height = (_node$right3 = node.right) === null || _node$right3 === void 0 ? void 0 : _node$right3.height) !== null && _node$right$height !== void 0 ? _node$right$height : 0) + 1;
  }
  getSize(node) {
    var _node$left$size, _node$left4, _node$right$size, _node$right4;
    if (!node) return 0;
    return ((_node$left$size = (_node$left4 = node.left) === null || _node$left4 === void 0 ? void 0 : _node$left4.size) !== null && _node$left$size !== void 0 ? _node$left$size : 0) + ((_node$right$size = (_node$right4 = node.right) === null || _node$right4 === void 0 ? void 0 : _node$right4.size) !== null && _node$right$size !== void 0 ? _node$right$size : 0) + node.count;
  }
  createNode(val) {
    return {
      id: Math.random() * new Date().valueOf(),
      val,
      left: null,
      right: null,
      size: 1,
      height: 1,
      count: 1
    };
  }
  insert(val) {
    let cur = this.createNode(val);
    if (this.isEmpty()) {
      this.root = cur;
      this.length++;
    } else {
      [, cur] = this.insertNode(this.root, cur);
    }
    if (this.min === null || this.compare(this.min, val) > 0) {
      this.min = val;
    }
    if (this.max === null || this.compare(this.max, val) < 0) {
      this.max = val;
    }
  }
  insertNode(node, cur, parent = null) {
    node.size++;
    const compareResult = this.compare(cur.val, node.val);
    let res;
    if (compareResult === 0) {
      node.count++;
      return [false, node];
    } else if (compareResult > 0) {
      if (node.right) {
        res = this.insertNode(node.right, cur, node);
        if (!res[0]) return res;
      } else {
        node.right = cur;
        this.length++;
        res = [true, cur];
      }
    } else {
      if (node.left) {
        res = this.insertNode(node.left, cur, node);
        if (!res[0]) return res;
      } else {
        node.left = cur;
        this.length++;
        res = [true, cur];
      }
    }
    let preHeight = node.height;
    const newNode = this.balance(node);
    if (newNode === node && node.height === preHeight) {
      res = [false, res[1]];
    } else if (newNode !== node) {
      if (parent) {
        parent.left === node ? parent.left = newNode : parent.right = newNode;
      } else {
        this.root = newNode;
      }
      res = [false, res[1]];
    }
    return res;
  }
  delete(val) {
    if (!this.root) return;
    this.deleteNode(val, this.root, null);
  }
  deleteNode(val, node, parent) {
    if (!node) return null;
    let res = this.compare(val, node.val);
    if (res === 0) {
      node.count--;
      node.size--;
      if (node.count > 0) return node;
      if (!node.left || !node.right) {
        if (this.min === val) {
          this.minCache = false;
        }
        if (this.max === val) {
          this.maxCache = false;
        }
        this.length--;
        if (!parent) {
          var _node$left5;
          this.root = (_node$left5 = node.left) !== null && _node$left5 !== void 0 ? _node$left5 : node.right;
          return this.root;
        } else {
          var _node$left6;
          return (_node$left6 = node.left) !== null && _node$left6 !== void 0 ? _node$left6 : node.right;
        }
      } else {
        const selectLeft = node.left.height > node.right.height;
        let replaceNode = selectLeft ? this.pre(node) : this.next(node),
            name = selectLeft ? 'left' : 'right';
        node.val = replaceNode.val;
        node.count = replaceNode.count;
        replaceNode.count = 0;
        node[name] = this.deleteNode(replaceNode.val, node[name], node);
      }
    } else if (res > 0) {
      node.right = this.deleteNode(val, node.right, node);
    } else {
      node.left = this.deleteNode(val, node.left, node);
    }
    node.size = this.getSize(node);
    node.height;
    const newNode = this.balance(node);
    if (parent) {
      parent.left === node ? parent.left = newNode : parent.right = newNode;
    } else {
      this.root = newNode;
    }
    return newNode;
  }
  next(node) {
    let next = node.right;
    while ((_next = next) !== null && _next !== void 0 && _next.left) {
      var _next;
      next = next.left;
    }
    return next;
  }
  pre(node) {
    let pre = node.left;
    while ((_pre = pre) !== null && _pre !== void 0 && _pre.right) {
      var _pre;
      pre = pre.right;
    }
    return pre;
  }
  search(val, compare) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, compare !== null && compare !== void 0 ? compare : this.compare);
    return node.val;
  }
  searchCeilingNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        return this.searchCeilingNode(node.right, val, compare, node);
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        const [p, value] = this.searchCeilingNode(node.left, val, compare, node);
        if (compare(value.val, val) < 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    }
  }
  ceiling(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchCeilingNode(this.root, val, this.compare);
    return this.compare(node.val, val) >= 0 ? node.val : null;
  }
  searchFloorNode(node, val, compare, parent = null) {
    const res = compare(val, node.val);
    if (res === 0) {
      return [parent, node];
    } else if (res > 0) {
      if (node.right) {
        const [p, value] = this.searchFloorNode(node.right, val, compare, node);
        if (compare(value.val, val) > 0) {
          return [parent, node];
        } else {
          return [p, value];
        }
      } else {
        return [parent, node];
      }
    } else {
      if (node.left) {
        return this.searchFloorNode(node.left, val, compare, node);
      } else {
        return [parent, node];
      }
    }
  }
  floor(val) {
    if (this.isEmpty()) {
      return null;
    }
    const [, node] = this.searchFloorNode(this.root, val, this.compare);
    return this.compare(node.val, val) <= 0 ? node.val : null;
  }
  searchKth(k) {
    if (this.isEmpty()) {
      return null;
    }
    if (k <= 0 || k > this.size()) {
      return null;
    }
    const node = this.searchNodeKth(this.root, k);
    return node.val;
  }
  searchNodeKth(node, k) {
    var _node$right$size2, _node$right5, _node$right$size3, _node$right6;
    const rSize = (_node$right$size2 = (_node$right5 = node.right) === null || _node$right5 === void 0 ? void 0 : _node$right5.size) !== null && _node$right$size2 !== void 0 ? _node$right$size2 : 0;
    if (rSize === k - 1 || rSize < k && rSize + node.count >= k) return node;
    if (node.right && rSize > k - 1) return this.searchNodeKth(node.right, k);else return this.searchNodeKth(node.left, k - ((_node$right$size3 = (_node$right6 = node.right) === null || _node$right6 === void 0 ? void 0 : _node$right6.size) !== null && _node$right$size3 !== void 0 ? _node$right$size3 : 0) - node.count);
  }
  countGreaterThanEq(val) {
    if (!this.root) return 0;
    return this.countCompare(val, (a, b) => this._compare(a, b), this.root);
  }
  countCompare(val, compare, node, pre = 0) {
    const res = compare(val, node.val);
    if (res === 0) {
      var _node$right$size4, _node$right7;
      return pre + ((_node$right$size4 = (_node$right7 = node.right) === null || _node$right7 === void 0 ? void 0 : _node$right7.size) !== null && _node$right$size4 !== void 0 ? _node$right$size4 : 0) + node.count;
    } else if (res > 0) {
      if (node.right) {
        return this.countCompare(val, compare, node.right, pre);
      } else {
        return pre;
      }
    } else {
      var _node$right$size5, _node$right8;
      let count = pre + ((_node$right$size5 = (_node$right8 = node.right) === null || _node$right8 === void 0 ? void 0 : _node$right8.size) !== null && _node$right$size5 !== void 0 ? _node$right$size5 : 0) + node.count;
      if (node.left) {
        return this.countCompare(val, compare, node.left, count);
      } else {
        return count;
      }
    }
  }
  toArray() {
    if (!this.root) return [];
    const res = [];
    const dfs = node => {
      if (node.left) dfs(node.left);
      res.push(node.val);
      if (node.right) dfs(node.right);
    };
    dfs(this.root);
    return res;
  }
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = [];
      let tmp = n;
      while (tmp--) {
        a.push((await read()).split(' ').map(Number));
      }
      res[i] = solve(n, m, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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


While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from $$$a_1, a_2, \ldots, a_n$$$ to $$$-a_1, -a_2, \ldots, -a_n$$$. For some unknown reason, the number of service variables is always an even number.William understands that with his every action he attracts more and more attention from the exchange's security team, so the number of his actions must not exceed $$$5\,000$$$ and after every operation no variable can have an absolute value greater than $$$10^{18}$$$. William can perform actions of two types for two chosen variables with indices $$$i$$$ and $$$j$$$, where $$$i < j$$$:  Perform assignment $$$a_i = a_i + a_j$$$  Perform assignment $$$a_j = a_j - a_i$$$  William wants you to develop a strategy that will get all the internal variables to the desired values.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 20$$$). Description of the test cases follows. The first line of each test case contains a single even integer $$$n$$$ ($$$2 \le n \le 10^3$$$), which is the number of internal variables. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, which are initial values of internal variables.

For each test case print the answer in the following format: The first line of output must contain the total number of actions $$$k$$$, which the strategy will perform. Note that you do not have to minimize $$$k$$$. The inequality $$$k \le 5\,000$$$ must be satisfied.  Each of the next $$$k$$$ lines must contain actions formatted as "type i j", where "type" is equal to "1" if the strategy needs to perform an assignment of the first type and "2" if the strategy needs to perform an assignment of the second type. Note that $$$i < j$$$ should hold. We can show that an answer always exists.

NoteFor the first sample test case one possible sequence of operations is as follows:  "2 1 2". Values of variables after performing the operation: [1, 0, 1, 1]  "2 1 2". Values of variables after performing the operation: [1, -1, 1, 1]  "2 1 3". Values of variables after performing the operation: [1, -1, 0, 1]  "2 1 3". Values of variables after performing the operation: [1, -1, -1, 1]  "2 1 4". Values of variables after performing the operation: [1, -1, -1, 0]  "2 1 4". Values of variables after performing the operation: [1, -1, -1, -1]  "1 1 2". Values of variables after performing the operation: [0, -1, -1, -1]  "1 1 2". Values of variables after performing the operation: [-1, -1, -1, -1] For the second sample test case one possible sequence of operations is as follows:  "2 1 4". Values of variables after performing the operation: [4, 3, 1, -2]  "1 2 4". Values of variables after performing the operation: [4, 1, 1, -2]  "1 2 4". Values of variables after performing the operation: [4, -1, 1, -2]  "1 2 4". Values of variables after performing the operation: [4, -3, 1, -2]  "1 3 4". Values of variables after performing the operation: [4, -3, -1, -2]  "1 1 2". Values of variables after performing the operation: [1, -3, -1, -2]  "1 1 2". Values of variables after performing the operation: [-2, -3, -1, -2]  "1 1 4". Values of variables after performing the operation: [-4, -3, -1, -2]

"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 = () => {
  const gcd = (a, b) => (a % b === 0 ? b : gcd(b, a % b));
  let t = parseInt(readline());
  while (t--) {
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       let res = [];
       for(let i=0;i<n;i+=2){
            let p1 = arr[i],p2 = arr[i+1];
            let k = [];
            while((p1!==(-1*arr[i]))||(p2!==(-1*arr[i+1]))){
                 p1 = p1+p2;
                 res.push(`1 ${i+1} ${i+1+1}`);
                 p2 = p2 - p1;
                 res.push(`2 ${i+1} ${i+1+1}`);
            }
       }
       console.log(res.length);
       for(let i=0;i<res.length;i++) console.log(res[i]);
  }
};
solve();

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function findAllStr(json, map, mapRev, index) {
   mapRev[index] = json;
   if (Array.isArray(json)) {
      for (var i = typeof json[0] === 'string' ? 1 : 0; i < json.length; i++) {
         findAllStr(json[i], map, mapRev, index + '_' + i);
      }
      return;
   }
   if (json && typeof json === 'string') {
      if (map[json]) {
         map[json].push(index);
      } else {
         map[json] = [index];
      }
   }
   return;
}

function solve() {
   var n2 = (Number(read()) >> 1);
   read();
   write(n2 * 6);
   for (var i = 0; i < n2; i++) {
      var a = i + 1;
      var b = n2 * 2 - i;
      var swapStr = a + ' ' + b;
      write('1 ' + swapStr);
      write('2 ' + swapStr);
      write('1 ' + swapStr);
      write('2 ' + swapStr);
      write('1 ' + swapStr);
      write('2 ' + swapStr);
   }
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}

"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 arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let dp = [];
    dp[0] = 0;
    let pm = 0;
    for (let i = 1; i < n; i++) {
      dp[i] = arr[pm] === Math.max(arr[i - 1], arr[pm]) ? pm : i - 1;
      pm = arr[pm] === Math.max(arr[i], arr[pm]) ? pm : i;
    }
    let res = [];
    for (let i = n - 1; i >= 1; i--) {
      while (arr[i] >= 0) {
        res.push(`2 ${dp[i] + 1} ${i + 1}`);
        arr[i] -= arr[dp[i]];
      }
    }
    let max = 1;
    for (let i = 1; i < n; i++) {
      if (Math.abs(arr[i]) >= Math.abs(arr[max])) max = i;
    }
    while (arr[0] >= 0) {
      res.push(`1 1 ${max + 1}`);
      arr[0] += arr[max];
    }
    console.log(res.length);
    for (let i = 0; i < res.length; i++) console.log(res[i]);
  }
};
solve();

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function findAllStr(json, map, mapRev, index) {
   mapRev[index] = json;
   if (Array.isArray(json)) {
      for (var i = typeof json[0] === 'string' ? 1 : 0; i < json.length; i++) {
         findAllStr(json[i], map, mapRev, index + '_' + i);
      }
      return;
   }
   if (json && typeof json === 'string') {
      if (map[json]) {
         map[json].push(index);
      } else {
         map[json] = [index];
      }
   }
   return;
}

function solve() {
   var n2 = (Number(read()) >> 1);
   read();
   write(n2 * 6);
   for (var i = 0; i < n2; i++) {
      var a = i + 1;
      var b = n2 * 2 - i;
      var swapStr = a + ' ' + b;
      write('1 ' + swapStr);
      write('2 ' + swapStr);
      write('2 ' + swapStr);
      write('1 ' + swapStr);
      write('1 ' + swapStr);
      write('2 ' + swapStr);
   }
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   return isNode && MEMORY;
}


Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it:Consider an $$$n$$$ by $$$n$$$ chessboard. Its rows are numbered from $$$1$$$ to $$$n$$$ from the top to the bottom. Its columns are numbered from $$$1$$$ to $$$n$$$ from the left to the right. A cell on an intersection of $$$x$$$-th row and $$$y$$$-th column is denoted $$$(x, y)$$$. The main diagonal of the chessboard is cells $$$(x, x)$$$ for all $$$1 \le x \le n$$$.A permutation of $$$\{1, 2, 3, \dots, n\}$$$ is written on the main diagonal of the chessboard. There is exactly one number written on each of the cells. The problem is to partition the cells under and on the main diagonal (there are exactly $$$1+2+ \ldots +n$$$ such cells) into $$$n$$$ connected regions satisfying the following constraints:  Every region should be connected. That means that we can move from any cell of a region to any other cell of the same region visiting only cells of the same region and moving from a cell to an adjacent cell.  The $$$x$$$-th region should contain cell on the main diagonal with number $$$x$$$ for all $$$1\le x\le n$$$.  The number of cells that belong to the $$$x$$$-th region should be equal to $$$x$$$ for all $$$1\le x\le n$$$.  Each cell under and on the main diagonal should belong to exactly one region.

The first line contains a single integer $$$n$$$ ($$$1\le n \le 500$$$) denoting the size of the chessboard. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$. $$$p_i$$$ is the number written on cell $$$(i, i)$$$. It is guaranteed that each integer from $$$\{1, \ldots, n\}$$$ appears exactly once in $$$p_1$$$, ..., $$$p_n$$$.

If no solution exists, output $$$-1$$$. Otherwise, output $$$n$$$ lines. The $$$i$$$-th line should contain $$$i$$$ numbers. The $$$j$$$-th number on the $$$i$$$-th line should be $$$x$$$ if cell $$$(i, j)$$$ belongs to the the region with $$$x$$$ cells.

NoteThe solutions to the examples are illustrated in the following pictures:

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
//////////// LIBS
const io = new IO();
function solve(n, arr) {
    let tab = Array.from({ length: n }).map(() => []);
    arr.forEach((a, i) => {
        tab[i][i] = a;
    });
    let left = Array.from({ length: n + 1 }).map((_, i) => i - 1);
    let visit = (i, j, a, initial = false) => {
        // console.log({ i, j, a, left });
        if (i < 0 || j < 0 || left[a] < 1 || i >= n || j >= n || j > i) {
            return;
        }
        if (!initial) {
            if (tab[i][j]) {
                return;
            }
            tab[i][j] = a;
            left[a]--;
        }
        [
            // [-1, 0],
            // [0, -1],
            // [0, 1],
            // [1, 0],
            [0, -1],
            [1, 0],
        ].forEach(([di, dj]) => {
            visit(i + di, j + dj, a);
        });
    };
    arr.forEach((a, i) => {
        visit(i, i, a, true);
    });
    // console.log({ left });
    for (let i = 0; i < n; i++) {
        for (let j = 0; j <= i; j++) {
            io.write(tab[i][j] || 0);
        }
        io.writeLine('');
    }
}
function main() {
    try {
        let n = io.nextNum();
        let arr = io.nextNumArray(n);
        solve(n, arr);
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

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 () {
	const n = rn();
	const p = rna();

	let ans = Array.from(Array(n), x => Array(n));

	for (let i = 0; ans && i < n; i++) {
		ans[i][i] = p[i];

		let r = i, c = i;
		for (let j = 1; j < p[i]; j++) {
			if (c-1>=0 && !ans[r][c-1])
				ans[r][--c] = p[i];
			else if (r+1<n & !ans[r+1][c])
				ans[++r][c] = p[i];
			else
				ans = false;
		}
	}

	if (!ans)
		console.log(-1);
	else
		for (let i = 0; i < n; i++)
			console.log(ans[i].slice(0, i+1).join(' '));
}

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 t = Number(input[0]);
    var arr = input[1].split(" ").map((i) => {
        return Number(i);
    });
    var grid = [];
    for (var i = 0; i < arr.length; i++) {
        grid[i] = new Array(i + 1).fill(0);
        grid[i][i] = arr[i];
    }
    var dirs = [[0, -1],[1, 0]];
    function helper(grid, i, j, num, count, dirs) {
        grid[i][j] = num;
        count--;
        for (var k = 0; k < dirs.length; k++) {
            var x = i + dirs[k][0];
            var y = j + dirs[k][1];
            if (x < grid.length && y >= 0 && grid[x][y] === 0 && count > 0) {
                helper(grid, x, y, num, count, dirs);
                break;
            }
        }
    }
    for (var i = 0; i < grid.length; i++) {
        helper(grid, i, i, arr[i], arr[i], dirs);
    }
    for (var i = 0; i < grid.length; i++) {
        console.log(grid[i].join(" "));
    }
});

process.stdin.setEncoding('utf-8')
const readline = require('readline')

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

let count = 2
let inputArr = []

rl.on('line', data => {
    if (count === -1) {
        count = +data
    } else if (count !== 0) {
        inputArr.push(data.trim())
        count--
    }
    // max number 2^(53) - 1 ~~ 10^(15)
    if (count === 0) {
        inputArr = inputArr.map(i => i.split(' ').map(j => +j))
        main()
        process.exit(0)
    }
})

function calcRecursive(arr, a, b, c, d, e) {
    if (e === 0) return 1
    if (c - 1 >= 0) {
        if (arr[b][c - 1] === 0) {
            arr[b][c - 1] = a
            return calcRecursive(arr, a, b, c - 1, d, e - 1)
        } else {
            if (b + 1 < d) {
                if (arr[b + 1][c] == 0) {
                    arr[b + 1][c] = a
                    return calcRecursive(arr, a, b + 1, c, d, e - 1)
                } else return 0
            }
        }
    } else {
        if (b + 1 < d) {
            if (arr[b + 1][c] == 0) {
                arr[b + 1][c] = a
                return calcRecursive(arr, a, b + 1, c, d, e - 1)
            } else return 0
        }
    }
}

function solve(n, arr) {
    let arr2 = []
    for (let i = 0; i < n; ++i) {
        arr2.push(new Array(n).fill(0))
        arr2[i][i] = arr[i]
    }
    for (let i = 0; i < n; i++) {
        if (calcRecursive(arr2, arr2[i][i], i, i, n, arr2[i][i] - 1) === 0) {
            console.log(-1)
            return
        }
    }

    for (let i = 0; i < n; ++i) {
        let temp = []
        for (let j = 0; j <= i; ++j) {
            temp.push(arr2[i][j])
        }
        console.log(temp.join(' '))
    }
}

function main() {
    solve(inputArr[0][0], inputArr[1])
}

//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 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 N = nextInt();
	var list = nextIntArray(N);
	var output = new Array(N);
	for(var j = 0; j < N; j++){
		output[j] = new Array(j + 1);
	}
	for(var j = N - 1; j >= 0; j--){
		var y = j;
		var x = j;
		var count = list[j];
		while(count > 0){
			output[y][x] = list[j];
			count--;
			if(count == 0){
				break;
			}
			if(y + 1 < N && output[y + 1][x] == null){
				y++;
				continue;
			}else if(x - 1 >= 0 && output[y][x - 1] == null){
				x--;
				continue;
			}else{
				break;
			}
		}
	}
	for(var j = 0; j < N; j++){
		myout(myconv(output[j], 8));
	}
}

const n = parseInt(readline());
const a = readline().split(' ').map((item, i) => {
  b = new Array(n).fill(0);
  b[i] = parseInt(item);
  return b;
});

for (var i = 0; i < n; i++) {
  var x = a[i][i];
  var x_ = x - 1;
  var posX = i;
  var posY = i;
  while (x_) {
    if (posX > 0 && !a[posY][posX - 1]) {
      posX--;
      a[posY][posX] = x;
    } else {
      posY++;
      a[posY][posX] = x;
    }
    x_--;
  }
}

for (var i = 0; i < n; i++) {
  for (var j = 0; j <= i; j++)
    write(`${a[i][j]} `);
  write('\n');
}

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
//////////// LIBS
const io = new IO();
function solve(n, arr) {
    let tab = Array.from({ length: n }).map(() => []);
    arr.forEach((a, i) => {
        tab[i][i] = a;
    });
    let left = Array.from({ length: n }).map((_, i) => i - 1);
    let visit = (i, j, a) => {
        // console.log({ i, j, a, left });
        if (i < 0 || j < 0 || left[a] < 1 || i >= n || j >= n || j > i) {
            return;
        }
        if (i !== j) {
            if (tab[i][j]) {
                return;
            }
            tab[i][j] = a;
            left[a]--;
        }
        [
            [-1, 0],
            [0, -1],
            [0, 1],
            [1, 0],
        ].forEach(([di, dj]) => {
            visit(i + di, j + dj, a);
        });
    };
    arr.forEach((a, i) => {
        visit(i, i, a);
    });
    for (let i = 0; i < n; i++) {
        for (let j = 0; j <= i; j++) {
            io.write(tab[i][j]);
        }
        io.writeLine('');
    }
}
function main() {
    try {
        let n = io.nextNum();
        let arr = io.nextNumArray(n);
        solve(n, arr);
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
//////////// LIBS
const io = new IO();
function solve(n, arr) {
    let tab = Array.from({ length: n }).map(() => []);
    arr.forEach((a, i) => {
        tab[i][i] = a;
    });
    let left = Array.from({ length: n }).map((_, i) => i - 1);
    let visit = (i, j, a) => {
        // console.log({ i, j, a, left });
        if (i < 0 || j < 0 || left[a] < 1 || i >= n || j >= n) {
            return;
        }
        if (i !== j) {
            if (tab[i][j]) {
                return;
            }
            tab[i][j] = a;
            left[a]--;
        }
        [
            [-1, 0],
            [0, -1],
            [0, 1],
            [1, 0],
        ].forEach(([di, dj]) => {
            visit(i + di, j + dj, a);
        });
    };
    arr.forEach((a, i) => {
        visit(i, i, a);
    });
    for (let i = 0; i < n; i++) {
        for (let j = 0; j <= i; j++) {
            io.write(tab[i][j]);
        }
        io.writeLine('');
    }
}
function main() {
    try {
        let n = io.nextNum();
        let arr = io.nextNumArray(n);
        solve(n, arr);
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
//////////// LIBS
class IO {
    constructor() {
        this.i = 0;
        this.out = '';
        this.text = require('fs').readFileSync(0, 'utf8');
    }
    nextToken() {
        let ret = '';
        while (this.text[this.i].charCodeAt(0) <= 32) {
            this.i++;
        }
        while (this.i < this.text.length && this.text[this.i].charCodeAt(0) > 32) {
            ret += this.text[this.i];
            this.i++;
        }
        return ret;
    }
    nextNum() {
        return Number(this.nextToken());
    }
    nextNumArray(n) {
        let ret = [];
        while (n--) {
            ret.push(this.nextNum());
        }
        return ret;
    }
    _write(x) {
        this.out += x;
    }
    write(x) {
        this._write(x + ' ');
    }
    writeLine(x) {
        this._write(x + '\n');
    }
    flush() {
        fs_1.default.writeFileSync(1, this.out);
        this.out = '';
    }
}
function binarySearch(array, pred) {
    let lo = -1, hi = array.length;
    while (1 + lo < hi) {
        const mi = lo + ((hi - lo) >> 1);
        if (pred(array[mi])) {
            hi = mi;
        }
        else {
            lo = mi;
        }
    }
    return hi;
}
function lowerBound(array, item) {
    return binarySearch(array, (j) => item <= j);
}
function upperBound(array, item) {
    return binarySearch(array, (j) => item < j);
}
//////////// LIBS
const io = new IO();
function solve(n, arr) {
    let tab = Array.from({ length: n }).map(() => []);
    arr.forEach((a, i) => {
        tab[i][i] = a;
    });
    let left = Array.from({ length: n }).map((_, i) => i - 1);
    let visit = (i, j, a) => {
        // console.log({ i, j, a, left });
        if (i < 0 || j < 0 || left[a] < 1 || i >= n) {
            return;
        }
        if (i !== j) {
            if (tab[i][j]) {
                return;
            }
            tab[i][j] = a;
            left[a]--;
        }
        [
            [0, -1],
            [1, 0],
        ].forEach(([di, dj]) => {
            visit(i + di, j + dj, a);
        });
    };
    arr.forEach((a, i) => {
        visit(i, i, a);
    });
    for (let i = 0; i < n; i++) {
        for (let j = 0; j <= i; j++) {
            io.write(tab[i][j]);
        }
        io.writeLine('');
    }
}
function main() {
    try {
        let n = io.nextNum();
        let arr = io.nextNumArray(n);
        solve(n, arr);
        io.flush();
    }
    catch (e) {
        console.log(e.stack);
    }
}
main();

const n = parseInt(readline());
const a = readline().split(' ').map((item, i) => {
  b = new Array(n).fill(0);
  b[i] = parseInt(item);
  return b;
});

for (var i = 0; i < n; i++) {
  var x = a[i][i];
  var x_ = x - 1;
  var posX = i;
  var posY = i;
  while (x_) {
    if (posX > 0 && !a[posY][posX - 1]) {
      posX--;
      a[posY][posX] = x;
    } else {
      posY++;
      a[posY][posX] = x;
    }
    x_--;
  }
}

for (var i = 0; i < n; i++) {
  for (var j = 0; j < n; j++)
    write(`${a[i][j]} `);
  write('\n');
}


Recently, Norge found a string $$$s = s_1 s_2 \ldots s_n$$$ consisting of $$$n$$$ lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string $$$s$$$. Yes, all $$$\frac{n (n + 1)}{2}$$$ of them!A substring of $$$s$$$ is a non-empty string $$$x = s[a \ldots b] = s_{a} s_{a + 1} \ldots s_{b}$$$ ($$$1 \leq a \leq b \leq n$$$). For example, "auto" and "ton" are substrings of "automaton".Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only $$$k$$$ Latin letters $$$c_1, c_2, \ldots, c_k$$$ out of $$$26$$$.After that, Norge became interested in how many substrings of the string $$$s$$$ he could still type using his broken keyboard. Help him to find this number.

The first line contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq k \leq 26$$$) — the length of the string $$$s$$$ and the number of Latin letters still available on the keyboard. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains $$$k$$$ space-separated distinct lowercase Latin letters $$$c_1, c_2, \ldots, c_k$$$ — the letters still available on the keyboard.

Print a single number — the number of substrings of $$$s$$$ that can be typed using only available letters $$$c_1, c_2, \ldots, c_k$$$.

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

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

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

  const [n, k] = arr.shift().split(' ').map(a => parseInt(a))

  const str = arr[0]
  const available = arr[1]
  let sum = 0, last = -1

  for(let i = 0; i < n; i++) {
    if(!available.includes(str[i])) {
      let x = i - last - 1
      // console.log('x:', x, sum, last, i)
      sum += (x + 1) * x / 2
      last = i
    }
  }
  if(last != n - 1) {
    let x = n - 1 - last
    // console.log('x:', x, sum, last)
    sum += (x + 1) * x / 2
  }

  console.log(sum)
})

'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 getArray(str) {
    return str.split(' ').map(x => Number(x));
}

function getInt(str) {
    return Number(str);
}

function getStrArray(str) {
    return str.split(' ').map(x => x);
}

function create2DArray(rows) {
    var arr = [];

    for (var i = 0; i < rows; i++) {
        arr[i] = [];
    }

    return arr;
}
// ---------------------------------------

function main() {
    let [strLen, charOptions] = getArray(readline());
    let str = readline();
    let charArr = getStrArray(readline());
    let x = [];
    for (let i = 0; i < strLen; i++) {
        if (charArr.indexOf(str[i]) > -1) {
            x[i] = 1;
        } else {
            x[i] = 0;
        }
    }

    let count = 0;
    let ans = 0;
    for(let i= 0; i< strLen; i++) {
        if (x[i] === 0) {
            ans += count*(count+1)/2;
            count = 0
        } else if (x[i] === 1) {
            count++;
        }
    }
    if(count !== 0) {
        ans += count*(count+1)/2;
    }
    console.log(ans);
}

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

    function foo (data, letters) {
        const subAr = data.split(new RegExp(`[^${letters}]`))
        return subAr.reduce((acc, value) => {
            const n = value.length;
            return acc + ((n * (n + 1)) / 2);
        }, 0)
    }

    let result = foo(lines[1], lines[2].replace(/\s/g, ''));
    console.log(result);
})

let finalInput = '';

process.stdin.setEncoding('utf-8').on('data', input => {
    finalInput += input;
});

process.stdin.setEncoding('utf-8').on('end', () => {
    let [str, letters] = finalInput.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0);
    letters = letters.split(' ');
    let result = 0;
    let list = [];
    str.split('').forEach((c, index) => {
        if (letters.indexOf(c) < 0) {
            list.push(index);
        }
    });
    list.push(str.length);

    let lastIndex = 0;
    list.forEach((v) => {
        if (v > 0 && v > lastIndex) {
            let len = v - lastIndex;
            result += len * (len + 1) / 2;
        }
        // console.log(lastIndex, v, result);
        lastIndex = v + 1;
    });

    // console.log(list);
    console.log(result);
});

let fs = require("fs");

let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0;
});
for (let i = 0; i < txt.length; i += 3) {
    doit(txt[i + 1], txt[i + 2].split(" ").filter(data => {
        return data.length > 0
    }))
}

function doit(tab, keys) {
    let arr = []
    let seg=""
    for (let i = 0; i < tab.length; i++) {
        if(keys.includes(tab[i])){
            seg+=tab[i]
        }else if(seg.length>0){
            arr.push(seg.length);
            seg=""
        }

    }
    if(seg.length>0){
        arr.push(seg.length)
    }
    seg=0;
    arr.forEach(data=>{
        seg+=data*(data+1)/2
    })
    console.log(seg);
}

'use strict'

const problem = (n, k, s, t) => {
    let j = 0, r = 0, len = s.length;
    for (let i = 0; i < len; i++) {
        if (t.indexOf(s[i]) === -1) {
            if (j === -1) continue;
            r += (i-j)*(i-j+1) / 2;
            j = -1;
        } else {
            if (j === -1) j = i;
        }
    }
    if (j === -1) return r;
    r += (len-j)*(len-j+1) / 2;
    return r;
}

const nk = readline().split(' ').map(i => +i);
print(problem(nk[0], nk[1], readline(), readline()));

function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim();}
function myout(t){print(t);}//standard output
//function myout(t){console.log(t);}//standard output
function myerr(t){console.err(t);}//standard error
//[no]param
//0:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
function myconv(i,no){switch(no){case 0:return i;case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));}}

function Main() {
  //input = myconv(input,3);
  var first = readline();
  var N = myconv(first,4)[0];
  var k = myconv(first,4)[1];
  var list = myconv(readline(),6);
  var keys = myconv(readline(),2);
  var numlist = new Array(N).fill(0);
  for(var i = 0; i < N; i++){
    var tmps = list[i];
    if(keys.indexOf(list[i]) != -1){
       if(i == 0){
          numlist[i] = 1;
       }else{
          numlist[i] = numlist[i-1]+1;
       }
    }
  }
  var output = 0;
  for(var i = 0; i < N; i++){
    output += numlist[i];
  }
  myout(output);
}

Main();

let finalInput = '';

process.stdin.setEncoding('utf-8').on('data', input => {
    finalInput += input;
});

process.stdin.setEncoding('utf-8').on('end', () => {
    let [str, letters] = finalInput.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0);
    letters = letters.split(' ');
    let result = 0;
    let list = [];
    str.split('').forEach((c, index) => {
        if (letters.indexOf(c) < 0) {
            list.push(index);
        }
    });
    list.push(str.length);

    let lastIndex = 0;
    list.forEach((v) => {
        if (v > 0 && v > lastIndex) {
            console.log(lastIndex, v);
            let len = v - lastIndex;
            result += len * (len + 1) / 2;
        }
        // console.log(lastIndex, v, result);
        lastIndex = v + 1;
    });

    // console.log(list);
    console.log(result);
});

let finalInput = '';

process.stdin.setEncoding('utf-8').on('data', input => {
    finalInput += input;
});

process.stdin.setEncoding('utf-8').on('end', () => {
    let [str, letters] = finalInput.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0);
    letters = letters.split(' ');
    let lastIndex = 0;
    let result = 0;
    str.split('').forEach((c, index, array) => {
        // console.log(index, c, lastIndex, result);
        if ((letters.indexOf(c) < 0) && index > lastIndex) {
            // console.log('adding', lastIndex, index, index - lastIndex);
            let len = index + 1 - lastIndex;
            result += len * (len + 1) / 2;
        } else if ((letters.indexOf(c) < 0 || index === array.length - 1) && index > lastIndex) {

        }
        if (letters.indexOf(c) < 0) {
            lastIndex = index + 1;
        }
    });
    console.log(result);
});

let finalInput = '';

process.stdin.setEncoding('utf-8').on('data', input => {
    finalInput += input;
});

process.stdin.setEncoding('utf-8').on('end', () => {
    let [str, letters] = finalInput.split('\r\n').filter((_, i) => i >= 1).filter(l => l && l.length > 0);
    letters = letters.split(' ');
    let lastIndex = 0;
    let result = 0;
    str.split('').forEach((c, index, array) => {
        // console.log(index, c, lastIndex, result);
        if (letters.indexOf(c) < 0 && index > lastIndex) {
            // console.log('adding', lastIndex, index, index - lastIndex);
            let len = index - lastIndex;
            result += len * (len + 1) / 2;
        } else if (index === array.length - 1 && index > lastIndex) {
            // console.log('adding', lastIndex, index, index + 1 - lastIndex);
            let len = index + 1 - lastIndex;
            result += len * (len + 1) / 2;
        }
        if (letters.indexOf(c) < 0) {
            lastIndex = index + 1;
        }
    });
    console.log(result);
});

'use strict'

const problem = (n, k, s, t) => {
    let j = 0, r = 0, len = s.length;
    for (let i = 0; i < len; i++) {
        if (t.indexOf(s[i]) === -1) {
            if (j === -1) continue;
            r += (i-j)*(i-j+1) / 2;
            j = -1;
        } else {
            if (j === -1) j = i;
        }
    }
    if (j === -1) return 0;
    r += (len-j)*(len-j+1) / 2;
    return r;
}

const nk = readline().split(' ').map(i => +i);
print(problem(nk[0], nk[1], readline(), readline()));

'use strict'

const problem = (n, k, s, t) => {
    let j = 0, r = 0, len = s.length;
    for (let i = 0; i < len; i++) {
        if (t.indexOf(s[i]) === -1) {
            if (j === -1) continue;
            r += (i-j)*(i-j+1) / 2;
            j = -1;
        } else {
            if (j === -1) j = i;
        }
    }
    r += (len-j)*(len-j+1) / 2;
    return r;
}

const nk = readline().split(' ').map(i => +i);
print(problem(nk[0], nk[1], readline(), readline()));


Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya.

The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct. Next follows number n (1 ≤ n ≤ 90) — the number of fouls.  Each of the following n lines contains information about a foul in the following form:    first goes number t (1 ≤ t ≤ 90) — the minute when the foul occurs;  then goes letter "h" or letter "a" — if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player;  then goes the player's number m (1 ≤ m ≤ 99);  then goes letter "y" or letter "r" — if the letter is "y", that means that the yellow card was given, otherwise the red card was given.  The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute.

For each event when a player received his first red card in a chronological order print a string containing the following information:   The name of the team to which the player belongs;  the player's number in his team;  the minute when he received the card.  If no player received a card, then you do not need to print anything. It is possible case that the program will not print anything to the output (if there were no red cards).

function main() {
    var homeTeam = next();
    var guestTeam = next();

    var n = nextInt();
    var status = {};
    var res = [];

    for (var i = 0; i < n; i++) {
        var time = nextInt();
        var team = next().charAt(0) === 'h' ? 0 : 1;
        var m = nextInt();
        var cardType = next().charAt(0);
        var name = team + '_' + m;
        var found = false;
        if (status[name] === 1) {
            status[name] = 2;
            found = true;
        } else if (status[name] === 2) {
        } else {
            status[name] = cardType === 'y' ? 1 : 2;
            found = status[name] === 2;
        }
        if (found)
          res.push([(team === 0 ? homeTeam : guestTeam), m, time]);
    }

    for (var j = 0; j < res.length; j++) {
        print(res[j][0] + ' ' + res[j][1] + ' ' + res[j][2]);
    }
}

// auxiliary code
var curTokens = [], curToken = 0;

function next() {
    while (curToken >= curTokens.length) {
        curTokens = readline().split(/[\s]+/);
        curToken = 0;
    }
    return curTokens[curToken++];
}

function nextInt() {
    return parseInt(next());
}

main();

function main(){
    var h = [];
    h.push(next());
    h.push(next());
    var E = [];
    E.push({});
    E.push({});
    var t = nextInt();
    var time,team,number,type;
    while(t-->0){
        time = nextInt();
        team = next().charAt(0)!="h" ? 1:0 ;
        number = nextInt();
        type = next();
        if(type == "r"){
            if(!E[team][number])
                E[team][number]=0;
            if(E[team][number]<=1){
                print(h[team]+" "+number+" "+time);
                }
            E[team][number]+=2;
            }
        else {
            if(!E[team][number])
               E[team][number]=0;
            if(E[team][number]==1){
                print(h[team]+" "+number+" "+time);
                }
            E[team][number]++;
            }
        }
    }
var curTokens = [], curToken = 0;

function next() {
    while (curToken >= curTokens.length) {
        curTokens = readline().split(/[\s]+/);
        curToken = 0;
    }
    return curTokens[curToken++];
}

function nextInt() {
    return parseInt(next());
}

main();

var home = readline(),
			away = readline(),
			n = parseInt(readline()),
			homeCheck = {}, awayCheck = {};

		for(var i = 0; i < n; i++)	{
			var inputs = readline().split(/\s/gi),
				time = inputs[0],
				team = inputs[1],
				player = inputs[2],
				card = inputs[3];

			if(team == 'a')	{
				if(!awayCheck[player])	awayCheck[player] = { 'y' : 0, 'r' : 0, 'hasRed' : false };

				awayCheck[player][card] += 1;

				if((awayCheck[player].y >= 2 || awayCheck[player].r >= 1) && !awayCheck[player].hasRed)	{
					print(away + ' ' + player + ' ' + time);
					awayCheck[player].hasRed = true;
				}
			} else	{
				if(!homeCheck[player])	homeCheck[player] = { 'y' : 0, 'r' : 0, 'hasRed' : false };

				homeCheck[player][card] += 1;

				if((homeCheck[player].y >= 2 || homeCheck[player].r >= 1) && !homeCheck[player].hasRed)	{
					print(home + ' ' + player + ' ' + time);
					homeCheck[player].hasRed = true;
				}
			}
		}

function main(){
    var h = [];
    h.push(next());
    h.push(next());
    var E = [];
    E.push({});
    E.push({});
    var t = nextInt();
    var time,team,number,type;

    while(t-->0){
        time = nextInt();
        team = next().charAt(0)!="h";
        number = nextInt();
        type = next();
        if(type == "r"){
            if(!E[team][number])
                E[team][number]=0;
            if(E[team][number]<=1){
                print([team]+" "+number+" "+time);
                }
            E[team][number]+=2;
            }
        else {
            if(!E[team][number])
               E[team][number]=0;
            if(E[team][number]==1){
                print([team]+" "+number+" "+time);
                }
            E[team][number]++;
            }
        }
    }

var home = readline(),
			away = readline(),
			n = parseInt(readline()),
			homeCheck = {}, awayCheck = {};

		for(var i = 0; i < n; i++)	{
			var inputs = readline().split(/\s/gi),
				time = inputs[0],
				team = inputs[1],
				player = inputs[2],
				card = inputs[3];

			if(team == 'a')	{
				if(!awayCheck[player])	awayCheck[player] = { 'y' : 0, 'r' : 0 };

				awayCheck[player][card] += 1;

				if(awayCheck[player].y >= 2 || awayCheck[player].r >= 1)	{
					print(away + ' ' + player + ' ' + time);
				}
			}
			if(team == 'h')	{
				if(!homeCheck[player])	homeCheck[player] = { 'y' : 0, 'r' : 0 };

				homeCheck[player][card] += 1;

				if(homeCheck[player].y >= 2 || homeCheck[player].r >= 1)	{
					print(home + ' ' + player + ' ' + time);
				}
			}
		}

var home = readline(),
			away = readline(),
			n = parseInt(readline()),
			homeCheck = {}, awayCheck = {};

		for(var i = 0; i < n; i++)	{
			var inputs = readline().split(/\s/gi),
				time = inputs[0],
				team = inputs[1],
				player = inputs[2],
				card = inputs[3];

			if(team == 'a')	{
				if(!awayCheck[player])	{
					awayCheck[player] = {
						'y' : 0,
						'r' : 0
					};
				}

				awayCheck[player][card] += 1;

				if(awayCheck[player].y >= 2 || awayCheck[player].r >= 1)	{
					print(away + ' ' + player + ' ' + time);
				}
			} else	{
				if(!homeCheck[player])	{
					homeCheck[player] = {
						'y' : 0,
						'r' : 0
					};
				}

				homeCheck[player][card] += 1;

				if(homeCheck[player].y >= 2 || homeCheck[player].r >= 1)	{
					print(home + ' ' + player + ' ' + time);
				}
			}
		}