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

let stdinInput = '';

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

process.stdin.on('end', () => {
  main(stdinInput);
});

function main(data) {
	data = data.split('\n');
	const testCases = data[0] * 1;
	let i = 1;
	while (i <= testCases) {
    let n = data[i] * 1;
    let arr = [];
    for (let i = n; i > 0; i -= 1) arr.push(i);
    console.log(arr.join(' '));
    i += 1;
	}
}

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

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

function main() {
	let t = readLine() >> 0;
	while (t--) {
		let n = readLine() >> 0;
		let arr = [];
		for (let i = n; i > 0; i--) {
			arr.push(i);
		}

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

'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
7

**/

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 a = [];

    let mid = Math.floor(n / 2);
    a[mid] = 1;

    let start = 2;
    for(let i=0;i<n;i++) {
        if(a[i]) {
            continue;
        }
        a[i] = start;
        start++;
    }

    console.log(a.join(" "));

}

function main() {
  var testCasesNum = +readline();
  for (var i = 0; i < testCasesNum; i++) {
    var n = +readline();
    var arr = [];
    for (var j = n; j > 0; j--) {
      arr.push(j);
    }
    print(arr.join(' '));
  }
}

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++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
    const x = readline();
    var cases = parseInt(x);
    for(var i=1;i<=cases;i++){
         var line2 = readline();
         var currentNumber = parseInt(line2);
         console.log(getGoodPermutation(currentNumber));
    }

}
function getGoodPermutation(x) {
    var strs = [];
    for(var i=1;i<=x;i++){
        strs.push(i);
    }
    return strs.join(" ");
}

var readline=require("readline");
var rl=readline.createInterface({
    input:process.stdin,
    output:process.stdout
});
var arr=[];
rl.on('line',function(inp){
    arr.push(parseInt(inp));
    var T=arr[0];
    if(arr.length>1){
        var n=parseInt(arr[arr.length-1]);
        var str="1";
        for(var i=2;i<=n;i++) str+=" "+i;
        console.log(str);
    }
    if(arr.length===(T+1)) process.exit(0);
});

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = [];
    for (let i = 0; i < len; i++) {
      arr.push(i + 1);
    }
    console.log(arr.join(" "));
  }
}

//Don't have to see. start------------------------------------------
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);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
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){
  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';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
  	var N = nextInt();
  	var list = [];
  	for(var j = N; j > 0; j--){
  		list.push(j);
  	}
  	output[i] = myconv(list, 8);
  }
  myout(myconv(output, 9));
}

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.split(/\n/);
    main();
});

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

function main() {
  const t = Number(readLine())
  for (let i = 0; i < t; i++) {
    const n = Number(readLine())
    console.log(Array(n).fill(0).map((_, i) => i + 1).join(' '))
  }
}


let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    for(i = 1; i <= t; i++){
        var k = lines[i].split(' ').map(Number);
        var n = k[0], m = k[1];
        if(n < m){
            var temp = n;
            n = m;
            m = temp;
        }
        if(m == 1 && n >= 3){
            console.log(-1);
        }else{
            console.log(2 * n - Math.floor((n + m) % 2) - 2);
        }
    }
});

//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 m = nextInt();

        let max = Math.max(n, m), min = Math.min(n, m);

        if (min === 1) {
            if (max === 1) {
                myout(0);
            } else if (max === 2) {
                myout(1);
            } else {
                myout(-1);
            }
            continue
        }

        if (max === min + 1 || max === min) {
            myout(max + min - 2);
            continue;
        }

        let diff = max - min;
        let res = 0;
        if (diff % 2 === 1) {
            res += 1
        }

        res += min*2 - 2 + Math.floor(diff / 2) * 4;
        myout(res)
        // output in nodeJs
        // console.log(arr)
	}
}

//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 m = nextInt();

        let max = Math.max(n, m), min = Math.min(n, m);

        if (min === 1) {
            if (max === 1) {
                myout(0);
            } else if (max === 2) {
                myout(1);
            } else {
                myout(-1);
            }
            continue
        }

        if (max === min + 1 || max === min) {
            myout(max + min - 2);
            continue;
        }

        let diff = max - min;
        let res = 0;
        if (diff % 2 === 1) {
            res += 1
        }

        res += min*2 - 2 + Math.floor(diff / 2) * 4;
        myout(res)
        // output in nodeJs
        // console.log(arr)
	}
}

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

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

