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

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

let count = -1
let inputArr = []

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

function solve(n) {
    let r = n.toString().length
    let copy = n
    let temp = 0
    for (let i = 0; i < r - 1; i++) copy = Math.floor(copy / 10)
    if (n > 9) {
        for (let i = 0; i < r; i++) {
            temp += copy * (10 ** i)
        }
        if (n < temp) --copy
    }
    console.log((r - 1) * 9 + copy)

}

function main() {
    for (let i = 0; i < inputArr.length; i++) solve(Number(inputArr[i]))
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var s = readline();
  var len = s.length;
  var n = parseInt(s);

  var p = 0;
  var count = 0;
  for (var i = 0; i < len; i++) {
    p = p * 10 + 1;
    for (var j = 1; j <= 9; j++)
      if (p * j >= 1 && p * j <= n)
        count++;
  }
  print(count);
}

var testcases = readline();
var count;

for(var k = 0 ; k < testcases ; k++) {
    var number = readline();
    count = 0;
    for (var i = 1; i <= number; i = i * 10 + 1) {
        for (var j = 1; j <= 9; j++) {
            if(i * j <= number) count++;
        }
    }
    print(count);
}

// 1520 B - Ordinary Numbers

// number of test case
var numTests = parseInt( readline() );

for (var numTest = 0; numTest < numTests; numTest++) {

    // input data
    var num = parseInt( readline() );

    // calculate number
    var n1 = 9 * ( num.toString().length -  1 );
    var n2 = num;
    var n3 = '1'.repeat( num.toString().length );

    var output = n1 + ( parseInt ( n2 / n3 ) );
    print( output );

}

t = parseInt(readline()) ;
while (t--) {
	n= readline();
	ans =  9 * ((n.length - 1 )) ;
	x  = parseInt(n);
	ds = "1" ;
	for (i = 1 ; i < n.length ; i ++ ) {
	    ds +='1' ;
	}
	new_x = parseInt(ds) ;
	for (i = 1 ; i <= 9 ; i++ ) {
	    if ((new_x * i )> x) break ;
	    ans ++ ;
	}
	print (ans);

}

var arr = [];
var tc = readline();
var sz;
function func(k, t) {
	var str = "";
	while (t--) str += k;
	return Number(str);
}
for (var i = 1; i <= 9; i++) {
	for (var j = 1; j <= 10; j++) {
		var str = func(i, j);
		arr.push(str);
	}
}
arr.sort(function (u, v) {
	return u - v;
});
sz=arr.length;
while (tc--) {
	var n = readline();
	var ans = 0;
	for (var i = 0; i < sz; i++) {
		if (arr[i] <= n) ans++;
		else break;
	}
	print(ans);
}

var t = +readline();

while (t--) {
  var n = +readline();
  var d = Math.floor(Math.log10(n)) + 1;
  var o = (d - 1) * 9; // ordinary numbers with less number of digits than n
  var firstOrdinary = (Math.pow(10, d) - 1) / 9;

  for(var i = 1; i < 10; i++) {
      if(n < firstOrdinary * i) {
          break;
      }
      o++;
  }
  print(o);
}

var numberOfCases = Number(readline());
for (var i = 0; i < numberOfCases; ++i) {
    processCase();
}

function processCase() {
    var limit = Number(readline());
    var limitStr = limit.toString();
    if (limit < 10) {
        return print(limit);
    }

    var numberOfFullDigits = limitStr.length - 1;

    var firstDigit = Number(limitStr[0]);
    var maxLesserBoringNumber = 0;
    for (var i = 0; i < limitStr.length; ++i) {
        maxLesserBoringNumber += firstDigit * Math.pow(10, i);
    }

    print(numberOfFullDigits * 9 + firstDigit - (limit >= maxLesserBoringNumber ? 0 : 1));
}

const t=parseInt(readline());

for(var j=0;j<t;j++)
{
    var n=parseInt(readline());
    var s=n.toString();
    var l=s.length;

    var ans=0;
    ans+=(l-1)*9;

    var fn=parseInt(s[0]);
    ans+=(fn-1);

    var ns='';

    for(var i=0;i<l;i++)
    {
        ns+=s[0];
    }

    var nn=parseInt(ns);
    //print(ns);

    if(nn<=n)
    {
        ans++;
    }

    print(ans);

}

var T = parseInt(readline());
while (T--) {
    var c = 0;
    var n = parseInt(readline());
	for (var x = 1; x <= n; x *= 10, ++x)
    	for (var y = x, z = 0; y <= n && z < 9; y += x, ++z)
    			++c;
    print(c); }

const readline = require('readline');

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

let input = [];

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

    if (input.length === +input[0] + 1) {
        rl.close();
        input.shift();
        main();
    }
});

function main() {
    input.forEach(item => ordinaryNumbers(item));
}

function ordinaryNumbers(item) {
    if (item.length === 1) {
        console.log(item);

    } else {
        let digits = item.length,
            ordinaryNumbers = 9 * (digits - 1),
            firstChar = item.charAt(0),
            ordinaryNumberWithFirstChar = firstChar.repeat(digits);

        ordinaryNumbers += Math.floor(+item / Math.pow(10, digits - 1)) - 1;

        if (item >= ordinaryNumberWithFirstChar) {
            console.log(++ordinaryNumbers);
        } else {
            console.log(ordinaryNumbers);
        }
    }
}

const readline = require('readline');

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

let input = [];

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

    if (input.length === +input[0] + 1) {
        rl.close();
        input.shift();
        main();
    }
});

function main() {
    input.forEach(item => ordinaryNumbers(item));
}

function ordinaryNumbers(item) {
    if (item.length === 1) {
        console.log(item);

    } else {
        let digits = item.length,
            ordinaryNumbers = 9 * (digits - 1),
            firstChar = item.charAt(0);

        ordinaryNumbers += Math.floor(+item / Math.pow(10, digits - 1));

        ordinaryNumberWithFirstChar = firstChar.repeat(digits);

        if (item >= ordinaryNumberWithFirstChar) {
            console.log(ordinaryNumbers);
        } else {
            console.log(--ordinaryNumbers);
        }
    }
}

const _mergeArrays = (a, b) => {
    const c = []

    while (a.length && b.length) {
      c.push(a[0] > b[0] ? b.shift() : a.shift())
    }

    //if we still have values, let's add them at the end of `c`
    while (a.length) {
      c.push(a.shift())
    }
    while (b.length) {
      c.push(b.shift())
    }

    return c
  }

  const mergeSort = (a) => {
    if (a.length < 2) return a
    const middle = Math.floor(a.length / 2)
    const a_l = a.slice(0, middle)
    const a_r = a.slice(middle, a.length)
    const sorted_l = mergeSort(a_l)
    const sorted_r = mergeSort(a_r)
    return _mergeArrays(sorted_l, sorted_r)
  }

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*/
    for(j =1 ; j<= lines[0]; j++){
        var a = lines[j]
        var b = 1
        var c = 0
        var d = 0
        for(l = 10; l <= a; l*=10){
            d = l - 1
            c += d /b
            b = b * 10 + 1
        }
        c += a/b
        console.log(Math.floor(c))
    }

});

//2 - 2 % 0 + 1
//2 - 2 % 0 - (0 - 1)

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    for(j = 1; j <= lines[0]; j++){
        var a = lines[j]
        var b = 1
        var c = 0
        var d = 0
        for(l = 10; l <= a; l*=10){
            d = l - 1
            c += d /b
            b = b * 10 + 1
        }
        c += a/ b
        console.log(Math.floor(c))
    }

});

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

let c = 0;
const answers = [];

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

  const n = Number(d);
  const len = d.length;
  let ans = Math.max(0, (len - 1) * 9);
  let inc = Number(String(1).repeat(len));

  for (let i = inc; i <= n; i += inc) {
    ans++;
  }

  answers.push(ans);

  // let answers = [];
  // let ans = 0;

  // for (let i = 1; i <= Number(d); i++) {
  //   if (new Set(String(i)).size === 1) {
  //     answers.push(i);
  //     ans++;
  //   }
  // }

  // console.log({ answers });
  // console.log({ ans });
  c++;
});

rl.on("close", () => {
  console.log(answers.join("\n"));
});

'use-strict'

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

