You are given a special jigsaw puzzle consisting of $$$n\cdot m$$$ identical pieces. Every piece has three tabs and one blank, as pictured below.  The jigsaw puzzle is considered solved if the following conditions hold:  The pieces are arranged into a grid with $$$n$$$ rows and $$$m$$$ columns.  For any two pieces that share an edge in the grid, a tab of one piece fits perfectly into a blank of the other piece. Through rotation and translation of the pieces, determine if it is possible to solve the jigsaw puzzle.

The test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. Each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 10^5$$$).

For each test case output a single line containing "YES" if it is possible to solve the jigsaw puzzle, or "NO" otherwise. You can print each letter in any case (upper or lower).

NoteFor the first test case, this is an example solution:   For the second test case, we can show that no solution exists.For the third test case, this is an example solution:

n = +readline();
while (n-->0){
    num = readline().split(' ').map(Number);
    if (num[0] == 1 || num[1] == 1 || (num[0] == 2 && num[1] == 2)){
        print('YES\n');
    } else {
        print('NO\n');
    }
}

var t = parseInt(readline());
for (var tc = 0; tc < t; tc++) {
  var nm = readline()
    .split(" ")
    .map((val) => parseInt(val));
  var n = nm[0],
    m = nm[1];
  if (n < 2 || m < 2 || (n == 2 && m == 2)) print("Yes");
  else print("No");
}

var inputLength = readline();

for (var i =0; i<inputLength; i++) {
    var input = readline().split(" ");
    var r = input[0], c = input[1];
    if( r * c >= (2*r*c - r - c)) {
        print ("YES");
    } else {
        print ("NO");
    }
}

var inputLength = readline();

for (var i =0; i<inputLength; i++) {
    var input = readline().split(" ");
    var r = input[0], c = input[1];
    if( r * c >= ((2*r - 1) * (c-1) + (r-1))) {
        print ("YES");
    } else {
        print ("NO");
    }
}

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

const input = [];

readline.on('line', value => {
  input.push(value)
});

readline.on('close', () => {
  const testCount = parseInt(input[0]);
  const variants = input.slice(1).map(str => str.split(' ').map(item => +item));
  variants.forEach(variant => console.log(calculate(variant)));
})

function calculate([n, m]) {
  if (n === 1 || m === 1) {
    return 'YES';
  } else if (n === 2 && m === 2) {
    return 'YES';
  } else {
    return 'NO';
  }
}

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

//main
function main() {
    var nbOfTestCases = parseInt(readline());

    for (var i=0 ; i<nbOfTestCases ; i++) {
        var [n,m] = readline().split(" ").map(e=>parseInt(e));
        console.log(n*m <= (n+m) ? "YES" : "NO");
    }
}

// Q: https://codeforces.com/contest/1348/problem/A

const readline = require('readline');

let input = [];

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

rl.on('line', lineInput => {
	input.push(lineInput);
});

rl.on('close', () => {
	const test = parseInt(input[0]);
	for (let i=0; i < test; i++) {
        let n, m;
		[n, m] = input[i+1].split(' ').map((a) => parseInt(a));
		console.log(solution(n, m));
	}
});

function solution(n, m) {
	return 2*n*m - n - m <= n*m ? 'YES' : 'NO';
}

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line.split(' '));
}).on('close', () => {
  for(i = 1; i < lines.length; i++) {
    if (
      (lines[i][0] == 1 || lines[i][1] == 1) ||
      (lines[i][0] == 2 && lines[i][1] == 2)
    ) {
      process.stdout.write(`YES\n`);
    } else {
      process.stdout.write(`NO\n`);
    }
  }

});

var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main(){
	var t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var one = nextIntArray();
		var N = one[0];
		var M = one[1];
		if(N == 1 || M == 1){
			output[i] = "YES";
		}else if(N == 2 && M == 2){
			output[i] = "YES";
		}else{
			output[i] = "NO";
		}
	}
	myout(myconv(output,9));
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const cases = readline();
    var i;
    for (i = 0; i < cases; i++) {
        const line = readline();
        var a = parseInt(line.split(" ")[0]);
        var b = parseInt(line.split(" ")[1]);

        solve(Math.min(a, b), Math.max(a, b));
    }
}

function solve(a, b) {
    if (a == 1) console.log('YES')
    else if (b < 3) console.log('YES')
    else console.log ('NO');
}

//Puzzle Pieces

const {EOL} = require('os');

let inp = '';

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

process.stdin.on('end', () => {
    let lines = inp.split(EOL);

    let t = +lines[0];

    for(let i = 0; i < t; i++)   {
    	let arr = lines[i + 1].split(' ').map(c => +c);
    	if(arr[0] == 1 || arr[1] == 1 || (arr[0] == 2 && arr[1] == 2))  {
    		process.stdout.write('YES' + EOL);
    	}  else  {
    		process.stdout.write('NO' + EOL);
    	}
    }

    return;
});

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  const [a, b] = d.split(' ').map(Number);

  if (a === 1 || b === 1) {
    console.log('YES');
  }
  else if (a === 2 && b === 2) {
    console.log('YES');
  }
  else {
    console.log('NO');
  }

  c++;
});

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line.split(' '));
}).on('close', () => {
  lines.map((index, i) => {
    if (i > 0) {
      if ((`${index[0]}` === '2' && `${index[1]}` === '2') ||
        (`${index[0]}` === '1' || `${index[1]}` === '1')) {
        process.stdout.write(`YES\n`);
      } else {
        process.stdout.write(`NO\n`);
      }
    }
  })
});

const processData = (lines) => {
  const n = +lines[0]
  for (let i=0; i<n; i++) {
    const [a, b] = lines[i+1].split(' ').map(x => +x).sort((a, b) => a-b)

    if (a === 1) {
      console.log('YES')
    } else {
      if (a === 2 && b === 2) {
        console.log('YES')
      } else {
        console.log('NO')
      }
    }
  }
}

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

// node template.js < A-small.in > A-small.out

function main() {
    var tests = 1;
    tests = nextInt();

    for (let t = 1; t <= tests; t++) {
        let N = nextInt(), M = nextInt();

        let result = (ok(N, M) ? "YES" : "NO");

        print(result);
    }
}

function ok(n, m) {
    if (n > m) {
        let tmp = n;
        n = m;
        m = tmp;
    }
    if (n==1) return true;
    if (n==2 && m == 2) return true;
    return false;
}

// ------- Template ------------------
function newTensor(dimensions, value) {
    let res = [];
    let dim = dimensions[0], subdim = dimensions.slice(1);
    if (subdim.length == 0) {
        for(let i = 0; i < dim; i++) {
            res.push(value);
        }
    } else {
        for(let i = 0; i < dim; i++) {
            res.push(newTensor(subdim, value));
        }
    }
    return res;
}

if (!String.prototype.startsWith) {
    Object.defineProperty(String.prototype, 'startsWith', {
        value: function(search, rawPos) {
            var pos = rawPos > 0 ? rawPos|0 : 0;
            return this.substring(pos, pos + search.length) === search;
        }
    });
}
if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
        return this.substring(this_len - search.length, this_len) === search;
    };
}

var curTokens = [], curToken = 0;

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

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

// code for nodejs
var inputBuffer = '', curLine = 0;

function readline() {
    return inputBuffer[curLine++];
}