function main(){
    // input in nodeJs
	let test = parseInt(readLine(),10);
	while(test--){
		let [n, m] = readLine().split(" ").map(ele => parseInt(ele, 10));

        let max = Math.max(n, m), min = Math.min(n, m);

        if (min === 1) {
            if (max === 1) {
                console.log(0);
            } else if (max === 2) {
                console.log(1);
            } else {
                console.log(-1);
            }
            continue
        }

        if (max === min + 1 || max === min) {
            console.log(max + min - 2);
            continue;
        }

        let diff = max - min;
        let res = 0;
        if (diff % 2 === 1) {
            res += 1
        }

        res += min*2 - 2 + Math.floor(diff / 2) * 4;
        console.log(res)
        // output in nodeJs
        // console.log(arr)
	}
}

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

let s = "";
process.stdin.on("data", (data) => {
  s += data;
});

process.stdin.on("end", () => {
  s = s.trim().split("\n");

  main();
});

function main() {
  let t = Number(s[0]);

  let i = 1;
  while (t--) {
    const [m, n] = s[i].split(" ").map(Number);
    solve(m, n);
    i++;
  }
}

function solve(m, n) {
  if (m === 1 || n === 1) {
    if (Math.abs(m - n) === 1) {
      console.log(1);
      return;
    }
    if (m + n > 2) {
      console.log(-1);
      return;
    }
  }

  if (m < n) {
    [m, n] = [n, m];
  }

  let count = 0;
  const diag = 2 * (n - 1);

  count += diag;

  const remaining = m - n;
  const twoJumps = Math.floor(remaining / 2);
  count += twoJumps * 4;
  count += remaining % 2;

  console.log(count);
}

'use strict';

var fs = require('fs');

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

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

function solve(n, m) {
  if (n > m) {
    return solve(m, n);
  } else {
    if (n === 1 && m > 2) console.log(-1);else if ((n & 1) === (m & 1)) console.log(m * 2 - 2);else console.log(m * 2 - 3);
  }
}

function main(inputs) {
  const _ = Number(inputs[0]);

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

    solve(n, m);
  }
}

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

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let i=1;i<=t;i++)
    {
        let [x,y]=line[i].split(' ').map(x=>{return parseInt(x)});
        x--;
        y--;
        if(x>y) [x,y]=[y,x];
        if(x===0)
        {
            if(y<=1) console.log(y);
            else console.log(-1);
        }
        else
        {
            let ans=y+x+(y-x-1);
            if((y-x-1)&1) ans++;
            console.log(ans);
        }
    }
})

'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, m] = readline().split(' ').map(Number);
        if (m > n) [m, n] = [n, m];

        if (m === 1 && n > 2) {
            output(-1);
            continue;
        }

        output(2*n-2-(n+m)%2);
    }
}

'use strict';
const readline = require('readline');
const util = require('util');
const lineReader = readline.createInterface({
    input: process.stdin,
});
let inputPos = 0;
const inputWords = [];
lineReader.on('line', (line) => {
    inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));
});
lineReader.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(inputWords[inputPos++]));
}
function nextStr() {
    return inputWords[inputPos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
const INF = Infinity;
function solve(n, m) {
    if (n < m) {
        [n, m] = [m, n];
    }
    if (m == 1 && n > 2) {
        return INIT;
    }
    let ans = m + m - 2;
    n -= m;
    let pairs = n - (n % 2);
    ans += pairs * 2;
    if ((n % 2) == 1) {
        ans++;
    }
    return ans;
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        let n = nextInt();
        let m = nextInt();
        printf("%d\n", solve(n, m));
    }
}

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, m] = input[index].split(" ").map((item) => parseInt(item));
    const testCase = {
      n,
      m,
    };
    testCases.push(testCase);
  }
}

function solution(testCase, index) {
  const { n, m } = testCase;

  const mini = Math.min(m - 1, n - 1);
  const maxi = Math.max(m - 1, n - 1);
  const diff = Math.abs(m - n);

  let result =
    mini == 0 && maxi > 1
      ? -1
      : mini * 2 + Math.floor(diff / 2) * 4 + (diff % 2);
  console.log(result);
}