let data = '';
let currentLine = 0;

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

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

        let testCases = parseInt(readLine());
        while(testCases--)
        {
            const n = parseInt(readLine());
            //const s = readLine();
            b(n);
        }

});

function print(c){
    return console.log(c);
}

function get_ints() {
    return readLine().split(' ').map(Number)
}

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

function a(n,s)
{
    let last = '';
        let solved = '';
        for(let i = 0 ; i < n; i++)
        {
            if(s[i] !== last && solved.includes(s[i]))
            {
                return console.log('NO');
            }
            solved += s[i];
            last = s[i];
        }
        return print('YES');
}

function b(n)
{
    // usiming every decimal add 9
    let d = n.toString()[0];
    let k = n.toString().length;
    let max = 0;
    for(let pw = 1; pw <= n; pw = pw * 10 + 1)
    {
        for(let d = 1; d <= 9; d++)
        {
            if(pw * d <= n)
            {
                max++
            }
        }
    }

    return print(max)

}

module.exports = b;

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let input = '';
process.stdin.on('data', inputStdin => {
    input += inputStdin;
});
process.stdin.on('end', _ => {
    main(input);
});

function main(input) {
    const args = input.split('\n');
    var v = [];
    var n = 1;
    for (var j = 1; j <= 9; j++) {
        for (var i = 1; i <= 9; i++) {
            v.push(i * n);
        }
        n *= 10;
        n += 1;
    }
    v.push(10 ** 9 + 1);
    const t = parseInt(args[0], 10);
    for (var i = 1; i <= t; i++) {
        const c = parseInt(args[i], 10);
        var j = 0;
        while (v[j] <= c) {
            j++;
        }
        console.log(j);
    }
}

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

function amountOfSameNums(inp){
  if(inp < 10) return inp

  let digits = String(inp).length,
      counter = (digits-1) * 9,
      divisor = '1'.repeat(digits);

  return counter + Math.floor(inp / divisor)

  //+ (Number( String(inp)[digits-1] ) || '');

  // for(var i=1, counter=0; i<=inp; i++){

  //   // count amount of digits 10-100  11 22 33 44 55 66 77 88 99
  //   100-1000 (3-4 symbols difference) 4-5 difference same 9 numbers to check
  //   11 22 33 44 55 66 77 88 99
  //   111 222 333 444 555 666 777 888 999
  //   if([...String(i)]
  //     ++counter
  //   }
}

rl.on('line', (input) => {
  if(initialized){ console.log( amountOfSameNums(input) ) }
  else initialized = true
});

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rl();

		const D = n.length;

		let flg = 0;
		for (const d of n) {
			if (d == n[0]) {
				continue;
			}
			if (d > n[0]) {
				break;
			}
			if (d < n[0]) {
				flg = 1;
				break;
			}
		}

		const ans = 9 * (D - 1) + Number(n[0]) - flg;

		console.log(ans)
	}
}

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(var j = 1; j <= n; j++){
        var a = lines[j];
        var b = 1;
        var r = 0;
        var t = 0;
        for(l = 10; l <= Number(a); l*=10){
            t = l-1;
            r += t/b;
            b = b*10+1;
        }
        r += Number(a)/b;
        console.log(Math.floor(r));
    }

});

const readline = require('readline');

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

function amountOfSameNums(inp) {
    if (inp < 10) return inp;

    const digits = String(inp).length;
    const counter = (digits - 1) * 9;
    const divisor = '1'.repeat(digits);

    return counter + Math.floor(inp / divisor);
}

rl.on('line', (input) => {
    if (initialized) { console.log(amountOfSameNums(input)); } else initialized = true;
});

const isNum = (num) => {
	if (num < 10)
		return true;

	const str = `${num}`.split('');

	const set = new Set();
	for (let i=0; i<str.length; i++) {
		set.add(str[i]);
	}

	return set.size === 1;
}

const solve = (line) => {
	const n = +line;

	let counter = 0;
	for (let i=1; i<10; i++) {
		let num = `${i}`;
		while (+num <= n) {
			counter++;
			num += `${i}`;
		}
	}

	return counter;
}

let input = '';
process.stdin.on('data', str => input += str)
process.stdin.on('end', () => {
	const [n, ...lines] = input.trim().split('\n')
		.map(l => l.trim());

	for (let i=0; i<n; i++) {
		console.log(solve(lines[i]))
	}
})

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

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

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

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

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

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

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

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

// ********** actual Code Starts from here **********
function buildNumber(n,digit){
    if(n==1){
        return parseInt(digit);
    }
    let ans = 0;
    while(n--){
        ans = ans*10+ digit;
    }

    return ans;
}

function solve() {

    let t = readSingleInt();
    let firstDigit ,ans ,targetNumber ,inputNumber,included;
    while(t--)
    {
        ans = 0;
        included = -1;
        let n =readLine();
        firstDigit = parseInt(n[0]);
        targetNumber = buildNumber(n.length,firstDigit);
        inputNumber = parseInt(n);
        if(inputNumber>=targetNumber){
            included = 0;
        }
        ans = (n.length-1) * 9 + (firstDigit) + included;
        console.log(ans);

    }

}

/**
 * Bismillahir Rahmanir Rahim
 * This code has been taken from: https://codeforces.com/blog/entry/69610
 */
 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++];
 }

 /****** BELOW HERE START WRITING YOUR CODE IN main() FUNCTION   ***************************************/
 /**
  * Use "readLine()" function for input, which will return a string consisting the entire line, so accordingly split the string
  * when required.
  *
  * I am using console.log() to output
  */
//  function main() {
//      let t = readLine();
//      t = parseInt(t);
//      console.log("mai yahan aaya")
//      while(t--) {
//          let line = readLine();
//          line = line.split(" ");
//          let n = parseInt(line[0]);
//          let m = parseInt(line[1]);
//          if(n === 1) {
//              console.log("0");
//          } else if (n === 2) {
//              console.log(m);
//          } else {
//              console.log(2*m);
//          }
//      }
//  }

function main() {

	let t = parseInt(readLine());
	// t = parseInt(t);
	while(t--) {
		let n = readLine();
		n = parseInt(n);
		//let s = readLine().split(" ").map(item=>parseInt(item));
		solve(n);

	}
    // console.log(t);
}

function solve(n) {
	let sol = 0 ;
	for (let i = 1; i <= 9; i++) {
		let j = i;
		while (j <= n) {
			sol++;
			j = j*10 + i;
		}
	}
	console.log(sol);
}

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

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	let t = nl.num();
    let ans = [];
    for(let i = 0; i < t; i++){
        ans.push(nl.num());
    }
    let numz = (n) => {
        let t = n;
        let cnt = 0;
        while(t >= 10){
            t /= 10;
            cnt++;
        }

        t = Math.trunc(t);
        let c = t;
        for(let i = 0; i < cnt; i++)  {
            c *= 10;
            c += t;
        }
        return cnt * 9  + ((c > n)?t - 1:t);
    }

	console.log(ans.map(numz).join("\n"));

};

process.stdin.on('end', sol);

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
let input = [];
rl.on('line', line => {
    input.push(line);
})
rl.on('close', line => {
    var t = Number(input[0]);
    for (var a = 1; a < input.length; a++) {
        var n = Number(input[a]);
        var sum = 0;
        var count = 0;
        for (var i = 0; i <= 8; i++) {
            sum += 10 ** i;
            for (var j = 1; j <= 9; j++) {
                if (j * sum <= n) {
                    count++;
                }
            }
        }
        console.log(count);
    }
})

//////////////////////  Nodejs  Problem Solving /////////////////
/////////////////////* @author  Nawab Khairuzzaman Mohammad Kibria *////////

process.stdin.resume();
process.stdin.setEncoding("utf-8");
let currentLine = 0;
let inputString = "";
process.stdin.on("data", (raw_data) => {
  inputString += raw_data;
});

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

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

///////////////////////// END BASIC IO STREAM TEMPLATE //////////////////////

function main() {
  let t = readLine(Number);
  while (t--) {
    let n = readLine(Number);

    if (n < 10) {
      console.log(n);
    } else {
      let y;
      let x = n.toString().split("").map(Number);
      y = x[0];

      for (let i = 1; i < x.length; i++) {
        if (x[0] > x[i]) {
          y -= 1;
          break;
        }

        if (x[0] < x[i]) {
          break;
        }
      }

      console.log(x.length * 9 - (9 - y));
    }
  }
}