function print(data) {
    process.stdout.write(data + '\n');
}

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

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

process.stdin.on('end', function () {
    inputBuffer = inputBuffer.split(/[\s]+/);
    main();
});

'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++];
}
/**
    3
1 3
100000 100000
2 2

**/

function main() {
    var range = readline();

    for(var r=0;r<range;r++) {
        var [x,y] = readline().split(" ").map(Number);

        if(x === 1 || y === 1) {
            console.log("YES");
        } else if(x===2 && y === 2) {
            console.log("YES");
        } else {
            console.log("NO");
        }
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const cases = readline();
    var i;
    for (i = 0; i < cases; i++) {
        const line = readline();
        var a = parseInt(line.split(" ")[0]);
        var b = parseInt(line.split(" ")[1]);

        solve(a, b);
    }
}

function solve(a, b) {
    if (a == 1) console.log('YES')
    else if (b < 3) console.log('YES')
    else console.log ('NO');
}

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line.split(' '));
}).on('close', () => {
  console.log(lines);
  lines.map((index, i) => {
    if (i > 0) {
      if ((`${index[0]}` === '2' && `${index[1]}` === '2') ||
        (`${index[0]}` === '1' || `${index[1]}` === '1')) {
        process.stdout.write(`YES\n`);
      } else {
        process.stdout.write(`NO\n`);
      }
    }
  })
});


Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.

The first input line contains integer n (1 ≤ n ≤ 100) — amount of numbers in the sequence. The second line contains n space-separated integer numbers — elements of the sequence. These numbers don't exceed 100 in absolute value.

If the given sequence has the second order statistics, output this order statistics, otherwise output NO.

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  arr.sort((a, b) => a - b);
  let ans = 'NO';
  let min = arr[0];

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== min) {
      ans = arr[i];
      break;
    }
  }

  console.log(ans);

  c++;
});

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

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

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

function main() {
	var n = parseInt(readline());
	var sequence = tokenizeIntegers(readline());
	sequence.sort(function(a, b) {
		return a-b;
	});

	for (var pos = 1; pos < sequence.length; pos += 1) {
		if (sequence[pos] != sequence[0]) {
			print(sequence[pos]);
			return;
		}
	}

	print("NO");
}

main();

'use strict'

const N = +readline()
let lll = readline().split(' ').map(v => parseInt(v))
lll.sort((a, b) => a - b)

let i = 1
let min = lll[0]
while (lll[i] == min) i++

print(lll[i] == null ? 'NO' : lll[i])


The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually calculate some value which would represent how high the temperatures are.Mathematicians of Berland State University came up with a special heat intensity value. This value is calculated as follows:Suppose we want to analyze the segment of $$$n$$$ consecutive days. We have measured the temperatures during these $$$n$$$ days; the temperature during $$$i$$$-th day equals $$$a_i$$$.We denote the average temperature of a segment of some consecutive days as the arithmetic mean of the temperature measures during this segment of days. So, if we want to analyze the average temperature from day $$$x$$$ to day $$$y$$$, we calculate it as $$$\frac{\sum \limits_{i = x}^{y} a_i}{y - x + 1}$$$ (note that division is performed without any rounding). The heat intensity value is the maximum of average temperatures over all segments of not less than $$$k$$$ consecutive days. For example, if analyzing the measures $$$[3, 4, 1, 2]$$$ and $$$k = 3$$$, we are interested in segments $$$[3, 4, 1]$$$, $$$[4, 1, 2]$$$ and $$$[3, 4, 1, 2]$$$ (we want to find the maximum value of average temperature over these segments).You have been hired by Berland State University to write a program that would compute the heat intensity value of a given period of days. Are you up to this task?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the number of days in the given period, and the minimum number of days in a segment we consider when calculating heat intensity value, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 5000$$$) — the temperature measures during given $$$n$$$ days.

Print one real number — the heat intensity value, i. e., the maximum of average temperatures over all segments of not less than $$$k$$$ consecutive days. Your answer will be considered correct if the following condition holds: $$$|res - res_0| < 10^{-6}$$$, where $$$res$$$ is your answer, and $$$res_0$$$ is the answer given by the jury's solution.

var line = readline ();
line = line.trim ().split ( ' ' );
line.map ( function ( a ) { return (+ a); } );
var n, k;
n = line [ 0 ];
k = line [ 1 ];
var a = readline ();
a = a.trim ().split ( ' ' );
a.map ( function ( b ) { return (+ b); } );
var dp = [ ];
var i, j;
dp [ 0 ] = [ ];
for ( i = 0; i < n; i ++ )
    dp [ 0 ][ i ] = a [ i ];
for ( i = 1; i < n; i ++ ) {
    dp [ i ] = [ ];
    for ( j = i; j < n; j ++ )
        dp [ i ][ j ] = (+ dp [ i - 1 ][ j - 1 ]) + (+ a [ j ]);
}
var max = 0;
for ( i = k - 1; i < n; i ++ )
    for ( j = i; j < n; j ++ )
        if ( (dp [ i ][ j ] / (i + 1)) > max )
            max = dp [ i ][ j ] / (i + 1);
print ( max );


There is a country with $$$n$$$ citizens. The $$$i$$$-th of them initially has $$$a_{i}$$$ money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have.Sometimes the government makes payouts to the poor: all citizens who have strictly less money than $$$x$$$ are paid accordingly so that after the payout they have exactly $$$x$$$ money. In this case the citizens don't send a receipt.You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^{5}$$$) — the numer of citizens. The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_{i} \le 10^{9}$$$) — the initial balances of citizens. The next line contains a single integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^{5}$$$) — the number of events. Each of the next $$$q$$$ lines contains a single event. The events are given in chronological order. Each event is described as either 1 p x ($$$1 \le p \le n$$$, $$$0 \le x \le 10^{9}$$$), or 2 x ($$$0 \le x \le 10^{9}$$$). In the first case we have a receipt that the balance of the $$$p$$$-th person becomes equal to $$$x$$$. In the second case we have a payoff with parameter $$$x$$$.

Print $$$n$$$ integers — the balances of all citizens after all events.

NoteIn the first example the balances change as follows: 1 2 3 4 $$$\rightarrow$$$ 3 3 3 4 $$$\rightarrow$$$ 3 2 3 4 $$$\rightarrow$$$ 3 2 3 4In the second example the balances change as follows: 3 50 2 1 10 $$$\rightarrow$$$ 3 0 2 1 10 $$$\rightarrow$$$ 8 8 8 8 10 $$$\rightarrow$$$ 8 8 20 8 10

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

var main = function() {"use strict";
    // TODO
    var n = rdN();
    var A = [null].concat(rdArN());
    var LC = crAr(n + 1, 0);
    var CS = [];
    var q = rdN();

    while (q --> 0) {
        var input = rdArN();
        var op = input[0];
        if (op === 1) {
            var p = input[1];
            var x = input[2];
            A[p] = x;
            LC[p] = CS.length;
        } else if (op === 2) {
            var x = input[1];
            CS.push(x);
        }
    }
    for (var i = CS.length - 2; i >= 0; --i) {
        CS[i] = Math.max(CS[i], CS[i+1]);
    }
    //prAr(LC);
    //prAr(CS);
    for (var i = 1; i <= A.length; ++i) {
        var lc = LC[i];
        var cs = CS[lc];
        if (A[i] < cs) {
            A[i] = cs;
        }
    }
    prAr(A.slice(1));
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true);for(var i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}var primes=[];for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{configurable:true,enumerable:false,value:v});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});
defineProperty(Set.prototype,'union',function(s){return new Set([...this,...s]);});
defineProperty(Set.prototype,'intersection',function(s){return new Set([...this].filter((v)=>s.has(v)));});
defineProperty(Set.prototype,'difference',function(s){return new Set([...this].filter((v)=>!s.has(v)));});