parseInput();

testCases.forEach(solution);

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

function div(val, by){
    return (val - val % by) / by;
}

const calc = (n, m)=>{
    if (n === 1 && m === 1) return 0;
    if (n === 1 && m > 2 || n > 2 && m === 1) return -1;
    if (n === 1 && m === 2 || n === 2 && m === 1) return 1;

    let diag = (Math.min(n, m) - 1) * 2;
    // console.log('DEBUG diag', diag);
    if (n === m) return diag;

    let diff = Math.abs(n - m);

    let x1 = Math.floor((diff + 1) / 2);
    let x2 = Math.floor(diff / 2);
    // console.log('DEBUG x1', x1);
    // console.log('DEBUG x2', x2);

    let min = Math.min(n, m);
    let divBy2 = min % 2;
    // console.log('DEBUG divBy2', divBy2);

    // let ones = divBy2 ? x2 : x1;
    // let threes = divBy2 ? x1 : x2;
    let ones = x1;
    let threes = x2;

    // console.log('DEBUG ones', ones);
    // console.log('DEBUG threes', threes);

    let res = diag + ones + threes * 3;

    return res;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let [n, m] = ra();

        console.log(`${calc(n, m)}`);
    }
}

'use strict';

const { checkPrime } = require('crypto');
const { Z_FIXED } = require('zlib');

 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
  rl.on('line', line => {
      lines.push(line);
  });
  rl.on('close', main)
}
let rli = 0;
function readline() {
    return lines[rli++];
}
const l = process.env.DEBUG ? console.log : ()=>{};

module.exports = E;

const ra = ()=>readline().split(' ').map(a=>+a)

const calc = (n, m)=>{
  if (n>m)
    return calc(m, n);
  // n<m
  n--;
  m--;
  if (n==0 && m>1)
    return -1;
  let ans = n*2;
  m -= n;
  if (m==0)
    return ans;
  l({ans, m})
  return ans + Math.floor((m)/2)*4 + m%2;
  if (m%3==2){
  }
  ans++;
  m--;
  ans += m*2
  if (0)
  if (m%2)
    ans++;
  return ans;
};

function main() {
    let T = +readline()
    while (T--){
      let [n, m] = ra();
      l('ans')
      print(calc(n, m));
    }
}

E.calc = calc;

//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 M = nextInt();
		var H = Math.min(N, M);
		var W = Math.max(N, M);
		if(H == 1 && W >= 3){
			myout(-1);
			continue;
		}
		var output = (H - 1) + (W - 1);
		if(W - H >= 2){
			var diff = W - H;
			output += Math.floor(diff / 2) * 2;
		}
		myout(output);
	}
}

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

let s = "";
process.stdin.on("data", (data) => {
  s += data;
});

process.stdin.on("end", () => {
  s = s.trim().split("\n");

  main();
});

function main() {
  let t = Number(s[0]);

  let i = 1;
  while (t--) {
    const [m, n] = s[i].split(" ").map(Number);
    solve(m, n);
    i++;
  }
}

function solve(m, n) {
  if (m === 1 || n === 1) {
    if (m - n === 1) {
      console.log(1);
      return;
    }
    if (m + n > 2) {
      console.log(-1);
      return;
    }
  }

  if (m < n) {
    [m, n] = [n, m];
  }

  let count = 0;
  const diag = 2 * (n - 1);

  count += diag;

  const remaining = m - n;
  const twoJumps = Math.floor(remaining / 2);
  count += twoJumps * 4;
  count += remaining % 2;

  console.log(count);
}

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

let s = "";
process.stdin.on("data", (data) => {
  s += data;
});

process.stdin.on("end", () => {
  s = s.trim().split("\n");

  main();
});

function main() {
  let t = Number(s[0]);

  let i = 1;
  while (t--) {
    const [m, n] = s[i].split(" ").map(Number);
    solve(m, n);
    i++;
  }
}