function findNumberOfDigts(N) {
    let count = 0;
    while (N) {
        count += 1;
        N = Math.floor(N / 10);
    }
    return count;
}

function solve(N) {
    const digits = findNumberOfDigts(N);
    let ans = (digits - 1) * 9;
    let b = 0;
    for (let i = 0; i < digits; i++) {
        b += Math.pow(10, i);
    }
    ans += Math.floor(N / b);
    return ans;
}

function processData(input) {
    //Enter your code here
    input = input.split('\n');
    const T = Number(input[0].trim());
    let i = 1;
    for (let t = 0; t < T; t++) {
        const N = Number(input[i++].trim());
        const ans = solve(N);
        console.log(ans);
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
    processData(_input);
});

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

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

function main() {
	let t = +readLine();
	while (t--) {
		const n = readLine();
		if (+n <= 9) console.log(n);
		else {
			let count = 9;
			const firstChar = n[0];
			const len = n.length;
			if (+n >= +firstChar.repeat(len)) count++;
			count += +firstChar - 1;
			count += (len - 2) * 9;
			console.log(count);
		}
	}
}

'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++];
}
/**
6
1
2
3
4
5
100

**/

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

function lcm(a, b) {
    return (a / gcd(a, b) * b);
}

function main() {
    let n = Number(readline());

    for(let r=0;r<n;r++) {
        solve();
    }

}

function solve() {
    let n = Number(readline());

    let d = Math.log(n) + 1;
    let temp = 0;

    let ans = 0;

    for(let i=0;i<d;i++) {
        temp = temp * 10 + 1;
            for(let j=1;j<=9;j++) {
                if((temp * j) <= n) {
                    ans++;
                } else {
                    console.log(ans);
                    return;
                }
            }
    }

    console.log(ans);

}

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

//Don't have to see. end------------------------------------------

function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var output = 0;
		var V = 1;
		var keta = 1;
		while(V <= N){
			output++;
			if(V % 10 != 9){
				V += (Math.pow(10, keta) - 1) / 9;
			}else{
				V = (Math.pow(10, keta + 1) - 1) / 9;
				keta++;
			}
		}
		myout(output);
	}
}

var hotel = readline();

while(hotel--){
    var n = parseInt(readline());
    var cnt = 0;
    var noOfDigits = n.toString().length;
    for(var i=1; i<=noOfDigits; i++){
       var val = parseInt('1'.repeat(i));
       for(var j=1; j<=9; j++){
           var res = val*j;
           if(res >= 1 && res <= n) {
               cnt++;
           }
       }
    }
    print(cnt);
}

        var limit = parseInt(readline());
        for (var i = 0; i < limit; i++)
        {
         var value = parseInt(readline());
         var count = 0;
         for (var j = 1; j < 10; j++)
         {
          var current = j;
          while (current <= value)
          {
           count++;
           current = (current * 10) + j;
          }
         }
         print(count);
        }

var T = parseInt(readline());
var values = [];
for(var i = 1; i <= 9; i++) {
    var ans = 0;
    while(ans < 1000000000) {
        ans = (ans * 10) + i;
        values.push(ans);
    }
}
while(T--) {
    var N = parseInt(readline());
    var ans = 0;
    for(var value of values) {
        if(value <= N) {
            ans++;
        }
    }
    print(ans);
}

var hotel = readline();

while(hotel--){
    var n = parseInt(readline());
    var cnt = 0;
    if(n < 10) {
        print(n)
    }
    else {
        for(var i=10; i <= n; i++){
            var noOfDigits = i.toString().length;
            var divisor = '1'.repeat(noOfDigits);
            if(i%parseInt(divisor)===0){
                cnt++;
            }
        }
        print(cnt);
    }
}

var testcases = readline();
var count;

for(var i = 0 ; i < testcases ; i++) {
    var number = readline();
    if(number < 10){
        count = number;
    }
    if(number > 10){
        count = 9;
        for (var j = 10; j <= number; j++) {
            var flag = true;
            j = j.toString();
            for (var i = 1; i < j.length; i++) {
                if(j[i - 1] !== j[i]){
                    flag = false;
                    break;
                }
            }
            if(flag) count++;
        }
    }
    print(i);
}

var testcases = readline();
var count;

for(var i = 0 ; i < testcases ; i++) {
    var number = readline();
    if(number < 10){
        count = number;
    }
    if(number > 10){
        count = 9;
        for (var j = 10; j <= number; j++) {
            var flag = true;
            j = j.toString();
            for (var i = 1; i < j.length; i++) {
                if(j[i - 1] !== j[i]){
                    flag = false;
                    break;
                }
            }
            if(flag) count++;
        }
    }
    print(count);
}

var T = parseInt(readline());
var values = [];
for(var i = 1; i <= 9; i++) {
    var ans = 0;
    while(ans < 1000000) {
        ans = (ans * 10) + i;
        values.push(ans);
    }
}
while(T--) {
    var N = parseInt(readline());
    var ans = 0;
    for(var value of values) {
        if(value <= N) {
            ans++;
        }
    }
    print(ans);
}

const t = parseInt(readline());

for (var _ = 0; _ < t; _++) {
  var s = readline();
  var n = parseInt(s);
  var len = s.length - 1;
  var p = Math.pow(10, len);
  print(n % (p === 1? 10: p) + 9 * len);
}

const readline = require('readline');

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

let input = [];

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

    if (input.length === +input[0] + 1) {
        rl.close();
        input.shift();
        main();
    }
});

function main() {
    input.forEach(item => ordinaryNumbers(item));
}

function ordinaryNumbers(item) {
    let ordinaryNumbers = 1;
    let firstChar = item.charAt(0);

    for (let i = 1; i < item.length; ++i) {
        if (firstChar === item.charAt(i)) {
            ordinaryNumbers++;
        }
    }

    console.log(ordinaryNumbers);
}

const readline = require('readline');

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

let input = [];

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

    if (input.length === +input[0] + 1) {
        rl.close();
        input.shift();
        main();
    }
});

function main() {
    input.forEach(item => console.log(item));
}

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*/
    var s = 1
    var answer = 0
    for(j = 1; j <= lines[0]; j ++){
        var a = lines[j]
        for(k = 1; k < a; k++){
            var b = a.split('').sort(function(a, b){return a - b});
           for(c = 0 ; c < b.length; c++){
               if(b[c] == b[c - 1]){
                   answer++
               }else if(b[c + 1] === '') {
                   answer++
               }
           }
           s++
        }
        console.log(answer)
    }
});

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 [firstNumber, ...rest] = d;
  let ans = (d.length - 1) * 9;

  if (ans === 0) {
    console.log(d);
  } else {
    ans += Number(firstNumber) - 1;
    console.log(ans);
  }

  // let answers = [];
  // let ans = 0;

  // for (let i = 1; i <= Number(d); i++) {
  //   if (new Set(String(i)).size === 1) {
  //     answers.push(i);
  //     ans++;
  //   }
  // }

  // console.log({ answers });
  // console.log(ans);
  c++;
});

rl.on("close", () => {});

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 [firstNumber, ...rest] = d;
  let ans = (d.length - 1) * 9;

  if (ans === 0) {
    console.log(d);
  } else {
    ans += Number(firstNumber) - 1;
  }

  console.log(ans);

  // let answers = [];
  // let ans = 0;

  // for (let i = 1; i <= Number(d); i++) {
  //   if (new Set(String(i)).size === 1) {
  //     answers.push(i);
  //     ans++;
  //   }
  // }

  // console.log({ answers });
  // console.log(ans);
  c++;
});

rl.on("close", () => {});

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

  let ans = (d.length - 1) * 9;

  if (ans === 0) {
    console.log(d);
  } else {
    console.log(ans);
  }

  c++;
});

rl.on("close", () => {});

'use-strict'

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

let data = '';
let currentLine = 0;

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

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

        let testCases = parseInt(readLine());
        while(testCases--)
        {
            const n = parseInt(readLine());
            //const s = readLine();
            b(n);
        }

});

function print(c){
    return console.log(c);
}

function get_ints() {
    return readLine().split(' ').map(Number)
}

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