main();
return OUTPUT;
})();

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

var main = function() {"use strict";
    // TODO
    var n = rdN();
    var A = [null].concat(rdArN());
    var LC = crAr(n + 1, 0);
    var CS = [];
    var q = rdN();

    while (q --> 0) {
        var input = rdArN();
        var op = input[0];
        if (op === 1) {
            var p = input[1];
            var x = input[2];
            A[p] = x;
            LC[p] = CS.length;
        } else if (op === 2) {
            var x = input[1];
            CS.push(x);
        }
    }
    for (var i = CS.length - 2; i >= 0; --i) {
        CS[i] = Math.max(CS[i], CS[i+1]);
    }
    //prAr(LC);
    prAr(CS);
    for (var i = 1; i <= A.length; ++i) {
        var lc = LC[i];
        var cs = CS[lc];
        if (A[i] < cs) {
            A[i] = cs;
        }
    }
    prAr(A.slice(1));
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true);for(var i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}var primes=[];for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{configurable:true,enumerable:false,value:v});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});
defineProperty(Set.prototype,'union',function(s){return new Set([...this,...s]);});
defineProperty(Set.prototype,'intersection',function(s){return new Set([...this].filter((v)=>s.has(v)));});
defineProperty(Set.prototype,'difference',function(s){return new Set([...this].filter((v)=>!s.has(v)));});

main();
return OUTPUT;
})();

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

var main = function() {"use strict";
    // TODO
    var n = rdN();
    var A = [null].concat(rdArN());
    var LC = crAr(n + 1, 0);
    var CS = [];
    var q = rdN();

    while (q --> 0) {
        var input = rdArN();
        var op = input[0];
        if (op === 1) {
            var p = input[1];
            var x = input[2];
            A[p] = x;
            LC[p] = CS.length;
        } else if (op === 2) {
            var x = input[1];
            CS.push(x);
        }
    }
    for (var i = CS.length - 2; i > 0; --i) {
        CS[i] = Math.min(CS[i], CS[i+1]);
    }
    //prAr(LC);
    //prAr(CS);
    for (var i = 1; i <= A.length; ++i) {
        var lc = LC[i];
        var cs = CS[lc];
        if (A[i] < cs) {
            A[i] = cs;
        }
    }
    prAr(A.slice(1));
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true);for(var i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}var primes=[];for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{configurable:true,enumerable:false,value:v});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});
defineProperty(Set.prototype,'union',function(s){return new Set([...this,...s]);});
defineProperty(Set.prototype,'intersection',function(s){return new Set([...this].filter((v)=>s.has(v)));});
defineProperty(Set.prototype,'difference',function(s){return new Set([...this].filter((v)=>!s.has(v)));});

main();
return OUTPUT;
})();


Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.

The first line contains three integers n, m and d (1 ≤ n, m ≤ 100, 1 ≤ d ≤ 104) — the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 ≤ aij ≤ 104).

In a single line print a single integer — the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).

print(function(n, m, d) {
	var a = [];
	for (var i = 0; i < n; i++) {
		a.push.apply(a, readline().split(' ').map(Number));
	}
	n = n * m;

	a = a.sort(function(a, b) {
		return a - b;
	}).map(function(v, i, a) {
		return v - a[0];
	});

	return a.some(function(v) {
		return v % d > 0;
	}) ? -1 : a.map(function(v) {
		return v / d;
	}).reduce(function(q, p, i, a) {
		return q + Math.abs(p - a[~~(n / 2)]);
	}, 0);

}.apply(0, readline().split(' ').map(Number)));

nmd = readline().split(' ').map(Number); n = nmd[0]; m = nmd[1]; d = nmd[2];

function fn() {
    a = readline().split(' ').map(Number);
    x = a[0] % d;
    for (j = 1; j < m; j++) if (x !== a[j] % d) return -1;
    A = [].concat(a);
    for (i = 1; i < n; i++) {
        a = readline().split(' ').map(Number);
        for (j = 0; j < m; j++) if (x !== a[j] % d) return -1;
        A = A.concat(a);
    }
    A = A.map(i => (i - x) / d).sort((a,b) => a-b);
    i=0;j=A.length-1;a=1;b=1;r=0;
    while(i < j) {
        if(a < b) {
            r += a*(A[i+1] - A[i]);
            a++;i++;
        } else {
            r += b*(A[j] - A[j-1]);
            b++;j--;
        }
    }
    return r;
}
write(fn());

nmd = readline().split(' ').map(Number); n = nmd[0]; m = nmd[1]; d = nmd[2];

function fn() {
    a = readline().split(' ').map(Number);
    x = a[0] % d;
    for (j = 1; j < m; j++) if (x !== a[j] % d) return -1;
    A = [].concat(a);
    for (i = 1; i < n; i++) {
        a = readline().split(' ').map(Number);
        for (j = 0; j < m; j++) if (x !== a[j] % d) return -1;
        A = A.concat(a);
    }

    A = A.map(i => (i - x) / d).sort((a,b) => a-b);
    i=0;j=A.length-1;a=1;b=1;r=0;
    while(i < j) r += a < b ? a++*(A[i+1] - A[i++]) : b++*(A[j] - A[--j]);
    return r;
}
write(fn());

ip = readline().split(" ");
n = parseInt(ip[0]);
m = parseInt(ip[1]);
d = parseInt(ip[2]);
var A = new Array();
var B = new Array();
tik = 0;

for (var i = 0; i < n && tik == 0; i++){
    A[i] = readline().split(" ");
    for (var j = 0; j < m && tik == 0; j++){
        if (parseInt(A[0][0]) % d != parseInt(A[i][j]) % d){
            write(-1);
            tik = 1;
        }
        B.push(Math.floor(parseInt(A[i][j]) / d));
    }
}
if (tik == 0){
    B = B.sort(function(a, b){return parseInt(a)-parseInt(b)});
    avgi = Math.floor(B.length / 2);
    avg = B[avgi];
    sum = 0;
    for (var i = 0; i < B.length; i++){
        sum += Math.abs(parseInt(B[i]) - parseInt(avg));
    }
    write(sum);
}

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var rowNum = integers[0], colNum = integers[1], delta = integers[2];

	var factors = [];
	row = tokenizeIntegers(readline());
	var remainder = row[0]%delta;

	for (var r = 0; r < rowNum; r += 1) {
		if (r != 0) {
			row = tokenizeIntegers(readline());
		}
		for (var c = 0; c < colNum; c += 1) {
			if (row[c]%delta != remainder) {
				print(-1);
				return;
			}
			factors.push(row[c]);
		}
	}

	factors.sort(function(a, b) {
		return a-b;
	});

	var best = factors.length * -factors[0];
	for (var i = 0; i < factors.length; i += 1) {
		best += factors[i];
	}

	var total = best, n = factors.length;
	for (var i = 1; i < n; i += 1) {
		var jump = factors[i] - factors[i-1];
		total += i * jump;
		total -= (n-i) * jump;
		best = Math.min(best, total);
	}

	print(best/delta);
}