function solve(m, n) {
  if (m === 1 && n === 1) {
    console.log(0);
    return 0;
  }
  if (m === 1 || n === 1) {
    console.log(-1);
    return;
  }

  let sx = 1,
    sy = 1;

  let count = 0;
  const defOptions = [
    [1, 0],
    [0, 1],
  ];
  let i = 0;
  while (sx !== m && sy !== n) {
    sx += defOptions[i][0];
    sy += defOptions[i][1];
    i = (i + 1) % 2;
    count++;
  }

  const diff = sx === m ? n - sy : m - sx;
  const q = Math.floor(diff / 2);
  const r = diff % 2;
  count += q * 4 + r;

  console.log(count);
}

'use strict';

var fs = require('fs');

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

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

function solve(n, m) {
  if (m === n) {
    console.log(n * (n - 1));
  } else if (n > m) {
    return solve(m, n);
  } else {
    if (n === 1 && m > 2) console.log(-1);else if ((n & 1) === (m & 1)) console.log(m * 2 - 2);else console.log(m * 2 - 3);
  }
}

function main(inputs) {
  const _ = Number(inputs[0]);

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

    solve(n, m);
  }
}

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


const processData = (lines) => {
  const nums = +lines[0]
  for (let i =0; i<nums;i++) {
    const [n, k] = lines[i*2+1].split(' ').map(x => +x)
    const arr = lines[i*2+2].split(' ').map(x => +x)
    const ns = new Set()
    for (const num of arr) {
      ns.add(num)
    }
    const s = Array.from(ns)
    if (s.length > k) {
      console.log(-1)
    } else {
      let diff = k - s.length
      while (diff) {
        s.push(s[0])
        diff--
      }
      console.log(n * s.length)
      console.log(arr.reduce((r) => r.concat(s), []).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)
})

const input = [];

function splbsi(line) {
  return line.split(" ").map((x) => parseInt(x));
}

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

readLine.on("line", (line) => {
  input.push(line);
});

readLine.on("close", () => {
  for (let i = 1; i < input.length; i += 2) {
    const [n, k] = splbsi(input[i]);
    const arr = splbsi(input[i + 1]);

    const nums = new Set(arr);

    if (nums.size > k) {
      console.log(-1);
      continue;
    }

    const res = [...nums];
    for (let j = 0; j < k - nums.size; j += 1) {
      res.push(1);
    }

    const answer = [];
    for (let i = 0; i < n; i += 1) {
      answer.push(...res);
    }

    console.log(answer.length);
    console.log(answer.join(" "));
  }
});

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

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

    for(var r=0;r<range;r++) {
        var [n, limit] = readline().split(" ").map(x=> parseInt(x));
        var numbers = readline().split(" ").map(x=> parseInt(x));
        var unique = new Set(numbers);

        if(unique.size > limit) {
            console.log(-1);
            continue;
        }

        const output = [];
        for(let i=0;i<n;i++) {
            output.push(...Array.from(unique));

            for(let k=0;k<limit - unique.size;k++) {
                output.push(1);
            }
        }
        console.log(output.length);

        console.log(output.join(" "));

    }
}

const input = [];

function splbsi(line) {
  return line.split(" ").map((x) => parseInt(x));
}

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

readLine.on("line", (line) => {
  input.push(line);
});

readLine.on("close", () => {
  for (let i = 1; i < input.length; i += 2) {
    const [n, k] = splbsi(input[i]);
    const arr = splbsi(input[i + 1]);

    const nums = new Set(arr);

    if (nums.size > k) {
      console.log(-1);
      continue;
    }

    const res = [];
    for (let j = 0; j < n; j += 1) {
      res.push(...[...nums, 1]);
    }

    console.log(n * k);
    console.log(res.join(" "));
  }
});

const input = [];

function splbsi(line) {
  return line.split(" ").map((x) => parseInt(x));
}

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

readLine.on("line", (line) => {
  input.push(line);
});

readLine.on("close", () => {
  for (let i = 1; i < input.length; i += 2) {
    const [n, k] = splbsi(input[i]);
    const arr = splbsi(input[i + 1]);

    const nums = new Set(arr);

    if (nums.size > k) {
      console.log(-1);
      continue;
    }

    const res = [];
    for (let j = 0; j < n; j += 1) {
      res.push(...[...nums, 1]);
    }

    console.log(res.length);
    console.log(res.join(" "));
  }
});

const input = [];

function splbsi(line) {
  return line.split(" ").map((x) => parseInt(x));
}

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

readLine.on("line", (line) => {
  input.push(line);
});