function a(n,s)
{
    let last = '';
        let solved = '';
        for(let i = 0 ; i < n; i++)
        {
            if(s[i] !== last && solved.includes(s[i]))
            {
                return console.log('NO');
            }
            solved += s[i];
            last = s[i];
        }
        return print('YES');
}

function b(n)
{
    // usiming every decimal add 9
    let s = n.toString();
    let max = s.length * 9 - (9 - parseInt(s[0]));
    if(s[1] < s[0]) max--;
    return print(max)
}

module.exports = b;

'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let input = '';
process.stdin.on('data', inputStdin => {
    input += inputStdin;
});
process.stdin.on('end', _ => {
    main(input);
});

function main(input) {
    const args = input.split('\n');
    var v = [];
    var n = 1;
    for (var j = 1; j <= 9; j++) {
        for (var i = 1; i <= 9; i++) {
            v.push(i * n);
        }
        n *= 10;
        n += 1;
    }
    v.push(10 ** 9);
    const t = parseInt(args[0], 10);
    for (var i = 1; i <= t; i++) {
        const c = parseInt(args[i], 10);
        var j = 0;
        while (v[j] <= c) {
            j++;
        }
        console.log(j);
    }
}

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

function amountOfSameNums(inp){
  if(inp < 10) return inp

  let digits = String(inp).length,
      counter = (digits-1) * 9 + (Number( String(inp)[digits-1] ) || '');
  // for(var i=1, counter=0; i<=inp; i++){

  //   // count amount of digits 10-100  11 22 33 44 55 66 77 88 99
  //   100-1000 (3-4 symbols difference) 4-5 difference same 9 numbers to check
  //   11 22 33 44 55 66 77 88 99
  //   111 222 333 444 555 666 777 888 999
  //   if([...String(i)]
  //     ++counter
  //   }

  return counter
}

rl.on('line', (input) => {
  if(initialized){ console.log( amountOfSameNums(input) ) }
  else initialized = true
});

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

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

function main () {
	let T = rn();
	while (T--) {
		const n = rl();

		const D = n.length;

		const dmin = Math.min(...n.split(''));

		const ans = 9 * (D - 1) + Number(n[0]) - (dmin == n[0] ? 0 : 1);

		console.log(ans)
	}
}

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(var j = 1; j <= n; j++){
        var a = lines[j];
        var b = 1;
        var r = 0;
        var t = 0;
        for(l = 10; l <= a; l*=10){
            t = l-1;
            r += t/b;
            b *= 10+1;
        }
        r += a/b;
        console.log(Math.floor(r));
    }

});

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

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

let count = -1
let inputArr = []

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

function solve(n) {
    let count = 9
    if (n < 10) console.log(n)
    else console.log(9 + Math.floor(n / 11))

}

function main() {
    for (let i = 0; i < inputArr.length; i++) solve(Number(inputArr[i]))
}

const isNum = (num) => {
	if (num < 10)
		return true;

	const str = `${num}`.split('');

	const set = new Set();
	for (let i=0; i<str.length; i++) {
		set.add(str[i]);
	}

	return set.size === 1;
}

const solve = (line) => {
	const n = +line;

	let counter = 0;
	for (let i=1; i<10; i++) {
		let num = `${i}`;
		while (+num <= n) {
			counter++;
			num += `${i}`;
		}
	}

	return counter;
}

let input = '';
process.stdin.on('data', str => input += str)
process.stdin.on('end', () => {
	const lines = input.trim().split('\n').slice(1)
		.map(l => l.trim());

	console.time('time')
	for (let i=0; i<lines.length; i++) {
		console.log(solve(lines[i]))
	}
	console.timeEnd('time');
})


let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    var a = 0;
    for(i = 1; i <= t * 3; i++){
        if(i % 3 == 1){
            n = lines[i];
        }else if(i % 3 == 2){
            a = lines[i].split(' ').map(Number);
        }else{
            var b = lines[i].split(' ').map(Number);
            var ans = 0;
            for(j = 0; j < n; j++){
                if(b[j] > a[j]){
                    var temp = b[j];
                    b[j] = a[j];
                    a[j] = temp;
                }
            }
            a.sort(function(a, b){return b - a});
            b.sort(function(a, b){return b - a});
            console.log(a[0] * b[0]);
        }
    }
});

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

var T = readline();
for(var q=1;q<=T;q++) {
            var g = readline();
            var a = readline().split(" ").map(w => parseInt(w))
            var b = readline().split(" ").map(w => parseInt(w))
            var max = []
            var min = []
            for(var i=0;i<a.length;i++) {
                max[i]=Math.max(a[i],b[i])
                min[i]=Math.min(a[i],b[i])
            }
            var mx = max[0]
            var mn = min[0]
            for(var i=0;i<a.length;i++) {
                mx=Math.max(mx,max[i])
                mn=Math.max(mn,min[i])
            }
            console.log(mx*mn)
}

let input = "";
process.stdin.on("data", (chunk) => {
  input += chunk;
});
process.stdin.on("end", () => {
  let lines = input.trim().split("\n");
  let t = parseInt(lines[0]);
  let i = 1;
  while (t--) {
    let n = parseInt(lines[i++]);
    let a = lines[i++]
      .trim()
      .split(" ")
      .map((element) => parseInt(element));
    let b = lines[i++]
      .trim()
      .split(" ")
      .map((element) => parseInt(element));
    let index = a.indexOf(Math.max(...a));
    while (a[index] > b[index]) {
      let temp = a[index];
      a[index] = b[index];
      b[index] = temp;
      index = a.indexOf(Math.max(...a));
    }
    index = b.indexOf(Math.max(...b));
    while (b[index] > a[index]) {
      let temp = a[index];
      a[index] = b[index];
      b[index] = temp;
      index = b.indexOf(Math.max(...b));
    }
    console.log(Math.max(...a) * Math.max(...b));
  }
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

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

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

        for (let i = 0; i < n; i++) {
            if (arr[i] > brr[i]) {
                [arr[i], brr[i]] = [brr[i], arr[i]];
            }
        }

        let f = Math.max(...arr);
        let s = Math.max(...brr);

        output(f * s);
    }
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var alist = nextIntArray(N);
		var blist = nextIntArray(N);
		for(var i = 0; i < N; i++){
			if(alist[i] < blist[i]){
				var tmp = alist[i];
				alist[i] = blist[i];
				blist[i] = tmp;
			}
		}
		alist.sort(function(a,b){
			return b - a;
		});
		blist.sort(function(a,b){
			return b - a;
		});
		myout(alist[0] * blist[0]);
	}
}

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

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let j = 0 ; j < t; j++) {
		let n = nl.num();
		let a = nl.nums();
		let b = nl.nums();
		for(let i = 0; i < n; i++){
			if (a[i] > b[i]) {
				[a[i], b[i]] = [b[i], a[i]];
			}
		}
		ans.push(Math.max(...a) * Math.max(...b));
	}
	console.log(ans.join('\n'));
};

process.stdin.on('end', sol);

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

let inputString = '';

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

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

    main(inputString);
});

function log(message){
    if(process.env.NODE_ENV === "debug"){
        console.log(message);
    }
}

// function main(fileContents) {//input lines as an array
//     // console.log(fileContents);
//     fileContents.splice(0,1);
//     for(let i = 0; i < fileContents.length; i+=3){
//         const line1 = fileContents[i+1].split(" ")
//         const line2 = fileContents[i+2].split(" ")
//         // console.log("line1: ",line1,"line2: ",line2)
//         let max = line1[0]*line2[0];
//
//         for(let x = 0; x < line1.length; x++){
//             max= Math.max(max,line1[x]*line2[x])
//         }
//
//         console.log(max)
//     }
// }

function main(fileContents) {//input lines as an array
    // console.log(fileContents);
    fileContents.splice(0,1);
    for(let i = 0; i < fileContents.length; i+=3){
        const small = fileContents[i+1].split(" ")
        const big = fileContents[i+2].split(" ")

        for(let x = 0; x < small.length; x++){
            const smallBuff = Math.min(small[x],big[x]);
            const bigBuff = Math.max(small[x],big[x]);

            small[x] = smallBuff;
            big[x] = bigBuff;
        }

        // console.log("small",small,"big",big)
        console.log(Math.max(...small)*Math.max(...big))
    }
}