main();

print(function(n, m, d) {
	var a = [];
	for (var i = 0; i < n; i++) {
		a.push.apply(a, readline().split(' ').map(Number));
	}

	a = a.sort(function(a, b) {
		return a - b;
	}).map(function(v, i, a) {
		return v - a[0];
	});

	return a.some(function(v) {
		return v % d > 0;
	}) ? -1 : a.map(function(v) {
		return v / d;
	}).reduce(function(q, p, i, a) {
		return q + Math.abs(p - a[~~n / 2]);
	}, 0);

}.apply(0, readline().split(' ').map(Number)));

print(function(n, m, d) {
	var a = [];
	for (var i = 0; i < n; i++) {
		a.push.apply(a, readline().split(' ').map(Number));
	}
	n = n * m;

	a = a.sort(function(a, b) {
		return a - b;
	}).map(function(v, i, a) {
		return v - a[0];
	});

	return a.some(function(v) {
		return v % d > 0;
	}) ? -1 : a.map(function(v) {
		return v / d;
	}).reduce(function(q, p, i, a) {
		return q + Math.abs(p - a[~~n / 2]);
	}, 0);

}.apply(0, readline().split(' ').map(Number)));

nmd = readline().split(' ').map(Number); n = nmd[0]; m = nmd[1]; d = nmd[2];

function fn() {
    a = readline().split(' ').map(Number);
    x = a[0] % d;
    for (j = 1; j < m; j++) if (x !== a[j] % d) return -1;
    A = [].concat(a);
    for (i = 1; i < n; i++) {
        a = readline().split(' ').map(Number);
        for (j = 0; j < m; j++) if (x !== a[j] % d) return -1;
        A = A.concat(a);
    }
    A = A.map(i => (i - x) / d).sort((a,b) => a-b);
    i=0;j=5;a=1;b=1;r=0;
    while(i < j) {
        if(a < b) {
            r += a*(A[i+1] - A[i]);
            a++;i++;
        } else {
            r += b*(A[j] - A[j-1]);
            b++;j--;
        }
    }
    return r;
}
write(fn());

nmd = readline().split(' ').map(Number); n = nmd[0]; m = nmd[1]; d = nmd[2];

function fn() {
    a = readline().split(' ').map(Number);
    A = [].concat(a);
    x = a[0] % d;
    for (j = 1; j < m; j++) if (x !== a[j] % d) return -1;
    for (i = n-1; i; --i) {
        a = readline().split(' ').map(Number);
        for (j = 0; j < m; j++) if (x !== a[j] % d) return -1;
        A = A.concat(a);
    }
    var mediana = A.reduce((res, i) => res + i, 0) / (n * m);
    return A.reduce((res, i) => res + Math.abs(i - mediana) / d, 0);
}
write(fn());

nmd = readline().split(' ').map(Number); n = nmd[0]; m = nmd[1]; d = nmd[2];

function fn() {
    a = readline().split(' ').map(Number);
    x = a[0] % d;
    for (j = 1; j < m; j++) if (x !== a[j] % d) return -1;
    A = [].concat(a);
    for (i = 1; i < n; i++) {
        a = readline().split(' ').map(Number);
        for (j = 0; j < m; j++) if (x !== a[j] % d) return -1;
        A = A.concat(a);
    }
    var mediana = A.reduce((res, i) => res + i, 0) / (n * m);
    return A.reduce((res, i) => res + Math.abs(i - mediana) / d, 0);
}
write(fn());

ip = readline().split(" ");
n = parseInt(ip[0]);
m = parseInt(ip[1]);
d = parseInt(ip[2]);
var A = new Array();
var B = new Array();
prev = 0;
sum = 0;
s1 = 0;
s2 = 0;
tik = 0;

for (var i = 0; i < n && tik == 0; i++){
	A[i] = readline().split(" ");
	for (var j = 0; j < m && tik == 0; j++){
		if (i == 0 && j == 0){
			prev = parseInt(A[i][j]) % d;
		} else {
			if (prev != parseInt(A[i][j]) % d){
				write(-1);
				tik = 1;
			}
		}
		B.push(parseInt(A[i][j]) / d);
		sum += parseInt(A[i][j]) / d;
	}
}
if (tik == 0){
	avg = Math.floor(sum/B.length);
	avg1 = avg + 1;
	for (var i = 0; i < B.length; i++){
		if (B[i] > avg){
			s1 += (B[i] - avg);
		} else {
			s1 += (avg - B[i]);
		}
		if (B[i] > avg1){
			s2 += (B[i] - avg1);
		} else {
			s2 += (avg1 - B[i]);
		}
	}
	write(Math.min(s1,s2));
}

ip = readline().split(" ");
n = parseInt(ip[0]);
m = parseInt(ip[1]);
d = parseInt(ip[2]);
var A = new Array();
var B = new Array();
tik = 0;

for (var i = 0; i < n && tik == 0; i++){
	A[i] = readline().split(" ");
	for (var j = 0; j < m && tik == 0; j++){
		if (parseInt(A[0][0]) % d != parseInt(A[i][j]) % d){
			write(-1);
			tik = 1;
		}
		B.push(parseInt(A[i][j]) / d);
	}
}
if (tik == 0){
	B = B.sort();
	avg = B.length / 2;
	avg = B[avg];
	write(avg);

}

ip = readline().split(" ");
n = parseInt(ip[0]);
m = parseInt(ip[1]);
d = parseInt(ip[2]);
var A = new Array();
var B = new Array();
tik = 0;

for (var i = 0; i < n && tik == 0; i++){
	A[i] = readline().split(" ");
	for (var j = 0; j < m && tik == 0; j++){
		if (parseInt(A[0][0]) % d != parseInt(A[i][j]) % d){
			write(-1);
			tik = 1;
		}
		B.push(parseInt(A[i][j]) / d);
	}
}
if (tik == 0){
	B = B.sort();
	avg = B.length / 2;
	avg = B[avg];
	sum = 0;
	for (var i = 0; i < B.length; i++){
		sum = Math.abs(B[i] - avg);
	}
	write(sum);
}

ip = readline().split(" ");
n = parseInt(ip[0]);
m = parseInt(ip[1]);
d = parseInt(ip[2]);
var A = new Array();
var B = new Array();
tik = 0;

for (var i = 0; i < n && tik == 0; i++){
	A[i] = readline().split(" ");
	for (var j = 0; j < m && tik == 0; j++){
		if (parseInt(A[0][0]) % d != parseInt(A[i][j]) % d){
			write(-1);
			tik = 1;
		}
		B.push(parseInt(A[i][j]) / d);
	}
}
if (tik == 0){
	B = B.sort();
	avg = B.length / 2;
	avg = B[avg];
	sum = "";
	for (var i = 0; i < B.length; i++){
		sum += B[i] + " ";
	}
	write(sum);
}

ip = readline().split(" ");
n = parseInt(ip[0]);
m = parseInt(ip[1]);
d = parseInt(ip[2]);
var A = new Array();
var B = new Array();
tik = 0;