readLine.on("close", () => {
  for (let i = 1; i < input.length; i += 2) {
    const [n, k] = splbsi(input[i]);
    const arr = splbsi(input[i + 1]);

    const nums = new Set(arr);

    if (nums.size > k) {
      console.log(-1);
      continue;
    }

    const res = [];
    while (res.length <= n) {
      res.push(...nums);
    }

    console.log(res.length);
    console.log(res.join(" "));
  }
});

const processData = (lines) => {
  const nums = +lines[0]
  for (let i =0; i<nums;i++) {
    const [n, k] = lines[i*2+1].split(' ').map(x => +x)
    const arr = lines[i*2+2].split(' ').map(x => +x)
    const ns = new Set()
    for (const num of arr) {
      ns.add(num)
    }
    const s = Array.from(ns)
    if (s.length > k) {
      console.log(-1)
    } else {
      console.log(n * s.length)
      console.log(arr.reduce((r) => r.concat(s), []).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)
})

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

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

    for(var r=0;r<range;r++) {
        var [n, limit] = readline().split(" ").map(x=> parseInt(x));
        var numbers = readline().split(" ").map(x=> parseInt(x));
        var oldNumber = [...numbers];
        numbers.sort((a,b) => a-b);

        if(numbers.join("") === oldNumber.join("")) {
            console.log(-1);
        } else {
            let max = Math.max.apply(null, oldNumber);
            let output = [];

            for(let i=0;i<n;i++) {
                let nu = max;
                while(nu) {
                    output.push(nu);
                    nu--;
                }
            }
            console.log(output.length);
            console.log(output.join(" "));
        }

    }
}

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

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

    for(var r=0;r<range;r++) {
        var [n, limit] = readline().split(" ").map(x=> parseInt(x));
        var numbers = readline().split(" ").map(x=> parseInt(x));
        var unique = new Set(numbers);

        if(unique.size === numbers.length) {
            console.log(-1);
            continue;
        }

        const output = [];
        console.log(n*limit);
        for(let i=0;i<= n;i++) {
            output.push(...Array.from(unique));
            if(!unique.has(1)) {
                output.push(1);
            }
        }
        console.log(output.join(" "));

    }
}

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

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

    for(var r=0;r<range;r++) {
        var [n, limit] = readline().split(" ").map(x=> parseInt(x));
        var numbers = readline().split(" ").map(x=> parseInt(x));
        var oldNumber = [...numbers];
        numbers.sort((a,b) => a-b);

        if(numbers.join("") === oldNumber.join("")) {
            console.log(-1);
        } else {
            let max = Math.max.apply(null, oldNumber);
            limit = limit * 2;
            let output = [];

            for(let i=0;i<limit;i++) {
                let nu = max;
                while(nu && output.length <= limit) {
                    output.push(nu);
                    nu--;
                }
            }
            console.log(output.length);
            console.log(output.join(" "));
        }

    }
}

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

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

    for(var r=0;r<range;r++) {
        var [n, limit] = readline().split(" ").map(x=> parseInt(x));
        var numbers = readline().split(" ").map(x=> parseInt(x));
        var unique = new Set(numbers);

        if(unique.size >= limit) {
            console.log(-1);
            continue;
        }

        const output = [];
        for(let i=0;i<n;i++) {
            output.push(...Array.from(unique));

            for(let k=0;k<limit - unique.size;k++) {
                output.push(1);
            }
        }
        console.log(output.length);

        console.log(output.join(" "));

    }
}

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

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

    for(var r=0;r<range;r++) {
        var [n, limit] = readline().split(" ").map(x=> parseInt(x));
        var numbers = readline().split(" ").map(x=> parseInt(x));
        var unique = new Set(numbers);

        if(unique.size === numbers.length) {
            console.log(-1);
            continue;
        }

        const output = [];
        for(let i=0;i<n;i++) {
            output.push(...Array.from(unique));

            for(let k=0;k<limit - unique.size;k++) {
                output.push(1);
            }
        }
        console.log(output.length);

        console.log(output.join(" "));

    }
}

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

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

    for(var r=0;r<range;r++) {
        var [n, limit] = readline().split(" ").map(x=> parseInt(x));
        var numbers = readline().split(" ").map(x=> parseInt(x));
        var oldNumber = [...numbers];
        numbers.sort((a,b) => a-b);

        if(numbers.join("") === oldNumber.join("")) {
            console.log(-1);
        } else {
            let max = Math.max.apply(null, oldNumber);
            let output = [];

            for(let i=0;i<n * limit;i++) {
                let nu = max;
                while(nu && output.length <= n*limit - 1) {
                    output.push(nu);
                    nu--;
                }
            }
            console.log(output.length);
            console.log(output.join(" "));
        }

    }
}

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

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

    for(var r=0;r<range;r++) {
        var [n, limit] = readline().split(" ").map(x=> parseInt(x));
        var numbers = readline().split(" ").map(x=> parseInt(x));
        var unique = new Set(numbers);

        if(unique.size === numbers.length) {
            console.log(-1);
            continue;
        }

        const output = [];
        console.log(n*limit);
        for(let i=0;i<= n;i++) {
            output.push(Array.from(unique));
            if(!unique.has(1)) {
                output.push(1);
            }
        }
        console.log(output.join(" "));

    }
}