// your code goes here
var total = parseInt(readline());

for(var i = 0; i < total; i++) {
	var count = parseInt(readline());
	var a = readline().split(" ").map(x => parseInt(x));
	var b = readline().split(" ").map(x => parseInt(x));

	var maxa = 1;
	var maxb = 1;
	for(var j = 0; j < count; j++) {
		if(a[j] < b[j]) {
			var temp = a[j];
			a[j] = b[j];
			b[j] = temp;
		}

		maxa = Math.max(maxa, a[j]);
		maxb = Math.max(maxb, b[j]);
	}

	print(maxa*maxb);
}

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

var T = readline();
for(var q=1;q<=T;q++) {
            var g = readline();
            var a = readline().split(" ").map(w => parseInt(w))
            var b = readline().split(" ").map(w => parseInt(w))
            a.sort(function(ar,br) { return ar-br })
            b.sort(function(ar,br) { return ar-br })
            var g = 'b';
            var ans = a[a.length-1]*b[b.length-1]
            for(var i=0;i<a.length;i++) {
            	if(a[i]>b[i]) {
            		g='a';
            		break;
            	}
            	else if(b[i]>a[i]) {
            		g='b';
            		break;
            	}
            }
            if(g == 'b') {
            	var maxb = b[0]
            	for(var i=0;i<a.length;i++) {
            		if(a[i] > b[0]) {
            			break;
            		} else {
            			maxb = Math.max(b[i], maxb);
            		}
            	}
                ans = Math.min(ans, a[a.length-1]*maxb)
            }
            else if(g =='a') {
            	var maxa = a[0]
            	for(var i=0;i<b.length;i++) {
            		if(b[i] <= a[0]) {
            			maxa = Math.max(maxa, a[i])
            		} else {
            		    break;
            		}
            	}
            	ans = Math.min(ans, b[b.length-1]*maxa)
            }
            console.log(ans)
}

let input = "";
process.stdin.on("data", (chunk) => {
  input += chunk;
});
process.stdin.on("end", () => {
  let lines = input.trim().split("\n");
  let t = parseInt(lines[0]);
  let i = 1;
  while (t--) {
    let n = parseInt(lines[i++]);
    let a = lines[i++]
      .trim()
      .split(" ")
      .map((element) => parseInt(element));
    let b = lines[i++]
      .trim()
      .split(" ")
      .map((element) => parseInt(element));
    if (Math.max(...a) > Math.max(...b)) {
      let index = b.indexOf(Math.max(...b));
      while (a[index] < b[index]) {
        let temp = a[index];
        a[index] = b[index];
        b[index] = temp;
        index = b.indexOf(Math.max(...b));
      }
    } else {
      let index = a.indexOf(Math.max(...a));
      while (a[index] > b[index]) {
        let temp = a[index];
        a[index] = b[index];
        b[index] = temp;
        index = b.indexOf(Math.max(...b));
      }
    }
    console.log(Math.max(...a) * Math.max(...b));
  }
});


print(function(n, k) {

	var ans = [];
	for (var i = 0; i < n; i++) {
		ans[i] = [];
		for (var j = 0; j < n; j++)
			ans[i][j] = i === j ? k : 0;
	}

	return ans.map(function(v) {
		return v.join(' ');
	}).join('\n');

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

;(function () {

	print((function (n, k) {
		var ret = [], t = [];
		for (var i = 0; i < n; i++) t.push(0);
		t[0] = k; ret.push(t.join(' '));
		for (var i = 1; i < n; i++) {
			t[i - 1] = 0; t[i] = k;
			ret.push(t.join(' '));
		}
		return ret.join('\n');
	}).apply(this, readline().split(' ').map(Number)));

}).call(this);

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var n = integers[0], sum = integers[1];

	for (var r = 0; r < n; ++r) {
		var row = [];
		for (var c = 0; c < n; ++c) {
			row.push(c == r ? sum : 0);
		}
		print(row.join(" "));
	}
}

main();

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

rl.on('line', (d) => {
  const [n, k] = d.split(' ').map(Number);
  const matrix = new Array(n).fill(0).map(x => new Array(n).fill(0));
  let idx = 0;
  for (let i = 0; i < matrix.length; i++) {
    matrix[i][idx] = k;
    idx++;
  }

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

  c++;
});


let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i <= b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = a; i >= b; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function Arr(a, b, cb) {
  if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb(i + a));
  return Array(a - b + 1).fill(0).map((v, i) => cb ? cb(a - i) : a - i);
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

function max(a, b) {
  if (a > b) return a;
  return b;
}

(async () => {
  await inputPromise;
  let inp = input.split(/\D+/); r = 0;
  let t = +inp[r++];
  For(1, t, i => {
    let [n, s] = inp.slice(r, r = r + 2);
    let n0 = n;
    n = [...n];
    s = +s;
    let sum = eval(n.join('+'));
    while (sum > s) {
      let d = Arr(n.length - 1, 0).find(v => n[v] != 0);
      n[d--] = 0;
      while (1) {
        if (d < 0) {
          n = [1, ...n];
          break;
        }
        n[d]++;
        if (n[d] < 10) break;
        n[d--] = 0;
      }
      sum = eval(n.join('+'));
    }
    console.log(BigInt(n.join('')) - BigInt(n0) + '')
  })
})();

let input = '';
let inputResolve;
let inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => inputResolve());

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i <= b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = a; i >= b; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function Arr(a, b, cb) {
  if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb(i + a));
  return Array(a - b + 1).fill(0).map((v, i) => cb ? cb(a - i) : a - i);
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

function max(a, b) {
  if (a > b) return a;
  return b;
}

(async () => {
  await inputPromise;
  let inp = input.split(/\D+/); r = 0;
  let t = +inp[r++];
  For(1, t, i => {
    let [n, s] = inp.slice(r, r = r + 2);
    let n0 = n;
    n = [0, ...n].map(v => +v);
    s = +s;
    let sum = n.sum();
    while (sum > s) {
      let d = Arr(n.length - 1, 0).find(v => n[v] != 0);
      while (1) {
        n[d--] = 0;
        n[d]++;
        if (n[d] < 10) break;
      }
      sum = n.sum();
    }
    console.log(BigInt(n.join('')) - BigInt(n0) + '')
  })
})();


var pa = readline().split(' ').map(function(x){return parseInt(x);});
write(readline().split(' ').map(function(x){return parseInt(((parseInt(x) * pa[1]) % pa[2]) / pa[1]);}).join(' '));

var line = readline().trim().split(' ');

var n = line[0];
var a = line[1];
var b = line[2];

line = readline().trim().split(' ');

for (var i = 0; i < n; i++) {
    write(Math.floor(((line[i] * a) % b) / a));
    write(' ');
}

function trim(s) {
    return s.replace(/^\s+|\s+$/gm, '')
}
function tokenize(s) {
    return trim(s).split(/\s+/);
}
function integers(s) {
    var tokens = tokenize(s);
    for(var i=0; i<tokens.length; ++i) tokens[i]=parseInt(tokens[i]);
    return tokens;
}
function main() {
    var data = integers(readline())
    var n = data[0];
    var a = data[1];
    var b = data[2];
    var d = integers(readline());
    var res = [];
    for(var i=0; i<d.length; ++i) {
        var r = Math.floor(((d[i]*a)%b)/a);
        res.push(r);
    }
    print(res.join(" "));
}
main();

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) tokens[i]=parseInt(tokens[i]);
    return tokens;
}
function main() {
    var data=tokenizeIntegers(readline())
    var numDays=data[0], p=data[1], q=data[2];
    var tokensPerDay=tokenizeIntegers(readline());
    var results = [];
    for(var dayIndex=0; dayIndex<numDays; ++dayIndex) {
        var tokens=tokensPerDay[dayIndex];
        var result = Math.floor(((p*tokens)%q)/p);
        results.push(result);
    }
    print(results.join(" "));
}