for (var i = 0; i < n && tik == 0; i++){
	A[i] = readline().split(" ");
	for (var j = 0; j < m && tik == 0; j++){
		if (parseInt(A[0][0]) % d != parseInt(A[i][j]) % d){
			write(-1);
			tik = 1;
		}
		B.push(parseInt(A[i][j]) / d);
	}
}
if (tik == 0){
	B = B.sort();
	avg = B.length / 2;
	write(avg);

}

ip = readline().split(" ");
n = parseInt(ip[0]);
m = parseInt(ip[1]);
d = parseInt(ip[2]);
var A = new Array();
var B = new Array();
tik = 0;

for (var i = 0; i < n && tik == 0; i++){
	A[i] = readline().split(" ");
	for (var j = 0; j < m && tik == 0; j++){
		if (parseInt(A[0][0]) % d != parseInt(A[i][j]) % d){
			write(-1);
			tik = 1;
		}
		B.push(parseInt(A[i][j]) / d);
	}
}
if (tik == 0){
	B = B.sort();
	avg = B.length / 2;
	avg = B[avg];
	sum = "";
	for (var i = 0; i < B.length; i++){
		sum += Math.abs(B[i] - avg) + " ";
	}
	write(sum);
}

ip = readline().split(" ");
n = parseInt(ip[0]);
m = parseInt(ip[1]);
d = parseInt(ip[2]);
var A = new Array();
var B = new Array();
prev = 0;
sum = 0;
s1 = 0;
tik = 0;

for (var i = 0; i < n && tik == 0; i++){
	A[i] = readline().split(" ");
	for (var j = 0; j < m && tik == 0; j++){
		if (i == 0 && j == 0){
			prev = parseInt(A[i][j]) % d;
		} else {
			if (prev != parseInt(A[i][j]) % d){
				write(-1);
				tik = 1;
			}
		}
		B.push(parseInt(A[i][j]) / d);
	}
}
if (tik == 0){
	B = B.sort();
	avg = B[Math.floor(B.length / 2)];
	for (var i = 0; i < B.length; i++){
		if (B[i] > avg){
			s1 += (B[i] - avg);
		} else {
			s1 += (avg - B[i]);
		}
	}
	write(s1);
}

ip = readline().split(" ");
n = parseInt(ip[0]);
m = parseInt(ip[1]);
d = parseInt(ip[2]);
var A = new Array();
var B = new Array();
tik = 0;

for (var i = 0; i < n && tik == 0; i++){
	A[i] = readline().split(" ");
	for (var j = 0; j < m && tik == 0; j++){
		if (parseInt(A[0][0]) % d != parseInt(A[i][j]) % d){
			write(-1);
			tik = 1;
		}
		B.push(parseInt(A[i][j]) / d);
	}
}
if (tik == 0){
	B = B.sort();
	avg = B.length / 2;
	avg = B[avg];
	sum = 0;
	for (var i = 0; i < B.length; i++){
		sum += Math.abs(B[i] - avg);
	}
	write(sum);
}

ip = readline().split(" ");
n = parseInt(ip[0]);
m = parseInt(ip[1]);
d = parseInt(ip[2]);
var A = new Array();
var B = new Array();
prev = 0;
sum = 0;
s1 = 0;
tik = 0;

for (var i = 0; i < n && tik == 0; i++){
	A[i] = readline().split(" ");
	for (var j = 0; j < m && tik == 0; j++){
		if (i == 0 && j == 0){
			prev = parseInt(A[i][j]) % d;
		} else {
			if (prev != parseInt(A[i][j]) % d){
				write(-1);
				tik = 1;
			}
		}
		B.push(parseInt(A[i][j]) / d);
	}
}
if (tik == 0){
	B = B.sort();
	avg = B[B.length / 2];
	for (var i = 0; i < B.length; i++){
		if (B[i] > avg){
			s1 += (B[i] - avg);
		} else {
			s1 += (avg - B[i]);
		}
	}
	write(s1);
}

ip = readline().split(" ");
n = parseInt(ip[0]);
m = parseInt(ip[1]);
d = parseInt(ip[2]);
var A = new Array();
var B = new Array();
prev = 0;
sum = 0;
s1 = 0;
tik = 0;

for (var i = 0; i < n && tik == 0; i++){
	A[i] = readline().split(" ");
	for (var j = 0; j < m && tik == 0; j++){
		if (i == 0 && j == 0){
			prev = parseInt(A[i][j]) % d;
		} else {
			if (prev != parseInt(A[i][j]) % d){
				write(-1);
				tik = 1;
			}
		}
		B.push(parseInt(A[i][j]) / d);
	}
}
if (tik == 0){
	B = B.sort();
	avg = B[parseInt(B.length / 2)];
	for (var i = 0; i < B.length; i++){
		if (B[i] > avg){
			s1 += (B[i] - avg);
		} else {
			s1 += (avg - B[i]);
		}
	}
	write(s1);
}

ip = readline().split(" ");
n = parseInt(ip[0]);
m = parseInt(ip[1]);
d = parseInt(ip[2]);
var A = new Array();
var B = new Array();
prev = 0;
sum = 0;
s1 = 0;
tik = 0;

for (var i = 0; i < n && tik == 0; i++){
	A[i] = readline().split(" ");
	for (var j = 0; j < m && tik == 0; j++){
		if (i == 0 && j == 0){
			prev = parseInt(A[i][j]) % d;
		} else {
			if (prev != parseInt(A[i][j]) % d){
				write(-1);
				tik = 1;
			}
		}
		B.push(parseInt(A[i][j]) / d);
	}
}
if (tik == 0){
	avg = B[parseInt(B.length / 2)];
	for (var i = 0; i < B.length; i++){
		if (B[i] > avg){
			s1 += (B[i] - avg);
		} else {
			s1 += (avg - B[i]);
		}
	}
	write(s1);
}


There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN".Find the number of cows that can currently show their hands without affecting any betting decisions.

The first line contains a single integer, n (2 ≤ n ≤ 2·105). The second line contains n characters, each either "A", "I", or "F". The i-th character is "A" if the i-th player's status is "ALLIN", "I" if the i-th player's status is "IN", or "F" if the i-th player's status is "FOLDED".

The first line should contain a single integer denoting the number of players that can currently show their hands.

NoteIn the first sample, cows 1, 4, 5, and 6 can show their hands. In the second sample, only cow 3 can show her hand.

;(function () {

	print((function (n, str) {

		var m = {A: 0, F: 0, I: 0};
		for (var i = 0; i < n; i++) m[str[i]]++;
		return m.I > 1 ? 0 : (m.I === 1 ? 1 : m.A);

	})(+readline(), readline()));

}).call(this);


Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≤ i ≤ n; 1 ≤ j ≤ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing. The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

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

  let max = Number.MIN_SAFE_INTEGER;
  let count = 0;

  for (let i = 0; i < len2; i++) {
    const a = arr2[i];
    for (let j = 0; j < len1; j++) {
      const b = arr1[j];
      const div = a / b;
      if (Number.isInteger(div)) {
        if (div > max) {
          max = div;
          count = 0;
        }
        if (div === max) count++;
      }
    }
  }
  console.log(count);
}

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

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

var dp = {};