function readInts() {
    return readline().split(' ').map(function (v) { return parseInt(v); });
}
function min(_a, _b) {
    var l1 = _a[0], r1 = _a[1];
    var l2 = _b[0], r2 = _b[1];
    // console.log('min', [l1, r1], [l2, r2]);
    return [l1 < l2 ? l1 : l2, r1 < r2 ? r1 : r2];
}
function solve(n, m, rooms) {
    var _a, _b, _c;
    var first = true;
    var _d = [0, 0], l = _d[0], r = _d[1];
    var f = 0;
    while (f < n) {
        var room = rooms[f];
        var leftmost = room.indexOf('1');
        if (leftmost < 0) {
            if (!first)
                _a = min([l + 1, r + 1], [r + m + 2, l + m + 2]), l = _a[0], r = _a[1];
        }
        else {
            var rightmost = room.lastIndexOf('1');
            if (first) {
                _b = [rightmost, m - leftmost + 1], l = _b[0], r = _b[1];
                first = false;
            }
            else {
                _c = min([m + 2 + r, m + 2 + l], [rightmost * 2 + 1 + l, (m - leftmost + 1) * 2 + 1 + r]), l = _c[0], r = _c[1];
            }
        }
        // console.log({ f, l, r });
        f++;
    }
    return l;
}
// function show(n: number, m: number, rooms: string[]) {
//     console.log({n, m, rooms}, '-->', solve(n, m, rooms))
// }
// show(2, 2, [
//     '0010',
//     '0100']);
// show(3, 4, [
//     '001000',
//     '000010',
//     '000010']);
// show(4, 3, [
//     '01110',
//     '01110',
//     '01110',
//     '01110'])
var _a = readInts(), n = _a[0], m = _a[1];
var rooms = [];
for (var i = 0; i < n; i++)
    rooms.push(readline());
print(solve(n, m, rooms));

var arr = readline().split(' ');
var n = parseInt(arr[0]);
var m = parseInt(arr[1]);
var v = Array(n);
var count = 0;
var ef = 0;
for (var i = 0; i < n; i ++)
{
    var arr = readline();
    var line = arr.substr(1,m);
    // var line = Array(m).fill(0);
    // for (var j = 0; j < m; j ++)
    // {
    //     line[j] = arr.charAt(j+1)=='1'?1:0;
    // }
    // v.splice(v, 0, line);
    if (line.indexOf('1') != -1)
    {
        v[count++] = line;
    }
    else if (count !== 0)
    {
        ef ++;
    }
}
n = count;
// print(JSON.stringify(v));

if (n === 0)
{
    print(0);
}
var dp = [Array(n+2).fill(0), Array(n+2).fill(0)];
for (var i = 0; i < n; i ++)
{
    var r = v[n-1-i].lastIndexOf('1');
    var l = v[n-1-i].indexOf('1');
    // print(l, r);
    if (i === 0)
    {
        if (n == 1)
        {
            print(r+1 + ef);
        }
        else
        {
            dp[0][i] = (r+1)*2 + 1;
            dp[1][i] = m + 2;
        }
    }
    else if (i == n-1)
    {
        print(Math.min( dp[0][i-1]+(r+1), dp[1][i-1]+(m-l)) + ef);
    }
    else
    {
        dp[0][i] = Math.min( dp[0][i-1]+(r+1)*2, dp[1][i-1]+(m+1)) + 1;
        dp[1][i] = Math.min( dp[0][i-1]+(m+1), dp[1][i-1]+(m-l)*2) + 1;
    }
    // print(JSON.stringify(dp));
}