main();

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) {
        tokens[i]=parseInt(tokens[i]);
    }
    return tokens;
}
function main() {
    var data = tokenizeIntegers(readline());
    var numDays = data[0], p = data[1], q=data[2];
    var tokensPerDay=tokenizeIntegers(readline());
    var results = [];
    for(var dayIndex = 0; dayIndex < numDays; ++dayIndex) {
        var tokens=tokensPerDay[dayIndex];
        var result = Math.floor(((p*tokens)%q)/p);
        results.push(result);
    }
    print(results.join(" "));
}
main();

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 data = tokenizeIntegers(readline());
	var numDays = data[0], p = data[1], q = data[2];

	var tokensPerDay = tokenizeIntegers(readline());
	var results = [];

	for (var dayIndex = 0; dayIndex < numDays; ++dayIndex) {
		var tokens = tokensPerDay[dayIndex];
		var result = Math.floor( ((p*tokens) % q) / p );
		results.push(result);
	}

	print(results.join(" "));
}

main();

function trim(s) {
    return s.replace(/^\s+|\s+$/gm, '')
}
function tokenize(s) {
    return trim(s).split(/\s+/);
}
function integers(s) {
    var tokens = tokenize(s);
    for(var i=0; i<tokens.length; ++i) tokens[i]=parseInt(tokens[i]);
    return tokens;
}
function main() {
    var data = integers(readline())
    var n = data[0];
    var a = data[1];
    var b = data[2];
    var d = integers(readline());
    var res = [];
    for(var i=0; i<d.length; ++i) {
        var r = Math.floor(d[i]*a%b/b);
        res.push(r);
    }
    print(res.join(" "));
}

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) {
          tokens[i]=parseInt(tokens[i]);
     }
     return tokens;
}
function main() {
    var data = tokenizeIntegers(readline())
    var n = data[0];
    var a = data[1];
    var b = data[2];
    var d = tokenizeIntegers(readline());
    var res = [];
    for(var i=0; i<d.length; ++i) {
        var r = Math.floor(d[i]*a%b/a);
        res.push(r);
    }
    print(res.join(" "));
}

function trim(s) {
    return s.replace(/^\s+|\s+$/gm, '')
}
function tokenize(s) {
    return trim(s).split(/\s+/);
}
function integers(s) {
    var tokens = tokenize(s);
    for(var i=0; i<tokens.length; ++i) tokens[i]=parseInt(tokens[i]);
    return tokens;
}
function main() {
    var data = integers(readline())
    var n = data[0];
    var a = data[1];
    var b = data[2];
    var d = integers(readline());
    var res = [];
    for(var i=0; i<d.length; ++i) {
        var r = Math.floor(d[i]*a%b/a);
        res.push(r);
    }
    print(res.join(" "));
}

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 data = tokenizeIntegers(readline());
	var numDays = data[0], p = data[1], q = data[2];

	var tokensPerDay = tokenizeIntegers(readline());
	var results = [];

	for (var dayIndex = 0; dayIndex < numDays; ++dayIndex) {
		var tokens = tokensPerDay[dayIndex];
		var result = (p*tokens) % q;
		results.push(result);
	}

	print(results.join(" "));
}

main();

var pa = readline().split(' ').map(function(x){return parseInt(x);});
write(readline().split(' ').map(function(x){return (parseInt(x) * pa[1]) % pa[2];}).join(' '));


Array(parseInt(readline())).fill().forEach(() => ((n, x, y) => print(['Alice', 'Bob'][(readline().split(' ').map(Number).reduce((a, b) => a ^ b, 0) ^ x ^ y) & 1]))(...readline().split(' ').map(Number)))

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

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

function main () {
	let T = rn();
	while (T--) {
		const [n, x, y] = rna();
		const a = rna();

		let k = x&1;
		for (let i = 0; i < n; i++) {
			k = k ^ a[i]&1;
		}

		console.log(k == (y&1) ? 'Alice' : 'Bob');
	}
}

Array(parseInt(readline())).fill().forEach(() => ((n, x, y) => print(['Alice', 'Bob'][(readline().split(' ').map(Number).reduce((a, b) => a ^ b, 0) ^ x ^ y) & 1]))(readline().split(' ').map(Number)))

Array(parseInt(readline())).fill().forEach(() => ((n, x, y) => ['Alice', 'Bob'][(readline().split(' ').map(Number).reduce((a, b) => a ^ b, 0) ^ x ^ y) & 1])(readline().split(' ').map(Number)))


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

let ls = [];

function solve() {
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let q = 0; q < t; q++){
        const n = parseInt(ls[l++]);
        const a = ls[l++].split(' ').map(it => parseInt(it));

        let lr = -1;
        for (let i = 0 ; i < n - 1; i++){
            if (a[i] == a[i + 1]){
                lr = i;
                break;
            }
        }

        let rr = -1;
        for (let i = n - 2; i >= 0; i--){
            if (a[i] == a[i + 1]){
                rr = i;
                break;
            }
        }

        if (lr == -1 || lr == rr|| a.length == 2){
            console.log(0);
        }
        else{
            console.log(Math.max(1, (rr - lr - 1)));
        }

    }
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, a) {
  let first = -1,
      last = -1;
  for (let i = 0; i < n; i++) {
    if (first === -1 && a[i] === a[i - 1]) {
      first = i;
    }
    if (a[i] === a[i + 1]) {
      last = i;
    }
  }
  if (first === -1 || last < first) {
    console.log(0);
  } else {
    console.log(Math.max(1, last - first));
  }
}

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

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

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

let ls = [];

function solve() {
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let q = 0; q < t; q++){
        const n = parseInt(ls[l++]);
        const a = ls[l++].split(' ').map(it => parseInt(it));

        let lr = -1;
        for (let i = 0 ; i < n - 1; i++){
            if (a[i] == a[i + 1]){
                lr = i;
                break;
            }
        }

        let rr = -1;
        for (let i = n - 2; i >= 0; i--){
            if (a[i] == a[i + 1]){
                rr = i;
                break;
            }
        }

        if (lr == -1 || a.length == 2){
            console.log(0);
        }
        else{
            console.log(Math.max(1, (rr - lr - 1)));
        }

    }
}

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

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

let ls = [];

function solve() {
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let q = 0; q < t; q++){
        const n = parseInt(ls[l++]);
        const a = ls[l++].split(' ').map(it => parseInt(it));

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

        let rr = -1;
        for (let i = n - 2; i >= 0; i--){
            if (a[i] == a[i + 1]){
                rr = i;
                break;
            }
        }

        if (lr == -1 || a.length == 2){
            console.log(0);
        }
        else if (lr == rr){
            console.log(1);
        }
        else{
            console.log(rr - lr);
        }
    }
}

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

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

let ls = [];

function solve() {
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let q = 0; q < t; q++){
        const n = parseInt(ls[l++]);
        const a = ls[l++].split(' ').map(it => parseInt(it));

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

        let rr = -1;
        for (let i = n - 2; i >= 0; i--){
            if (a[i] == a[i + 1]){
                rr = i;
                break;
            }
        }

        if (lr == -1){
            console.log(0);
        }
        else if (lr == rr){
            console.log(1);
        }
        else{
            console.log(rr - lr);
        }
    }
}

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

'use strict';

var readline = require('readline');

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

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

function solve(n, a, b) {
  const map = new Map();
  for (let i = 0; i < n; i++) {
    if (!map.has(a[i])) map.set(a[i], []);
    map.get(a[i]).push(i);
  }
  const flag = new Array(n).fill(0);
  new Array(n).fill(-1);
  const hasIndex = (i, j) => {
    let arr = map.get(i);
    while (arr.length && arr[arr.length - 1] > j) {
      arr.pop();
    }
    return !!arr.length;
  };
  for (let i = n - 1, j = n - 1; i >= 0; i--) {
    if (flag[j]) {
      if (!hasIndex(b[i], j - 1)) {
        console.log('NO');
        return;
      }
      while (flag[j] && b[i] !== a[j]) {
        j--;
      }
      if (a[j] !== b[i]) {
        console.log('NO');
        return;
      }
      if (flag[j]) {
        const k = map.get(b[i]).pop();
        flag[k] = 1;
      }
      j--;
    } else {
      if (a[j] !== b[i]) {
        if (!hasIndex(b[i], j - 1) || b[i] !== a[j + 1]) {
          console.log('NO');
          return;
        }
        const k = map.get(b[i]).pop();
        flag[k] = 1;
      } else {
        j--;
      }
    }
  }
  console.log('YES');
}

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

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