function fibonacci(n) {
	if (n === 0) return 0;
	if (n === 1) return 1;

	if (dp[n] !== undefined) return dp[n];
	let result = fibonacci(n - 1) + fibonacci(n - 2);
	return (dp[n] = result);
}

function main() {
	let n = readLine() >> 0;
	let a = readLine()
		.split(' ')
		.map(x => x >> 0);
	let m = readLine() >> 0;
	let b = readLine()
		.split(' ')
		.map(x => x >> 0);
	let best = 0;
	let store = {};

	for (let i = 0; i < n; i++) {
		for (let j = m - 1; j >= 0; j--) {
			if (Math.floor(b[j] / a[i]) < best) {
				break;
			}
			if (b[j] % a[i] === 0) {
				best = Math.max(best, b[j] / a[i]);
				store[best] = (store[best] || 0) + 1;
			}
		}
	}
	console.log(store[best]);
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', (inputStd) => {
    inputString += inputStd;
});
process.stdin.on('end', function () {
    inputString = inputString
        .trim()
        .split('\n')
        .map((str) => {
            return str.trim();
        });
    main();
});
function readLine() {
    return inputString[currentLine++];
}

function main() {
    let n = parseInt(readLine());
    let aS = readLine().split(' ').map(Number);
    let m = parseInt(readLine());
    let bS = readLine().split(' ').map(Number);
    let integers = [];
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (Number.isInteger(bS[i] / aS[j])) {
                integers.push(bS[i] / aS[j]);
            }
        }
    }
    integers.sort((a, b) => {
        return b - a;
    });
    let count = 1;
    for (let i = 1; i < integers.length; i++) {
        if (integers[0] === integers[i]) {
            count++;
        }
    }
    console.log(count);
}

print(function(n, a, m, b) {
	var i, j,
		max = 0,
		ans = 0;
	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			if (b[j] % a[i] === 0) {
				if (b[j] / a[i] > max) {
					max = b[j] / a[i];
					ans = 1;
				} else if (b[j] / a[i] === max) {
					ans++;
				}
			}

	return ans;

}(+readline(), readline().split(' ').map(Number), +readline(), readline().split(' ').map(Number)));

;(function () {

	var n = +readline(),
		a = readline().split(' ').map(Number),
		m = +readline(),
		b = readline().split(' ').map(Number),
		c = (function () {
			var t = [], l, max, i, j;
			for (i = 0; i < n; i++)
				for (j = 0; j < m; j++) {
					l = b[j] / a[i];
					if (l === parseInt(l)) {
						t.push(l);
					}
				}
			max = Math.max.apply(null, t);
			return t.filter(function (e) { return e === max; }).length;
		})();

	print(c);

}).call(this);

print(function(n, a, m, b) {
	var i, j, d = new Int8Array(1e4);
	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			if (b[j] % a[i] === 0)
				d[b[j] / a[i]]++;

	d[1] = 0;
	return Math.max.apply(0, d);

}(+readline(), readline().split(' ').map(Number),
  +readline(), readline().split(' ').map(Number)));

print(function(n, a, m, b) {
	var i, j, d = new Int8Array(1e4);
	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			if (b[j] % a[i] === 0)
				d[b[j] / a[i]]++;

	return Math.max.apply(0, d);

}(+readline(), readline().split(' ').map(Number),
  +readline(), readline().split(' ').map(Number)));


Doremy is asked to test $$$n$$$ contests. Contest $$$i$$$ can only be tested on day $$$i$$$. The difficulty of contest $$$i$$$ is $$$a_i$$$. Initially, Doremy's IQ is $$$q$$$. On day $$$i$$$ Doremy will choose whether to test contest $$$i$$$ or not. She can only test a contest if her current IQ is strictly greater than $$$0$$$.If Doremy chooses to test contest $$$i$$$ on day $$$i$$$, the following happens:   if $$$a_i>q$$$, Doremy will feel she is not wise enough, so $$$q$$$ decreases by $$$1$$$;  otherwise, nothing changes.  If she chooses not to test a contest, nothing changes.Doremy wants to test as many contests as possible. Please give Doremy a solution.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 10^9$$$) — the number of contests and Doremy's IQ in the beginning. The second line contains $$$n$$$ integers $$$a_1,a_2,\cdots,a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the difficulty of each contest. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, you need to output a binary string $$$s$$$, where $$$s_i=1$$$ if Doremy should choose to test contest $$$i$$$, and $$$s_i=0$$$ otherwise. The number of ones in the string should be maximum possible, and she should never test a contest when her IQ is zero or less. If there are multiple solutions, you may output any.

NoteIn the first test case, Doremy tests the only contest. Her IQ doesn't decrease.In the second test case, Doremy tests both contests. Her IQ decreases by $$$1$$$ after testing contest $$$2$$$.In the third test case, Doremy tests contest $$$1$$$ and $$$2$$$. Her IQ decreases to $$$0$$$ after testing contest $$$2$$$, so she can't test contest $$$3$$$.

let i = '';
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL); /*your input text, split by lines*/
    const splitLines = lines.map(x => x.split(" ").map(x => parseInt(x)))
    for (let i = 0; i < splitLines[0][0]; i ++)
    {
        const currentArray = splitLines.slice(2 * i + 1, 2 * i + 3);
        const n = currentArray[0][0];
        const q = currentArray[0][1];
        let q0 = 0;
        let str = "";
        for (let i = currentArray[1].length - 1; i >= 0; i --)
        {

            if (q0 >= currentArray[1][i])
            {
                str = 1 + str;
            }
            else if (q0 < q)
            {
                q0 ++;
                str = 1 + str;
            }
            else
            {
                str = 0 + str;
            }
        }

        console.log(str)
    }
})

function dormey(n,q,arr){
    let q1=0;
    let ans=[];
    for(let i=n-1;i>=0;i--){
        if(arr[i]<=q1){
           ans[i]=1;
        }
        else{
            if(q1<q){
                q1++;
                ans[i]=1;
            }
            else{
                ans[i]=0;
            }
        }
    }
    return ans.join("");
}
function runProgram(input){
    input = input.trim().split("\n");
    var tc =+input[0];
    var line=1;
    for(var i=0;i<tc;i++){
        var x = input[line++].trim().split(" ").map(Number);
        var n=x[0];
        var q =x[1];
        var arr = input[line++].trim().split(" ").map(Number);
        var res = dormey(n,q,arr);
        console.log(res);
    }

}
if (process.env.USER === "") {
  runProgram(``);
} else {
  process.stdin.resume();
  process.stdin.setEncoding("ascii");
  let read = "";
  process.stdin.on("data", function (input) {
    read += input;
  });
  process.stdin.on("end", function () {
    read = read.replace(/\n$/, "");
    read = read.replace(/\n$/, "");
    runProgram(read);
  });
  process.on("SIGINT", function () {
    read = read.replace(/\n$/, "");
    runProgram(read);
    process.exit(0);
  });
}

const fs = require("fs");

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

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const [n, q] = input[index]
      .trim()
      .split(" ")
      .map((a) => parseInt(a));
    index++;
    const a = input[index]
      .trim()
      .split(" ")
      .map((a) => parseInt(a));
    const testCase = {
      n,
      q,
      a,
    };

    testCases.push(testCase);
  }
}