var arr = readline().split(' ');
var n = parseInt(arr[0]);
var m = parseInt(arr[1]);
var v = Array(n);
for (var i = 0; i < n; i ++)
{
    var arr = readline();
    var line = arr.substr(1,m);
    // var line = Array(m).fill(0);
    // for (var j = 0; j < m; j ++)
    // {
    //     line[j] = arr.charAt(j+1)=='1'?1:0;
    // }
    // v.splice(v, 0, line);
    v[n-i-1] = line;
}
// print(JSON.stringify(v));

var dp = [Array(n+2).fill(0), Array(n+2).fill(0)];
for (var i = 0; i < n; i ++)
{
    var r = v[i].lastIndexOf('1');
    var l = v[i].indexOf('1');
    // print(l, r);
    if (i === 0)
    {
        dp[0][i] = (r+1)*2 + 1;
        dp[1][i] = m + 2;
    }
    else if (i == n-1)
    {
        print(Math.min( dp[0][i-1]+(r+1), dp[1][i-1]+(m-l)));
    }
    else
    {
        dp[0][i] = Math.min( dp[0][i-1]+(r+1)*2, dp[1][i-1]+(m+1)) + 1;
        dp[1][i] = Math.min( dp[0][i-1]+(m+1), dp[1][i-1]+(m-l)*2) + 1;
    }
    // print(JSON.stringify(dp));
}

var arr = readline().split(' ');
var n = parseInt(arr[0]);
var m = parseInt(arr[1]);
var v = Array(n);
var count = 0;
var ef = 0;
for (var i = 0; i < n; i ++)
{
    var arr = readline();
    var line = arr.substr(1,m);
    // var line = Array(m).fill(0);
    // for (var j = 0; j < m; j ++)
    // {
    //     line[j] = arr.charAt(j+1)=='1'?1:0;
    // }
    // v.splice(v, 0, line);
    if (line.indexOf('1') != -1)
    {
        v[count++] = line;
    }
    else if (count !== 0)
    {
        ef ++;
    }
}
n = count;
// print(JSON.stringify(v));

var dp = [Array(n+2).fill(0), Array(n+2).fill(0)];
for (var i = 0; i < n; i ++)
{
    var r = v[n-1-i].lastIndexOf('1');
    var l = v[n-1-i].indexOf('1');
    // print(l, r);
    if (i === 0)
    {
        dp[0][i] = (r+1)*2 + 1;
        dp[1][i] = m + 2;
    }
    else if (i == n-1)
    {
        print(Math.min( dp[0][i-1]+(r+1), dp[1][i-1]+(m-l)) + ef);
    }
    else
    {
        dp[0][i] = Math.min( dp[0][i-1]+(r+1)*2, dp[1][i-1]+(m+1)) + 1;
        dp[1][i] = Math.min( dp[0][i-1]+(m+1), dp[1][i-1]+(m-l)*2) + 1;
    }
    // print(JSON.stringify(dp));
}

var arr = readline().split(' ');
var n = parseInt(arr[0]);
var m = parseInt(arr[1]);
var v = Array(n);
var count = 0;
var ef = 0;
for (var i = 0; i < n; i ++)
{
    var arr = readline();
    var line = arr.substr(1,m);
    // var line = Array(m).fill(0);
    // for (var j = 0; j < m; j ++)
    // {
    //     line[j] = arr.charAt(j+1)=='1'?1:0;
    // }
    // v.splice(v, 0, line);
    if (line.indexOf('1') != -1)
    {
        v[count++] = line;
    }
    else if (count !== 0)
    {
        ef ++;
    }
}
n = count;
// print(JSON.stringify(v));