var path = readline().split('');

function counter (ch) {
    return function (total, x) {
        if (x === ch) {
            return total + 1;
        }
        return total;
        }
}

var pathL = path.reduce(counter('L'), 0);

var pathR = path.reduce(counter('R'), 0);

var pathU = path.reduce(counter('U'), 0);

var pathD = path.reduce(counter('D'), 0);

if (path.length % 2 !== 0) {
    print(-1);
} else if (pathL === pathR && pathU === pathD) {
    print(0);
} else {
    print((Math.abs(pathL - pathR) + Math.abs(pathU - pathD)) / 2);
}

var s = readline();
var solution = function ( s ) {
  if ( s.length%2 != 0 ) {
    return -1;
  }
  var step = function ( coord, c ) {
    switch ( c ) {
      case "L":
        --coord.x;
        break;
      case "R":
        ++coord.x;
        break;
      case "U":
        ++coord.y;
        break;
      case "D":
        --coord.y;
        break;
    }
    return coord;
  };
  var destination = [...s].reduce( ( coord, c ) => step( coord, c ), { x: 0, y: 0 } );
  var manhattanDistance = Math.abs( destination.x ) + Math.abs( destination.y );
  return manhattanDistance / 2;
};
print( solution( s ) );

var path = readline().split('');

function counter (ch) {
    return function (total, x) {
        if (x === 'L') {
            return total + 1;
        }
        return total;
        }
}

var pathL = path.reduce(counter('L'), 0);

var pathR = path.reduce(counter('R'), 0);

var pathU = path.reduce(counter('U'), 0);

var pathD = path.reduce(counter('D'), 0);

if (path.length % 2 !== 0) {
    print(-1);
} else if (pathL === pathR && pathU === pathD) {
    print(0);
} else {
    print(Math.abs(pathL - pathR) / 2 + Math.abs(pathU - pathD) / 2);
}

var path = readline().split('');

function counter (ch) {
    return function (total, x) {
        if (x === 'L') {
            return total + 1;
        }
        return total;
        }
}

var pathL = path.reduce(counter('L'), 0);

var pathR = path.reduce(counter('R'), 0);

var pathU = path.reduce(counter('U'), 0);

var pathD = path.reduce(counter('D'), 0);

if (path.length % 2 !== 0) {
    print(-1);
} else if (pathL === pathR && pathU === pathD) {
    print(0);
} else {
    print((Math.abs(pathL - pathR) + Math.abs(pathU - pathD)) / 2);
}

var s = readline();
var solution = function ( s ) {
  if ( s.length%2 != 0 ) {
    return -1;
  }
  var forward = [...s.substr( 0, s.length / 2 )];
  var backward = [...s.substr( s.length / 2, s.length / 2 )];
  var forwardHist = new Map( [ [ "L", 0 ], [ "R", 0 ], [ "U", 0 ], [ "D", 0 ] ] );
  var backwardHist = new Map( [ [ "L", 0 ], [ "R", 0 ], [ "U", 0 ], [ "D", 0 ] ] );
  forward.forEach( c => forwardHist.set( c, forwardHist.get( c ) + 1) );
  backward.forEach( c => backwardHist.set( c, backwardHist.get( c ) + 1) );
  return ( Math.abs( backwardHist.get( "L" ) - forwardHist.get( "R" ) ) +
    Math.abs( backwardHist.get( "R" ) - forwardHist.get( "L" ) ) +
    Math.abs( backwardHist.get( "U" ) - forwardHist.get( "D" ) ) +
    Math.abs( backwardHist.get( "D" ) - forwardHist.get( "U" ) )) / 2;
};
print( solution( s ) );


'use strict';

var readline = require('readline');

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

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

function solve(n, a) {
  [...new Array(10).keys()];
  let res = -1;
  for (let i = 0; i < n; i++) {
    if (a[i] !== i) {
      if (res === -1) res = a[i];else res &= a[i];
    }
  }
  return res;
}

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

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

Number.prototype.toInt = function () {
	return parseInt(this);
};
String.prototype.toNumber = function () {
	return +this;
}

const readline = require('readline');

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

class Input {

	constructor() {
		this._lineIndex = 0
		this._inputsBuffer = []
	}

	get _currentLine() {
		return this._lineIndex++;
	}

	buffer(value) {
		this._inputsBuffer.push(value);
	}

	readLine() {
		return this._inputsBuffer[this._currentLine];
	}

	readNumber() {
		return this.readLine().toNumber();
	}

	readArray() {
		return this.readLine().split(' ');
	}

	readIntArray() {
		return this.readArray().map(item => parseInt(item));
	}

}

const io = new Input();

rl.on('line', (input) => {
	io.buffer(input);
});

rl.on('close', () => {
	// const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
	for (let i = io.readLine(); i > 0; --i) {
		io.readLine();
		console.log(io.readIntArray().reduce((ans, value, index) => {
			if (value !== index)
				return ans & value;
			return ans;
		}, Number.MAX_SAFE_INTEGER));
	}
});

Number.prototype.toInt = function () {
	return parseInt(this);
};
String.prototype.toNumber = function () {
	return +this;
}

const readline = require('readline');

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

class Input {

	constructor() {
		this._lineIndex = 0
		this._inputsBuffer = []
	}

	get _currentLine() {
		return this._lineIndex++;
	}

	buffer(value) {
		this._inputsBuffer.push(value);
	}

	readLine() {
		return this._inputsBuffer[this._currentLine];
	}

	readNumber() {
		return this.readLine().toNumber();
	}

	readArray() {
		return this.readLine().split(' ');
	}

	readIntArray() {
		return this.readArray().map(item => parseInt(item));
	}

}

const io = new Input();

rl.on('line', (input) => {
	io.buffer(input);
});

rl.on('close', () => {
	// (function() {
	// const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
	io.readLine();
	io.readLine();
	console.log(io.readIntArray().reduce((ans, value, index) => {
		if (value !== index)
			return ans & value;
		return ans;
	}, Number.MAX_SAFE_INTEGER));
});

'use strict';

var readline = require('readline');

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

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

function solve(n, a) {
  const p = [...new Array(10).keys()];
  function find(i) {
    while (i !== p[i]) {
      p[i] = p[p[i]];
      i = p[p[i]];
    }
    return i;
  }
  function union(i, j) {
    const [rooti, rootj] = [find(i), find(j)];
    if (rooti === rootj) return;
    p[rootj] = rooti;
  }
  for (let i = 0; i < n; i++) {
    if (a[i] !== i) union(i, a[i]);
  }
  let scc = new Map();
  for (let i = 0; i < n; i++) {
    const root = find(i);
    if (!scc.has(root)) scc.set(root, []);
    scc.get(root).push(i);
  }
  let nums = new Set();
  for (let [, arr] of scc) {
    if (arr.length <= 1) continue;
    let x = arr[0];
    for (let i = 1; i < arr.length; i++) {
      x &= arr[i];
    }
    nums.add(x);
  }
  if (nums.size > 1) return 0;else return [...nums][0];
}

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

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