function solution(testCase, index) {
  const { n, q, a } = testCase;
  let result = "";
  let iq = 0;
  for (let i = n - 1; i >= 0; i--) {
    if (a[i] <= iq) result = "1" + result;
    else if (a[i] > iq && iq < q) {
      iq++;
      result = "1" + result;
    } else result = "0" + result;
  }

  console.log(result);
}

parseInput();

testCases.forEach(solution);

'use strict';

function solve(n, m, a) {
  if (m >= n) return '1'.repeat(n);
  let l = 0,
      r = n - 1;
  const check = s => {
    let t = m;
    for (let i = s; i < n; i++) {
      if (a[i] > t) t--;
      if (t < 0) return false;
    }
    return true;
  };
  while (l < r) {
    const mid = l + r >> 1;
    if (check(mid)) {
      r = mid;
    } else {
      l = mid + 1;
    }
  }
  let res = new Array(n).fill(0);
  for (let i = l; i < n; i++) res[i] = 1;
  for (let i = 0; i < l; i++) if (a[i] <= m) res[i] = 1;
  return res.join('');
}

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

let input = ''
process.stdin.on('data', chunk => input += chunk)
process.stdin.on('end', () => {
    let array = input.trim().split('\n').slice(1).map(item => item.replace('\r', ''))
    .map(item => item.split(' '));
    array.forEach((item, index, arr) =>{
        if(index % 2 === 0 || index === 0){
            let result = new Array(arr[index][0]*1).fill(0);
            let iq = arr[index][1];
            let test = array[index+1];
            let step = 0;
            for (let i = arr[index][0]-1; i >= 0; i--) {
            if ( test[i] <= step) {
                result[i] = 1;
            } else {
                if (step < iq) {
                    step++;
                    result[i] = 1;
                }
            }
            }
        console.log(result.join(''));
        }
    })
});

const main = () => {

	var t = readInt();
	var allans = [];
	for (var zz = 0; zz < t; zz++) {
		var arr = readIntArr();
		var n, q;
		n = arr[0]; q = arr[1];
		a = readIntArr();

		var ans = [];
		// go from back since ideal to keep v large for as long as possible?
		if (q >= n) {
			for (var i = 0; i < n; i++) ans.push('1');
		} else {
			for (var i = 0; i < n; i++) ans.push('0');
			var v = 0;
			for (var i = n - 1; i > -1; i--) {
				if (a[i] > v) {
					if (v < q) {
						v += 1;
						ans[i] = '1';
					}
				} else {
					ans[i] = '1';
				}
			}
		}
		allans.push(ans.join(''));
	}
	multiLineArrayPrint(allans);

	return;
}

const readInt = () => parseInt(readline());
const readString = () => readline();
const readIntArr = () => readline().split(" ").map(zzzz => parseInt(zzzz));
const parseLong = (string) => { // javascript's largest long is < (1<<62)
	var n = string.length;
	var res = 0;
	for (var i = 0; i < n; i++) {
		res *= 10;
		res += parseInt(string[i]);
	}
	return res;
}
const readLong = () => parseLong(readLong());
const readLongArr = () => readline().split(" ").map(zzzz => parseLong(zzzz));
const oneLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join(' '));
const multiLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join('\n'));
const multiLineArrayOfArraysPrint = (arr) => print(arr.map(yyyy => yyyy.map(zzzz => zzzz.toString()).join(' ')).join('\n'));
const makeArr = (defaultVal, dimensionsArr) => {
	var n = dimensionsArr.length;
	if (n === 1) return Array(dimensionsArr[0]).fill(defaultVal);
	else {
		var temp = [];
		for (var i = 0; i < dimensionsArr[0]; i++)
			temp.push(makeArr(defaultVal, dimensionsArr.slice(1)));
		return temp;
	}
}

for (_ = 0; _ < 1; _++) {
	main();
}

// newline for testing
 //newline for testing
// codeforces js cannot use "let" keyword. use "var" instead
// codeforces js cannot destructure arrays

var tests = parseInt(readline());
    for (var t=0; t < tests; t++) {
        var nq = readline().split(' ').map(x=>parseInt(x));
        var arr = readline().split(' ').map(x=>parseInt(x));
        var iq = 0;
        var ans = Array(nq[0]).fill(0);
        for (var i = nq[0]-1; i >= 0; i--) {
            if (arr[i] <= iq) {
                ans[i] = 1;
            } else {
                if (iq < nq[1]) {
                    iq++;
                    ans[i] = 1;
                }
            }
        }
        print(ans.join(''));
    }

'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) {
  const bst = new BinarySearchTree();
  let max = Math.min(n, m),
      t = -1;
  for (let [i, num] of a.entries()) {
    if (num <= m) {
      const cnt = bst.countGreaterThanEq(num + 1);
      let ans = i + 1 - cnt;
      if (cnt <= m - num) {
        ans += cnt;
        ans += Math.min(m - cnt, n - i - 1);
      } else {
        ans += m - num;
        ans += Math.min(num, n - i - 1);
      }
      if (ans > max) {
        max = ans;
        t = i;
      }
      max = Math.max(max, ans);
    }
    bst.insert(num);
  }
  if (t === -1) {
    return '1'.repeat(max).padEnd(n, '0');
  }
  let res = new Array(n).fill(0),
      l = m - a[t],
      r = a[t];
  for (let i = 0; i < n; i++) {
    if (i <= t && a[i] <= a[t]) res[i] = 1;else if (i < t) {
      if (l) {
        res[i] = 1;
        l--;
      }
    } else {
      if (r) {
        res[i] = 1;
        r--;
      }
    }
    if (i === t) r += l;
  }
  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 = (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) {
  const bst = new BinarySearchTree();
  let max = Math.min(n, m),
      t = -1;
  for (let [i, num] of a.entries()) {
    if (num <= m) {
      const cnt = bst.countGreaterThanEq(num + 1);
      let ans = i + 1 - cnt;
      if (cnt <= m - num) {
        ans += cnt;
        ans += Math.min(m - cnt, n - i - 1);
      } else {
        ans += m - num;
        ans += Math.min(num, n - i - 1);
      }
      if (ans > max) {
        max = ans;
        t = i;
      }
      max = Math.max(max, ans);
    }
    bst.insert(num);
  }
  if (t === -1) {
    return '1'.repeat(max).padEnd(n - max, '0');
  }
  let res = new Array(n).fill(0),
      l = m - a[t],
      r = a[t];
  for (let i = 0; i < n; i++) {
    if (i <= t && a[i] <= a[t]) res[i] = 1;else if (i < t) {
      if (l) {
        res[i] = 1;
        l--;
      }
    } else {
      if (r) {
        res[i] = 1;
        r--;
      }
    }
    if (i === t) r += l;
  }
  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 = (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);
});


Mr. Chanek has a new game called Dropping Balls. Initially, Mr. Chanek has a grid $$$a$$$ of size $$$n \times m$$$Each cell $$$(x,y)$$$ contains an integer $$$a_{x,y}$$$ denoting the direction of how the ball will move.  $$$a_{x,y}=1$$$ — the ball will move to the right (the next cell is $$$(x, y + 1)$$$);  $$$a_{x,y}=2$$$ — the ball will move to the bottom (the next cell is $$$(x + 1, y)$$$);  $$$a_{x,y}=3$$$ — the ball will move to the left (the next cell is $$$(x, y - 1)$$$). Every time a ball leaves a cell $$$(x,y)$$$, the integer $$$a_{x,y}$$$ will change to $$$2$$$. Mr. Chanek will drop $$$k$$$ balls sequentially, each starting from the first row, and on the $$$c_1, c_2, \dots, c_k$$$-th ($$$1 \leq c_i \leq m$$$) columns.Determine in which column each ball will end up in (position of the ball after leaving the grid).