var dp = [Array(n+2).fill(0), Array(n+2).fill(0)];
for (var i = 0; i < n; i ++)
{
    var r = v[n-1-i].lastIndexOf('1');
    var l = v[n-1-i].indexOf('1');
    // print(l, r);
    if (i === 0)
    {
        if (n == 1)
        {
            print(r+1 + ef);
        }
        else
        {
            dp[0][i] = (r+1)*2 + 1;
            dp[1][i] = m + 2;
        }
    }
    else if (i == n-1)
    {
        print(Math.min( dp[0][i-1]+(r+1), dp[1][i-1]+(m-l)) + ef);
    }
    else
    {
        dp[0][i] = Math.min( dp[0][i-1]+(r+1)*2, dp[1][i-1]+(m+1)) + 1;
        dp[1][i] = Math.min( dp[0][i-1]+(m+1), dp[1][i-1]+(m-l)*2) + 1;
    }
    // print(JSON.stringify(dp));
}


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

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

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

  for(let i = 0; i < t; i++) {
    const [A, B] = readInts(arr, i)
    // wr(arr[i], A, B)

    let st = B.toString()
    let len = st.length

    if(Math.pow(10, len) - 1 > B) len --

    wr(A * len)

  }
})

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

'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() {
    var t = parseInt(readline());
    var A, B;
    for (var i = 0; i < t; i++)
    {
        var line = readline().split(' ')
        A = parseInt(line[0]);
        B = parseInt(line[1]);
        console.log(A * (('' + (B + 1)).length - 1));
    }

}

'use strict'
var t=Number(readline());

while(t--){
    var s=readline().replace(/\r$/, '').split(' ').map(Number);
    var a=s[0];
    var b=s[1];

    var cnt=0,nine=0;

    while((nine*10+9)<=b){
        nine*=10;
        nine+=9;
        cnt++;
   }
    var ans=Number(a*cnt);
    print(ans);
}

'use strict'
var t=Number(readline());

while(t--){
    var s=readline().replace(/\r$/, '').split(' ').map(Number);
    var a=s[0];
    var b=s[1];

    var cnt=0,nine=0;

    while((nine*10+9)<=b){
        nine*=10;
        nine+=9;
        cnt++;
        print("pp");
   }
    var ans=Number(a*cnt);
    print(ans);
}


"use strict";

var atLevel = {};

function addForLevel (text, level) {
    if (!(level in atLevel)) {
        atLevel[level] = [];
    }
    atLevel[level].push(text);
}

function parseComment (tokens, pos, level) {
    var text = tokens[pos++];
    var kids = parseInt(tokens[pos++]);
    addForLevel (text, level);
    var positions = [kids];
    while (true) {
        while (positions.length > 0 && positions[positions.length - 1] === 0)
            positions.pop();
        if (positions.length === 0)
            break;
        text = tokens[pos++];
        kids = parseInt(tokens[pos++]);
        positions[positions.length - 1]--;
        addForLevel (text, positions.length);
        positions.push(kids)
    }
    return pos;
}

function parseAll (s) {
    var tokens = s.split(',');
    var pos = 0;
    while (pos < tokens.length)
        pos = parseComment(tokens, pos, 0);
}

var s = readline();
parseAll(s);
var level = 0;
while (level in atLevel)
    level++;
print(level);
for (var i = 0; i < level; i++)
    print(atLevel[i].join(' '));

// Generated by CoffeeScript 1.10.0

/*
readline = ->
  #'hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0'
  #'a,5,A,0,a,0,A,0,a,0,A,0'
  'A,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0'

print = console.log
 */

(function() {
  var depthstack, el, i, j, layers, len, line, name, numbers, text;

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

  text = line.filter(function(x, i) {
    return i % 2 === 0;
  });

  numbers = line.filter(function(x, i) {
    return i % 2 === 1;
  }).map(Number);

  layers = [];

  depthstack = [Infinity];

  for (i = j = 0, len = text.length; j < len; i = ++j) {
    el = text[i];
    if (layers[name = depthstack.length - 1] == null) {
      layers[name] = [];
    }
    layers[depthstack.length - 1].push(text[i]);
    depthstack[depthstack.length - 1] -= 1;
    depthstack.push(numbers[i]);
    while (depthstack[depthstack.length - 1] === 0) {
      depthstack.pop();
    }
  }

  print(layers.length);

  print(layers.map(function(x) {
    return x.join(' ');
  }).join('\n'));

}).call(this);