function processData(input) {
input = input.trim().split('\n')

for( let i = 1; i < input.length; i+=3){
    console.log(input[i+1].split(' ').map(n => Number(n)).sort((a,b) => a - b).join(' '))
    console.log(input[i+2].split(' ').map(n => Number(n)).sort((a,b) => a - b).join(' '))
}
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

function processData(input) {

    const verbose = 0;
    input = input.trim().split("\n");
    // console.log(input);
    const tc = Number(input[0]);
    let row = 1;

    for (let i = 0; i < tc; i++)
    {
        const n = Number(input[row]);
        row++;
        let necklace = input[row].trim().split(" ").map(ele => Number(ele));
        row++;
        let bracelet = input[row].trim().split(" ").map(ele => Number(ele));
        row++;

        necklace.sort((a,b) => a - b);
        bracelet.sort((a,b) => a - b);
        let str1 = "";
        let str2 = "";
        for(let j = 0; j < n; j++)
        {
            str1 += necklace[j] + " ";
            str2 += bracelet[j] + " ";
        }

        console.log(str1);
        console.log(str2);

        if(verbose){
            console.log(n);
            console.log(necklace);
              console.log(bracelet);
        }
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

function processData(input) {
    //Enter your code here
    let verbose = 0
    input = input.trim().split('\n')
    let tc = parseInt(input[0])
    verbose ? console.log(input, tc) : ''

    for(let t=0; t<tc*3; t+=3) {
        let n = parseInt(input[t+1])
        let neck = input[t+2].split(' ').map(e=>parseInt(e)).sort((a, b)=>a-b)
        let brace = input[t+3].split(' ').map(e=>parseInt(e)).sort((a, b)=>a-b)
        verbose ? console.log(n, neck, brace) : ''
        console.log(neck.join(' '))
        console.log(brace.join(' '))
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_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++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const test = Number(readline())
    for(let i = 0; i < test; i++){
        const n = Number(readline())
        let necklace = readline().split(" ").map(e => Number(e)).sort((a,b) => (a-b))
        let bracelet = readline().split(" ").map(e => Number(e)).sort((a,b) => (a-b))
        console.log(necklace.join(" "))
        console.log(bracelet.join(" "))
   }

}

function processData(input) {
    //Enter your code here
    input = input.trim().split("\n")
    var tCase = parseInt(input[0])
    input.shift()
    for(let i = 0; i < input.length; i++){
        var stk = input[i+1].split(" ").map(Number)
        var arr = input[i+2].split(" ").map(Number)
        stk = stk.sort((a,b) => a-b)
        arr = arr.sort((a,b) => a-b)
        console.log(stk.join(" "))
        console.log(arr.join(" "))
        i = i + 2
    }

}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

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

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

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

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let ptr = 0
  let t = readInt(input, ptr++)
  while(t--) {
    let n = readInt(input, ptr++)
    let ai = readInts(input, ptr++)
    let bi = readInts(input, ptr++)

    sort(ai)
    sort(bi)
    wr(ai.join(' '))
    wr(bi.join(' '))
  }
}

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

    function foo (a, b) {
        return [a.sort((a, b) => a - b).join(' '), b.sort((a, b) => a - b).join(' ')];
    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let a = lines[testCount * 3 - 1].split(" ").map(Number);
        let b = lines[testCount * 3].split(" ").map(Number);

        let result = foo(a, b);
        answer += result[0] +"\n";
        answer += result[1] +"\n";
        testCount++;
    }
    console.log(answer);
})

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

  main();
});

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

function main() {
  let tests = Number(readline().trim());

  while (tests) {
    let len = Number(readline().trim());

    let necklaces = readline()
      .trim()
      .split(" ")
      .map(e => {
        return Number(e);
      })
      .sort(function(a, b) {
        return a - b;
      });

    let bracelets = readline()
      .trim()
      .split(" ")
      .map(e => {
        return Number(e);
      })
      .sort(function(a, b) {
        return a - b;
      });

    console.log(necklaces.join(" "));
    console.log(bracelets.join(" "));

    --tests;
  }
}

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

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

  if (c % 3 === 0) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number);
  arr.sort((a, b) => a - b);

  console.log(arr.join(' '));

  c++;
});

function processData(input) {
    input = input.trim().split("\n");
    input.shift();
    const printResult = (x,y,n) => {
        x.sort((a,b) => a-b);
        y.sort((a,b) => a-b);
        console.log(x.join(" "));
        console.log(y.join(" "));
    }
    for(let i = 0; i < input.length; i+=3){
        let size = Number(input[i]);
        let arr1 = input[i+1].split(" ").map(Number);
        let arr2 = input[i+2].split(" ").map(Number);
        printResult(arr1,arr2,size);
    }

}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

const processData = (lines) => {
  const num = +lines[0]

  for (let j =0; j<num; j++) {
    const o = lines[j*3+2].split(' ').map(x => +x).sort((a, b) => a -b)
    const b = lines[j*3+3].split(' ').map(x => +x).sort((a, b) => a -b)

    console.log(o.join(' '))
    console.log(b.join(' '))
  }

}

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

function processData(input) {
    //Enter your code here
    input = input.trim().split("\n");
    input = input.map(ele => ele.trim().split(" ").map(Number))
    let tc = input[0][0]
    // console.log(tc)
    for(let i = 2; i < input.length; i = i + 3) {
        let necklessArr = input[i]
        let braceletArr = input[i + 1]
        necklessArr.sort((a, b) => a - b)
        braceletArr.sort((a, b) => a - b)
        console.log(necklessArr.join(" "))
        console.log(braceletArr.join(" "))

    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

function main(raw) {
    var lines = raw.trim().split("\n").map(function (v) { return v.trim().split(" ").map(function (u) { return parseInt(u); }); });
    var n = lines.shift()[0];
    while (n > 0) {
        lines.shift();
        var as = lines.shift().sort(function (a, b) { return a - b; });
        var bs = lines.shift().sort(function (a, b) { return a - b; });
        // const as = Array.from({ length: 100 }, () => Math.floor(Math.random() * 1000));
        // const bs = Array.from({ length: 100 }, () => Math.floor(Math.random() * 1000));
        // const ra = as.sort((a, b) => a - b);
        // const rb = bs.sort((a, b) => a - b);
        // const set = new Set();
        // for()
        // try {
        //     bruteforce(as, new Set(bs), new Set(), 0, []);
        // } catch(res) {
        console.log(as.join(" "));
        console.log(bs.join(" "));
        // }
        n--;
    }
}
function bruteforce(as, bset, got, i, order) {
    if (i === as.length) {
        throw order;
    }
    bset.forEach(function (b) {
        var sum = as[i] + b;
        if (!got.has(sum)) {
            got.add(sum);
            bset["delete"](b);
            bruteforce(as, bset, got, i + 1, order.concat(b));
            bset.add(b);
            got["delete"](sum);
        }
    });
}
(function () {
    var d = "";
    process.stdin.on("data", function (c) { return d += c; });
    process.stdin.on("end", function () { return main(d); });
})();

function processData(input) {
    //Enter your code here
    var data = input.split('\n')
    var tcs = Number(data[0])
    var line= 1
    for(var i = 0;i<tcs;i++){
        var len = Number(data[line])
        line++
        var a = data[line].split(' ').map(a=>parseInt(a))
        a.sort((a,b)=>(a-b))
        console.log(a.join(' '))
        line++
        var b =  data[line].split(' ').map(a=>parseInt(a))
                b.sort((a,b)=>(a-b))
        console.log(b.join(' '))

        line++

    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

'use strict'

const problem = (n, a, b) => a.sort((x, y) => x - y).join(' ') + '\n' + b.sort((x, y) => x - y).join(' ');

let t = +readline()
while(t--) print(problem(+readline(), readline().split(' ').map(i => +i), readline().split(' ').map(i => +i)))

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
//atcoderのサンプルは最後に改行入れること
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));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 = myconv(next(),1);
    var output = new Array(t * 2);
    for(var i = 0; i < t; i++){
        var n = myconv(next(),1);
        var alist = myconv(next(),4);
        var blist = myconv(next(),4);
        alist.sort(function(a,b){
            return a -b;
        });
        blist.sort(function(a,b){
            return a -b;
        });
        output[i * 2] = myconv(alist,8);
        output[i * 2 + 1] = myconv(blist,8);
    }
    myout(myconv(output,9));
}

//var input = readline();

var T = parseInt(readline());
for (var i = 0; i<T; i++) {
    var n = parseInt(readline());

    var ar = readline().split(" ").map(x => parseInt(x));
    ar.sort((a, b) => a - b);

    var ar1 = readline().split(' ').map(x => parseInt(x));
    ar1.sort((a, b) => a - b);

    print(ar.join(' '));
    print(ar1.join(' '));
}

//var input = readline();

var T = parseInt(readline());
for (var i = 0; i<T; i++) {
    var n = parseInt(readline());

    var ar = readline().split(" ").map(x => parseInt(x));
    ar.sort((a, b) => a - b);

    var ar1 = readline().split(' ').map(x => parseInt(x));
    ar1.sort((a, b) => a - b);

    print(ar.join(" ") + "\n" + ar1.join(" "));

}

var t = readline();
for (var i=0; i<t; i++) {
    var n = readline();
    var A = readline().split(' ').sort((a,b) => a-b).join(' ');
    var B = readline().split(' ').sort((a,b) => a-b).join(' ');
    print(A);
    print(B);
}