The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \leq n, m \leq 1000$$$, $$$1 \leq k \leq 10^5$$$) — the size of the grid and the number of balls dropped by Mr. Chanek. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1},a_{i,2},\ldots,a_{i,m}$$$ ($$$1 \leq a_{i,j} \leq 3$$$). It will satisfy $$$a_{i, 1} \ne 3$$$ and $$$a_{i, m} \ne 1$$$. The next line contains $$$k$$$ integers $$$c_1, c_2, \ldots, c_k$$$ ($$$1 \leq c_i \leq m$$$) — the balls' column positions dropped by Mr. Chanek sequentially.

Output $$$k$$$ integers — the $$$i$$$-th integer denoting the column where the $$$i$$$-th ball will end.

NoteIn the first example, the first ball will drop as follows. Note that the cell $$$(1, 1)$$$ will change direction to the bottom direction.  The second and third balls will drop as follows.   All balls will be dropped from the first row and on the $$$c_1, c_2, \dots, c_k$$$-th columns respectively. A ball will stop dropping once it leaves the grid.

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

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

function main () {
	let [n, m, k] = rna();
	let g = Array.from(Array(n), x => Array(m));

	for (let i in g)
		g[i] = rna();

	const c = rna();
	let ans = [];
	for (let j of c) {
		j--; // 0indexing
		let i = 0;
		while (i < n) {
			const dir = g[i][j];
			g[i][j] = 2;
			if (dir == 1) j++;
			if (dir == 2) i++;
			if (dir == 3) j--;
		}
		ans.push(j+1);
	}
	console.log(ans.join(' '));
}


A binary string is a string that consists of characters $$$0$$$ and $$$1$$$. A bi-table is a table that has exactly two rows of equal length, each being a binary string.Let $$$\operatorname{MEX}$$$ of a bi-table be the smallest digit among $$$0$$$, $$$1$$$, or $$$2$$$ that does not occur in the bi-table. For example, $$$\operatorname{MEX}$$$ for $$$\begin{bmatrix} 0011\\ 1010 \end{bmatrix}$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ occur in the bi-table at least once. $$$\operatorname{MEX}$$$ for $$$\begin{bmatrix} 111\\ 111 \end{bmatrix}$$$ is $$$0$$$, because $$$0$$$ and $$$2$$$ do not occur in the bi-table, and $$$0 < 2$$$.You are given a bi-table with $$$n$$$ columns. You should cut it into any number of bi-tables (each consisting of consecutive columns) so that each column is in exactly one bi-table. It is possible to cut the bi-table into a single bi-table — the whole bi-table.What is the maximal sum of $$$\operatorname{MEX}$$$ of all resulting bi-tables can be?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of the description of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of columns in the bi-table. Each of the next two lines contains a binary string of length $$$n$$$ — the rows of the bi-table. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the maximal sum of $$$\operatorname{MEX}$$$ of all bi-tables that it is possible to get by cutting the given bi-table optimally.

NoteIn the first test case you can cut the bi-table as follows:  $$$\begin{bmatrix} 0\\ 1 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$2$$$. $$$\begin{bmatrix} 10\\ 10 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$2$$$. $$$\begin{bmatrix} 1\\ 1 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$0$$$. $$$\begin{bmatrix} 0\\ 1 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$2$$$. $$$\begin{bmatrix} 0\\ 0 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$1$$$. $$$\begin{bmatrix} 0\\ 0 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$1$$$.The sum of $$$\operatorname{MEX}$$$ is $$$8$$$.

"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 arr1 = readline()
      .trim()
      .split("")
      .map((cur) => parseInt(cur));
    let arr2 = readline()
      .trim()
      .split("")
      .map((cur) => parseInt(cur));
    let ans = 0;
    for (let i = 0; i < n; i++) {
      if (arr1[i] !== arr2[i]) {
        ans += 2;
      } else {
        if (arr1[i] === 0) {
          if (i + 1 < n) {
            if (arr1[i + 1] === 1 && arr2[i + 1] === 1) {
              ans += 2;
              i++;
            } else ans++;
          } else ans++;
        } else {
          if (i + 1 < n) {
            if (arr1[i + 1] === 0 && arr2[i + 1] === 0) {
              ans += 2;
              i++;
            }
          }
        }
      }
    }
    console.log(ans);
  }
};
solve();


DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?

The first line contains a single string s (1 ≤ |s| ≤ 103). The second line contains a single integer k (0 ≤ k ≤ 103). The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.

Print a single integer — the largest possible value of the resulting string DZY could get.

NoteIn the test sample DZY can obtain "abcbbc", value = 1·1 + 2·2 + 3·2 + 4·2 + 5·2 + 6·2 = 41.

var s = readline()
var k = Number(readline())
var w = readline().split(' ').map(Number)
var l = s.length
var c = Math.max.apply(null, w) * k * (2 * l + k + 1) / 2
for (var i = 1; i <= l; ++i) {
    c += i * w[s.charCodeAt(i - 1) - 'a'.charCodeAt()]
}
print(c)

function main(str,k,arr){

    var t = 0;
    for(var i = 1 ; i <= str.length ; i++){
      t += (arr[str.charCodeAt(i-1)-'a'.charCodeAt(0)]*i);

    }
    var max = -Infinity;
    for(var i= 0 ; i < arr.length ; i++)max = Math.max(max,arr[i]);
    for(var i = str.length+1 ; i <= str.length+k ; i++)t += max*i;
    print(t);
}

var str = readline();
var k = parseInt(readline());
var arr = readline().split(" ");
for(var i = 0 ; i < arr.length ; i++)arr[i] = parseInt(arr[i]);

main(str,k,arr);

var a = 'a'.charCodeAt(0);

;(function () {
	var str = readline(), l = str.length;
	var k = +readline();
	var alphabet = readline().split(' ').map(Number);
	var maxPrice = Math.max.apply(null, alphabet);

	var sum = ((function () {
		for (var i = 0, ret = 0; i < l; i++)
			ret += alphabet[str.charCodeAt(i) - a] * (i + 1);
		return ret;
	})()) + maxPrice * ((function () {
		for (var i = 0, ret = 0; i < k; i++)
			ret += l + i + 1;
		return ret;
	})());

	print(sum);

}).call(this);

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

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

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

function main() {
	var s = trim(readline()),
		k = parseInt(readline()),
		values = tokenizeIntegers(readline()),
		maxValue = 0,
		ch2value = {},
		total = 0;
	for (var i = 0; i < 26; ++i) {
		ch2value[String.fromCharCode(97+i)] = values[i];
		maxValue = Math.max(maxValue, values[i]);
	}
	for (var i = 0; i < s.length; ++i) {
		total += (i+1)*ch2value[s.charAt(i)];
	}
	for (var i = 0; i < k; ++i) {
		total += (s.length+i+1)*maxValue;
	}
	print(total);
}

main();