Polycarp has a string $$$s$$$. Polycarp performs the following actions until the string $$$s$$$ is empty ($$$t$$$ is initially an empty string):  he adds to the right to the string $$$t$$$ the string $$$s$$$, i.e. he does $$$t = t + s$$$, where $$$t + s$$$ is a concatenation of the strings $$$t$$$ and $$$s$$$;  he selects an arbitrary letter of $$$s$$$ and removes from $$$s$$$ all its occurrences (the selected letter must occur in the string $$$s$$$ at the moment of performing this action). Polycarp performs this sequence of actions strictly in this order.Note that after Polycarp finishes the actions, the string $$$s$$$ will be empty and the string $$$t$$$ will be equal to some value (that is undefined and depends on the order of removing).E.g. consider $$$s$$$="abacaba" so the actions may be performed as follows:  $$$t$$$="abacaba", the letter 'b' is selected, then $$$s$$$="aacaa";  $$$t$$$="abacabaaacaa", the letter 'a' is selected, then $$$s$$$="c";  $$$t$$$="abacabaaacaac", the letter 'c' is selected, then $$$s$$$="" (the empty string). You need to restore the initial value of the string $$$s$$$ using only the final value of $$$t$$$ and find the order of removing letters from $$$s$$$.

The first line contains one integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Then $$$T$$$ test cases follow. Each test case contains one string $$$t$$$ consisting of lowercase letters of the Latin alphabet. The length of $$$t$$$ doesn't exceed $$$5 \cdot 10^5$$$. The sum of lengths of all strings $$$t$$$ in the test cases doesn't exceed $$$5 \cdot 10^5$$$.

For each test case output in a separate line:   $$$-1$$$, if the answer doesn't exist;  two strings separated by spaces. The first one must contain a possible initial value of $$$s$$$. The second one must contain a sequence of letters — it's in what order one needs to remove letters from $$$s$$$ to make the string $$$t$$$. E.g. if the string "bac" is outputted, then, first, all occurrences of the letter 'b' were deleted, then all occurrences of 'a', and then, finally, all occurrences of 'c'. If there are multiple solutions, print any one.

7
abacabaaacaac
nowyouknowthat
polycarppoycarppoyarppyarppyrpprppp
isi
everywherevrywhrvryhrvrhrvhv
haaha
qweqeewew

abacaba bac
-1
polycarp lcoayrp
is si
everywhere ewyrhv
-1
-1

NoteThe first test case is considered in the statement.

const readline = require('readline')

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

function solve(str) {
    const ch = []
    const map = {}
    for (let i = str.length - 1; i >= 0; i--) {
        if (ch.indexOf(str[i]) < 0) {
            ch.unshift(str[i])
        }
        map[str[i]] = (map[str[i]] || 0) + 1
    }
// console.log(map, ch)
    let sum = 0
    for (let i = 0; i < ch.length; i++) {
        const c = ch[i]
        const k = map[c]
        // if (i === ch.length - 1) {
        //     sum += k
        //     break
        // }
        if (k % (i + 1)) return -1

        sum += k / (i + 1)
    }
    const old = str.slice(0, sum)

    const d = {}
    let p = 0
    for (let i = 0; i < ch.length; i++) {
        for (let j = 0; j < sum; j++) {
            if (!d[old[j]]) {
                if (str[p] !== old[j]) return -1
                p++
            }
        }
        const c = ch[i]
        d[c] = 1
    }

    return old + ' ' + ch.join('')
}

let inputs = []

function read() {
    return inputs.pop();
}

function readInt() {
    return parseInt(read());
}

function solve() {
    let test = readInt();
    while (test--) {
        let t = read();
        used = new Array(256);
        for (let i = 0; i < 256; i++) {
            used[i] = 0;
        }
        let s = '';
        let sq = '';
        for (let i = t.length - 1; 0 <= i; i--) {
            let c = t.charCodeAt(i);
            if (!used[c]) {
                sq += t[i];
            }
            used[c] += 1;
        }
        sq = sq.split("").reverse().join("");
        cnt = new Array(256);
        for (let i = 0; i < 256; i++) {
            cnt[i] = 0;
        }
        cnt2 = new Array(256);
        for (let i = 0; i < 256; i++) {
            cnt2[i] = 0;
        }
        for (let i = 0; i < sq.length; i++) {
            let c = sq.charCodeAt(i);
            cnt[c] = parseInt(used[c] / (i + 1));
        }
        let num = 0;
        for (let i = 0; i < t.length; i++) {
            let c = t.charCodeAt(i);
            cnt2[c]++;
            if (cnt[c] == cnt2[c]) {
                num++;
            }
            s += t[i];
            if (num == sq.length) {
                break;
            }
        }
        if (s == '') {
            console.log(-1);
            continue;
        }
        for (let i = 0; i < 256; i++) {
            used[i] = 0;
        }
        let t2 = '';
        for (let i = 0; i < sq.length; i++) {
            for (let j = 0; j < s.length; j++) {
                let c = s.charCodeAt(j);
                if (!used[c]) {
                    t2 += s[j];
                }
            }
            let c = sq.charCodeAt(i);
            used[c] = 1;
        }
        if (t == t2) {
            console.log(s + ' ' + sq);
        }
        else {
            console.log(-1);
        }
    }
}

function main() {
    inputs = inputString.trim().split(/\n| /).map((string) => string.trim());
    inputs.reverse();
    solve();
}

let inputString = '';

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

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

'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readLineAsNumber() {
    return Number(this.readLine())
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(String(e))
  }
  println(e) {
    stdout.write(String(e)), stdout.write('\n')
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(t => {
      stdin.on('data', t => e.push(t)),
        stdin.on('end', function () {
          const n = e.join('').split(os.EOL)
          t(n)
        })
    })
  }
}
async function __main__(e) {
  const t = new InputAndOutput()
  await t.init(), e(t)
}
function solve(e) {
  let t = []
  const n = {}
  for (let i = e.length - 1; i >= 0; --i) {
    const s = e[i]
    let r = n[s]
    void 0 === r ? (t.push(s), (r = 1)) : (r += 1), (n[s] = r)
  }
  const i = t.length
  let s = 0
  for (let e = 0; e < i; ++e) {
    const r = n[t[e]]
    if (r % (i - e) != 0) return -1
    s += r / (i - e)
  }
  t = t.reverse()
  let r = e.slice(0, s)
  for (let n = 0, o = s; n < i; ++n) {
    r = r.replace(new RegExp(t[n], 'g'), '')
    for (let t = 0; t < r.length; ++t) if (r[t] != e[o++]) return -1
  }
  return e.slice(0, s).concat(' ').concat(t.join(''))
}
__main__(function (e) {
  const t = e.readLineAsNumber()
  for (let n = 1; n <= t; ++n) {
    const t = solve(e.readLine())
    e.print(t + '\n')
  }
})


Hacker Zhorik wants to decipher two secret messages he intercepted yesterday. Yeah message is a sequence of encrypted blocks, each of them consists of several bytes of information.Zhorik knows that each of the messages is an archive containing one or more files. Zhorik knows how each of these archives was transferred through the network: if an archive consists of k files of sizes l1, l2, ..., lk bytes, then the i-th file is split to one or more blocks bi, 1, bi, 2, ..., bi, mi (here the total length of the blocks bi, 1 + bi, 2 + ... + bi, mi is equal to the length of the file li), and after that all blocks are transferred through the network, maintaining the order of files in the archive.Zhorik thinks that the two messages contain the same archive, because their total lengths are equal. However, each file can be split in blocks in different ways in the two messages.You are given the lengths of blocks in each of the two messages. Help Zhorik to determine what is the maximum number of files could be in the archive, if the Zhorik's assumption is correct.

The first line contains two integers n, m (1 ≤ n, m ≤ 105) — the number of blocks in the first and in the second messages. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 106) — the length of the blocks that form the first message. The third line contains m integers y1, y2, ..., ym (1 ≤ yi ≤ 106) — the length of the blocks that form the second message. It is guaranteed that x1 + ... + xn = y1 + ... + ym. Also, it is guaranteed that x1 + ... + xn ≤ 106.

Print the maximum number of files the intercepted array could consist of.

NoteIn the first example the maximum number of files in the archive is 3. For example, it is possible that in the archive are three files of sizes 2 + 5 = 7, 15 = 3 + 1 + 11 = 8 + 2 + 4 + 1 and 4 + 4 = 8.In the second example it is possible that the archive contains two files of sizes 1 and 110 = 10 + 100 = 100 + 10. Note that the order of files is kept while transferring archives through the network, so we can't say that there are three files of sizes 1, 10 and 100.In the third example the only possibility is that the archive contains a single file of size 4.

var firstLine = readline().split(' ').map(function(v){return +v;});
var secondLine = readline().split(' ').map(function(v){return +v;});
var thirdLine = readline().split(' ').map(function(v){return +v;});

var aCount = firstLine[0];
var bCount = firstLine[1];
var a = secondLine;
var b = thirdLine;

var curA = a[0];
var curB = b[0];
var result = 0;

var i = 0;
var j = 0;

while (true) {
    if (curA == curB) {
        i++;
        j++;

        if (i > aCount) break;
        if (j > bCount) break;

        result++;

        curA = a[i];
        curB = b[j];
        continue;
    }

    if (curA > curB) {
        j++;
        curB += b[j];
        continue;
    }

    if (curA < curB) {
        i++;
        curA += a[i];
    }
}

print(result);

const firstLine = readline();
const n = firstLine.split(' ')[0];
const m = firstLine.split(' ')[1];
const firstArray = readline().split(' ').map(function(x) {
    return parseInt(x);
});
const secondArray = readline().split(' ').map(function(x) {
    return parseInt(x);
});

var result = 0;
var i = 0,
    j = 0,
    firstSum = firstArray[0],
    secondSum = secondArray[0];

while (i < firstArray.length && j < secondArray.length){
    if (firstSum > secondSum){
        j++;
        secondSum += secondArray[j];
        continue;
    }
    if (firstSum < secondSum){
        i++;
        firstSum += firstArray[i];
        continue;
    }
    if (firstSum === secondSum){
        result++;
        i++;
        firstSum = firstArray[i];
        j++;
        secondSum = secondArray[j];
    }
}

print(result);


You are given three integers $$$n, a, b$$$. Determine if there exists a permutation $$$p_1, p_2, \ldots, p_n$$$ of integers from $$$1$$$ to $$$n$$$, such that:There are exactly $$$a$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} < p_i > p_{i+1}$$$ (in other words, there are exactly $$$a$$$ local maximums).There are exactly $$$b$$$ integers $$$i$$$ with $$$2 \le i \le n-1$$$ such that $$$p_{i-1} > p_i < p_{i+1}$$$ (in other words, there are exactly $$$b$$$ local minimums).If such permutations exist, find any such permutation.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The description of test cases follows. The only line of each test case contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq a,b \leq n$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, if there is no permutation with the requested properties, output $$$-1$$$. Otherwise, print the permutation that you are found. If there are several such permutations, you may print any of them.

NoteIn the first test case, one example of such permutations is $$$[1, 3, 2, 4]$$$. In it $$$p_1 < p_2 > p_3$$$, and $$$2$$$ is the only such index, and $$$p_2> p_3 < p_4$$$, and $$$3$$$ the only such index.One can show that there is no such permutation for the third test case.

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--) {
		let [n, a, b] = rna();

		if (a+b > n-2 || Math.abs(a-b) > 1) {
			console.log(-1);
			continue;
		}

		const ans = [];
		for (let i = 0; i < n; i++) ans.push(i+1);

		let i = 0;
		if (a == b) i = 1;
		else if (a > b) ans.reverse();

		let cnt = Math.max(a, b);
		while (cnt--) {
			[ans[i], ans[i+1]] = [ans[i+1], ans[i]];
			i += 2;
		}

		//console.log({cnt, ans, a, b})

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

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--) {
		let [n, a, b] = rna();

		if (a+b <= n-2 && Math.abs(a-b) <= 1) {

			let cur = 0, diff = 0, sign = 1, mn = 0;

			if (a < b) sign = -1;
			const ans = [0];
			for (let i = 0; i < n-1; i++) {
				if (cur > 0 && a) {
					a--;
					sign *= -1;
				} else if (cur < 0 && b) {
					b--;
					sign *= -1;
				} else {
					diff = 0;
				}
				diff++;

				cur = cur + diff*sign;
				ans.push(cur);

				mn = Math.min(mn, cur);
			}

			//console.log({ans, a, b})
			for (let i = 0; i < n; i++)
				ans[i] += 1 - mn;

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

		} else {
			console.log(-1);
		}

	}
}

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, a, b] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (a + b + 2 > n || Math.abs(a - b) > 1) {
      console.log(-1);
      continue;
    }
    let c = false;
    if (a < b) {
      [a, b] = [b, a];
      c = true;
    }
    let sI = n - a - b - 1;
    let res = [],
      obj = {},
      narr = new Array(n).fill(1).map((cur, ind) => ind + 1);
    for (let i = sI, j = n; i < n; i += 2, j--) obj[j] = res[i] = j;
    let sar = [];
    for (let i = 0; i < n; i++) if (!obj[narr[i]]) sar.push(narr[i]);
    for (let i = 0, j = 0; i < n; i++) if (!res[i]) res[i] = sar[j++];
    if (c) for (let i = 0; i < n; i++) res[i] = n + 1 - res[i];
    console.log(res.join(" "));
  }
};
solve();

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--) {
		let [n, a, b] = rna();

		if (a+b > n-2 || Math.abs(a-b) > 1) {
			console.log(-1);
			continue;
		}

		let cur, mn = 0;
		if (a > b) cur = 1;
		else cur = -1;

		const ans = [0, cur];

		for (let i = 0; i < n-2; i++) {
			if (cur > 0 && a) {
				a--;
				cur = -cur;
			} else if (cur < 0 && b) {
				b--;
				cur = -cur + 1;
			} else {
				cur += cur > 0 ? 1 : -1;
			}

			ans.push(cur);

			mn = Math.min(mn, cur);
		}

		//console.log({a, b, mn})
		for (let i = 0; i < n; i++)
			ans[i] += 1 - mn;

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

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, a, b] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (a + b + 2 > n || Math.abs(a - b) > 1) {
      console.log(-1);
      continue;
    }
    let c = false;
    if (a < b) {
      [a, b] = [b, a];
      c = true;
    }
    let start = n - a;
    let sI = n - a - b - 1;
    let res = [],
      obj = {},
      narr = new Array(n).fill(1).map((cur, ind) => ind + 1);
    for (let i = sI, j = start; i < n; i += 2, j++) obj[j] = res[i] = j;
    let sar = [];
    for (let i = 0; i < n; i++) if (!obj[narr[i]]) sar.push(narr[i]);
    for (let i = 0, j = 0; i < n; i++) if (!res[i]) res[i] = sar[j++];
    if (c) for (let i = 0; i < n; i++) res[i] = n + 1 - res[i];
    console.log(res.join(" "));
  }
};
solve();


Polycarp found on the street an array $$$a$$$ of $$$n$$$ elements.Polycarp invented his criterion for the beauty of an array. He calls an array $$$a$$$ beautiful if at least one of the following conditions must be met for each different pair of indices $$$i \ne j$$$:   $$$a_i$$$ is divisible by $$$a_j$$$;  or $$$a_j$$$ is divisible by $$$a_i$$$. For example, if:   $$$n=5$$$ and $$$a=[7, 9, 3, 14, 63]$$$, then the $$$a$$$ array is not beautiful (for $$$i=4$$$ and $$$j=2$$$, none of the conditions above is met);  $$$n=3$$$ and $$$a=[2, 14, 42]$$$, then the $$$a$$$ array is beautiful;  $$$n=4$$$ and $$$a=[45, 9, 3, 18]$$$, then the $$$a$$$ array is not beautiful (for $$$i=1$$$ and $$$j=4$$$ none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array $$$a$$$ so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array $$$a$$$ beautiful.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ numbers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) — elements of the array $$$a$$$.

For each test case output one integer — the minimum number of elements that must be removed to make the array $$$a$$$ beautiful.

NoteIn the first test case, removing $$$7$$$ and $$$14$$$ will make array $$$a$$$ beautiful.In the second test case, the array $$$a$$$ is already beautiful.In the third test case, removing one of the elements $$$45$$$ or $$$18$$$ will make the array $$$a$$$ beautiful.In the fourth test case, the array $$$a$$$ is beautiful.

let text = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', str => {
    if (str === '\r\n' || str === '\n') {
        process.stdin.emit('end');
    } else {
        text += str;
    }
});

var halvesAreAlike = function(number) {
    const ary = new Array(number);
    const result = [];
    for (let i = 2; i < number; i++) {
        if (!ary[i]) {
            result.push(i);
        }
        for (let ele of result) {
            ary[i * ele] = true;
            if (i* ele >= number) {
                break;
            }
        }
    }
    return result;
};

const mutis = halvesAreAlike(100001);

process.stdin.on('end', () => {
    const input = text.trim().replace(/\r/g, '').split('\n');
    const total = +input[0];
    for (let i = 1; i <= total; i++) {
       console.log(solve(input[i * 2]));
    }
    process.exit();
});

function solve(str) {
    const numbers = str.split(' ').map(ele => +ele);
    const sums = new Array(200001).fill(0);
    let max = 0;
    for (let number of numbers) {
        sums[number]++;
        number > max && (max = number);
    }
    const dp = new Array(max + 1).fill(0);
    let result = 0;
    for (let i = 2; i <= max; i++) {
        dp[i] += sums[i];
        if (dp[i]) {
            result = Math.max(result, dp[i]);
            let left = 0;
            let right = mutis.length - 1;
            while (left < right) {
                const mid = (left + right) >> 1;
                if (mutis[mid] * i > max) {
                    right = mid;
                } else {
                    left = mid + 1;
                }
            }
            for (let j = 0; j < left; j++) {
                const next = mutis[j] * i;
                dp[next] = Math.max(dp[next], dp[i]);
            }
        }
    }

    return numbers.length - result - sums[1];
}


You are playing a game similar to Sokoban on an infinite number line. The game is discrete, so you only consider integer positions on the line.You start on a position $$$0$$$. There are $$$n$$$ boxes, the $$$i$$$-th box is on a position $$$a_i$$$. All positions of the boxes are distinct. There are also $$$m$$$ special positions, the $$$j$$$-th position is $$$b_j$$$. All the special positions are also distinct.In one move you can go one position to the left or to the right. If there is a box in the direction of your move, then you push the box to the next position in that direction. If the next position is taken by another box, then that box is also pushed to the next position, and so on. You can't go through the boxes. You can't pull the boxes towards you.You are allowed to perform any number of moves (possibly, zero). Your goal is to place as many boxes on special positions as possible. Note that some boxes can be initially placed on special positions.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then descriptions of $$$t$$$ testcases follow. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of boxes and the number of special positions, respectively. The second line of each testcase contains $$$n$$$ distinct integers in the increasing order $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_1 < a_2 < \dots < a_n \le 10^9$$$; $$$a_i \neq 0$$$) — the initial positions of the boxes. The third line of each testcase contains $$$m$$$ distinct integers in the increasing order $$$b_1, b_2, \dots, b_m$$$ ($$$-10^9 \le b_1 < b_2 < \dots < b_m \le 10^9$$$; $$$b_i \neq 0$$$) — the special positions. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print a single integer — the maximum number of boxes that can be placed on special positions.

NoteIn the first testcase you can go $$$5$$$ to the right: the box on position $$$1$$$ gets pushed to position $$$6$$$ and the box on position $$$5$$$ gets pushed to position $$$7$$$. Then you can go $$$6$$$ to the left to end up on position $$$-1$$$ and push a box to $$$-2$$$. At the end, the boxes are on positions $$$[-2, 6, 7, 11, 15]$$$, respectively. Among them positions $$$[-2, 6, 7, 15]$$$ are special, thus, the answer is $$$4$$$.In the second testcase you can push the box from $$$-1$$$ to $$$-10^9$$$, then the box from $$$1$$$ to $$$10^9$$$ and obtain the answer $$$2$$$.The third testcase showcases that you are not allowed to pull the boxes, thus, you can't bring them closer to special positions.In the fourth testcase all the boxes are already on special positions, so you can do nothing and still obtain the answer $$$3$$$.In the fifth testcase there are fewer special positions than boxes. You can move either $$$8$$$ or $$$9$$$ to the right to have some box on position $$$10$$$.

'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(data.shift());

    while(testCases--) {
        const [n,m] = readLine().split(' ').map(Number);
        const a = readLine().split(' ').map(Number);
        const b = readLine().split(' ').map(Number);
        const a0 = a.filter(num => num < 0);
        const a1 = a.filter(num => num >= 0);
        const b0 = b.filter(num => num < 0);
        const b1= b.filter(num => num >= 0);
        const a0_filter = a0.filter(num => num >= b0[0]);
        const b0_filter = b0.filter(num => num <= a0_filter[a0_filter.length - 1])
        const a00_filter = a0_filter.map(num => num *-1);
        const b00_filter = b0_filter.map(num => num *-1);
        const a1_filter = a1.filter(num => num <= b1[b1.length - 1]);
        const b1_filter = b1.filter(num => num >= a1_filter[0]);
        console.log(count1(a00_filter.sort((a,b) => a - b), b00_filter.sort((a,b) => a - b),1) + count1(a1_filter, b1_filter,1) );
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function intersection(setA, setB) {
    let _intersection = new Set()
    for (let elem of setB) {
        if (setA.has(elem)) {
            _intersection.add(elem)
        }
    }
    return _intersection
}

function count1(a,b,opt = 0){
    if(a.length === 0 || b.length === 0) return 0;
    let globalMax = 0;
    const setB = new Set([...b]);
    const setA = new Set([...a]);
    let good_pos = intersection(setA, setB)
    let good_len = good_pos.size;
    const start_time = new Date();
    let j =0;
    let i = 0;
    let b_start = 0;
    while(i < b.length){
        // console.log('here', 'curr = ', j, 'b_start  = ', b_start, 'b_end = ', i)
        while(j < a.length && a[j] <= b[i]){
            // console.log(`curr = ${j}, good_len = ${good_len}`)
            if(good_pos.has(a[j])){
                good_len -= 1;
            }
            j += 1;
        }
        while(b_start < i && b[b_start] + j <= b[i]){
            b_start += 1
        }

        globalMax = Math.max(globalMax, Math.min(i - b_start + 1, j) + good_len);
        // console.log(`globalMax+ = ${globalMax}`)
        i++;
    }
    // console.log(`finish in: ${new Date() - start_time} with ${globalMax} `)
    return globalMax;
}

module.exports = count1

const solve = (box, goal) => {
  let res = 0;

  let mem = {};
  let already = goal.map(() => 0);
  box.forEach(b => (mem[b] = true));
  for (let i = 0; i < goal.length; i++) {
    if (mem[goal[i]]) already[i] = 1;
  }
  for (let i = goal.length - 2; i >= 0; i--) {
    already[i] = already[i + 1] + already[i];
  }
  already.push(0);

  let j = 0;
  for (let i = 0; i < goal.length; i++) {
    while (j < box.length && box[j] - j <= goal[i]) {
      j++;
    }
    let currentRes = null;
    let l = i,
      r = goal.length - 1;

    while (true) {
      if (l > r) break;
      const m = Math.floor((l + r) / 2);
      if (goal[m] <= goal[i] - 1 + j) {
        currentRes = m;
        l = m + 1;
      } else r = m - 1;
    }
    currentRes = currentRes === null ? 0 : currentRes - i + 1;
    res = Math.max(res, currentRes + already[currentRes + i]);
  }
  return res;
};

const main = () => {
  const start = new Date();
  let test = readInt();
  while (test--) {
    let [n, m] = readListInt();
    const box = readListInt();
    const goal = readListInt();
    const right = solve(box.filter(i => i > 0), goal.filter(i => i > 0));

    const boxLeft = box
      .filter(i => i < 0)
      .map(i => -i)
      .reverse();
    const goalLeft = goal
      .filter(i => i < 0)
      .map(i => -i)
      .reverse();

    const left = solve(boxLeft, goalLeft);
    console.log(left + right);
  }
};

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 => string.trim());
  main();
});

const readLine = () => {
  return inputString[currentLine++];
};

const readInt = () => {
  return parseInt(inputString[currentLine++]);
};

const readListInt = () => {
  return inputString[currentLine++].split(" ").map(s => parseInt(s));
};

'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(read) {
  const rns = () => {
    return read().split(' ').filter(s => s !== '').map(Number);
  };
  const [n, m] = rns(),
        a = rns(),
        b = rns();
  const calc = () => {
    let sa = 0,
        sb = 0;
    for (; sa < n; sa++) {
      if (a[sa] > 0) break;
    }
    if (sa === n) return 0;
    for (; sb < m; sb++) {
      if (b[sb] > 0) break;
    }
    if (sb === m) return 0;
    let res = 0,
        pre = 0;
    for (let i = m - 1, j = n - 1, k = i; i >= sb; i--) {
      while (a[j] > b[i]) j--;
      if (j < sa || i < sb || i < 0) {
        res = Math.max(res, pre);
        break;
      }
      let num = j - sa + 1;
      for (; k >= 0 && b[i] - b[k] + 1 <= num; k--) {}
      res = Math.max(res, i - k + pre);
      if (a[j] === b[i]) pre++;
    }
    return res;
  };
  let res = calc();
  a.reverse();
  b.reverse();
  for (let i = 0; i < n; i++) a[i] = -a[i];
  for (let i = 0; i < m; i++) b[i] = -b[i];
  res += calc();
  return res;
}

function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < 100) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= 100) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r\n?/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0;
    var t = +lines[l++]
    for (var i = 0; i < t; i++) {
        l++
        var a1 = lines[l++].trim().split(' ').map(Number)
        var a2 = lines[l++].trim().split(' ').map(Number)
        console.log(solve(a1, a2))
    }
});

function solve(a, b) {
    const special = b.reduce((o, x) => {
        o[x] = 1
        return o
    }, {})
    const c = []
    a.forEach(x => {
        if (special[x]) c.push(x)
    })

    const sep = binarySearch(0, b.length - 1, x => b[x] < 0)
    let m1 = 0
    for (let i = sep + 1; i < b.length; i++) {
        const n = cover(0, b[i], a)
        const l1 = cover(b[i] - n + 1, b[i], b) // after pushing
        const l2 = cover(0, b[i], c) // before
        m1 = Math.max(m1, l1 - l2)
    }
    let m2 = 0
    for (let i = sep; i >= 0; i--) {
        const n = cover(b[i], 0, a)
        const l1 = cover(b[i], b[i] + n - 1, b)
        const l2 = cover(b[i], 0, c, false)
        m2 = Math.max(m2, l1 - l2)
    }
    // console.log(c.length, m1, m2)
    return c.length + m1 + m2
}
function cover(l, r, b, include = true) {
    const i = binarySearch(0, b.length - 1, x => b[x] < l)
    const j = binarySearch(0, b.length - 1, x => (include ? b[x] <= r : b[x] < r))
    return j - i
}
function binarySearch(l, r, fn) {
    while (l <= r) {
        const m = Math.floor((l + r) / 2)
        if (fn(m)) {
            l = m + 1
        } else {
            r = m - 1
        }
    }
    return r
}

'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();
var mod = 1000000000n + 7n
var maxN = 1002

function main() {
  const x = readline();
  //
  Array(parseInt(x)).fill(1).map((t, iii) => {
    // var n = parseInt(readline())
    var [n, m] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })
    var a1 = []
    var a2 = []
    var a = readline().split(' ').map((x, iii) => {
      x = parseInt(x)
      if (x > 0) a1.push(x)
      if (x < 0) a2.push(-x)
      return parseInt(x)
    })

    var b1 = []
    var b2 = []
    var b = readline().split(' ').map((x, iii) => {
      x = parseInt(x)
      if (x > 0) b1.push(x)
      if (x < 0) b2.push(-x)

      return parseInt(x)
    })

    var ans1 = solve(a1, b1)
    var ans2 = solve(a2.reverse(), b2.reverse())
    // console.log('-----------')
    console.log(ans1 + ans2)
  })
}

function solve(a, b) {
  var suffix = new Array(a.length + 1).fill(0)

  var right = b.length - 1
  for (let i = a.length - 1; i >= 0; i--) {
    suffix[i] = suffix[i + 1]
    while (right >= 0 && a[i] < b[right]) right--
    if (right >= 0 && a[i] === b[right]) suffix[i]++
  }

  var left = 0
  right = 0
  var ans = 0
  for (let i = 0; i < b.length; i++) {
    while (left < a.length && a[left] <= b[i] + left) left++
    while (right < b.length && b[right] - b[i] < left) right++
    // console.log(left, right, suffix[i])
    ans = Math.max(ans, right - i + suffix[left])
  }

  // console.log(suffix)
  return ans
}

'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(data.shift());

    while(testCases--) {
        const [n,m] = readLine().split(' ').map(Number);
        const a = readLine().split(' ').map(Number);
        const b = readLine().split(' ').map(Number);
        const a0 = a.filter(num => num < 0);
        const a1 = a.filter(num => num >= 0);
        const b0 = b.filter(num => num < 0);
        const b1= b.filter(num => num >= 0);
        const a0_filter = a0.filter(num => num >= b0[0]);
        const a1_filter = a1.filter(num => num <= b1[b1.length - 1]);
        console.log(count1(a0_filter, b0,0) + count1(a1_filter, b1,1) );
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function count1(a,b,opt = 0){
    if(a.length === 0) return 0;
    let globalMax = 0;
    if(opt === 0){
        let j = a.length - 1;
        for(let i = b.length - 1; i >= 0; i--){
            a[j] = b[i];
            if(a[j] <= a[j-1]){
                let c = 1;
                for(let m = j-1; m >= 0 ; m--){
                    a[m] = a[j] - c;
                    if(a[m - 1] < a[m]) break;
                    c++;
                }
            }
            // console.log(`a = ${a}, b = ${b}`);
            let localMax = 0;
            for(let k = a.length - 1 ; k >= 0; k--){
                for(let n = b.length - 1; n >= 0; n--){
                    if(a[k] === b[n]){
                        localMax++;
                        break;
                    }
                }
            }
            if(localMax>globalMax){
                globalMax = localMax;
            }
            // console.log(b, a, localMax,globalMax);
            if(globalMax === b.length || globalMax === a.length) break;
            if(a[a.length - 1] - a.length + 1 <= b[0]) break;
        }
    }
    else {
        let j =0;
        for(let i = 0; i < b.length; i++){
            a[j] = b[i];
            if(a[j] >= a[j+1]){
                let c = 1;
                for(let m = j+1; m < a.length ; m++){
                    a[m] = a[j] + c;
                    if(a[m + 1] > a[m]) break;
                    c++;
                }
            }
            // console.log(`a = ${a}, b = ${b}`);
            let localMax = 0;
            for(let k = 0 ; k < a.length; k++){
                for(let n = 0; n < b.length; n++){
                    if(a[k] === b[n]){
                        localMax++;
                        break;
                    }
                }

            }
            if(localMax>globalMax){
                globalMax = localMax;
            }
            // console.log(b, a, localMax,globalMax);
            if(globalMax === b.length || globalMax === a.length) break;
            if(a[0] + a.length - 1 >= b[b.length - 1]) break;
        }
    }
    return globalMax;
}

module.exports = count1

'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(data.shift());

    while(testCases--) {
        const [n,m] = readLine().split(' ').map(Number);
        const a = readLine().split(' ').map(Number);
        const b = readLine().split(' ').map(Number);
        const a0 = a.filter(num => num < 0);
        const a1 = a.filter(num => num >= 0);
        const b0 = b.filter(num => num < 0);
        const b1= b.filter(num => num >= 0);
        const a0_filter = a0.filter(num => num >= b0[0]);
        const a1_filter = a1.filter(num => num <= b1[b1.length - 1]);
        console.log(count1(a0_filter, b0,0) + count1(a1_filter, b1,1) );
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function count1(a,b,opt = 0){
    if(a.length === 0) return 0;
    let globalMax = 0;
    if(opt === 0){
        let j = a.length - 1;
        for(let i = b.length - 1; i >= 0; i--){
            a[j] = b[i];
            if(a[j] <= a[j-1]){
                let c = 1;
                for(let m = j-1; m >= 0 ; m--){
                    a[m] = a[j] - c;
                    if(a[m - 1] < a[m]) break;
                    c++;
                }
            }
            // console.log(`a = ${a}, b = ${b}`);
            let localMax = 0;
            for(let k = a.length - 1 ; k >= 0; k--){
                for(let n = b.length - 1; n >= 0; n--){
                    if(a[k] === b[n]){
                        localMax++;
                        break;
                    }
                }
            }
            if(localMax>globalMax){
                globalMax = localMax;
            }
            // console.log(b, a, localMax,globalMax);
            if(globalMax === b.length || globalMax === a.length) break;
        }
    }
    else {
        let j =0;
        for(let i = 0; i < b.length; i++){
            a[j] = b[i];
            if(a[j] >= a[j+1]){
                let c = 1;
                for(let m = j+1; m < a.length ; m++){
                    a[m] = a[j] + c;
                    if(a[m + 1] > a[m]) break;
                    c++;
                }
            }
            // console.log(`a = ${a}, b = ${b}`);
            let localMax = 0;
            for(let k = 0 ; k < a.length; k++){
                for(let n = 0; n < b.length; n++){
                    if(a[k] === b[n]){
                        localMax++;
                        break;
                    }
                }

            }
            if(localMax>globalMax){
                globalMax = localMax;
            }
            // console.log(b, a, localMax,globalMax);
            if(globalMax === b.length || globalMax === a.length) break;
        }
    }
    return globalMax;
}

module.exports = count1

'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(data.shift());

    while(testCases--) {
        const [n,m] = readLine().split(' ').map(Number);
        const a = readLine().split(' ').map(Number);
        const b = readLine().split(' ').map(Number);
        const a0 = a.filter(num => num < 0);
        const a1 = a.filter(num => num >= 0);
        const b0 = b.filter(num => num < 0);
        const b1= b.filter(num => num >= 0);
        const a0_filter = a0.filter(num => num >= b0[0]);
        const a1_filter = a1.filter(num => num <= b1[b1.length - 1]);
        console.log(count1(a0_filter, b0,0) + count1(a1_filter, b1,1) );
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function count1(a,b,opt = 0){
    if(a.length === 0) return 0;
    let globalMax = 0;
    if(opt === 0){
        let j = a.length - 1;
        for(let i = b.length - 1; i >= 0; i--){
            a[j] = b[i];
            if(a[j] <= a[j-1]){
                let c = 1;
                for(let m = j-1; m >= 0 ; m--){
                    a[m] = a[j] + c;
                    if(a[m - 1] < a[m]) break;
                    c++;
                }
            }
            // console.log(`a = ${a}, b = ${b}`);
            let localMax = 0;
            for(let k = a.length - 1 ; k >= 0; k--){
                for(let n = b.length - 1; n >= 0; n--){
                    if(a[k] === b[n]){
                        localMax++;
                        break;
                    }
                }
            }
            if(localMax>globalMax){
                globalMax = localMax;
            }
            // console.log(b, a, localMax,globalMax);
            if(globalMax === b.length || globalMax === a.length) break;
        }
    }
    else {
        let j =0;
        for(let i = 0; i < b.length; i++){
            a[j] = b[i];
            if(a[j] >= a[j+1]){
                let c = 1;
                for(let m = j+1; m < a.length ; m++){
                    a[m] = a[j] + c;
                    if(a[m + 1] > a[m]) break;
                    c++;
                }
            }
            // console.log(`a = ${a}, b = ${b}`);
            let localMax = 0;
            for(let k = 0 ; k < a.length; k++){
                for(let n = 0; n < b.length; n++){
                    if(a[k] === b[n]){
                        localMax++;
                        break;
                    }
                }

            }
            if(localMax>globalMax){
                globalMax = localMax;
            }
            // console.log(b, a, localMax,globalMax);
            if(globalMax === b.length || globalMax === a.length) break;
        }
    }
    return globalMax;
}

module.exports = count1

const solve = (box, goal) => {
  let res = 0;

  let mem = {};
  let already = goal.map(() => 0);
  box.forEach(b => (mem[b] = true));
  for (let i = 0; i < goal.length; i++) {
    if (mem[goal[i]]) already[i] = 1;
  }
  for (let i = goal.length - 2; i >= 0; i--) {
    already[i] = already[i + 1] + already[i];
  }
  already.push(0);

  let j = 0;
  for (let i = 0; i < goal.length; i++) {
    while (j < box.length && box[j] - j <= goal[i]) {
      j++;
    }
    let currentRes = 0;
    let l = i,
      r = goal.length - 1;

    while (true) {
      if (l > r) break;
      const m = Math.floor((l + r) / 2);
      if (goal[m] <= goal[i] - 1 + j) {
        currentRes = m;
        l = m + 1;
      } else r = m - 1;
    }
    currentRes = currentRes - i + 1;
    res = Math.max(res, currentRes + already[currentRes + i]);
  }
  return res;
};

const main = () => {
  const start = new Date();
  let test = readInt();
  while (test--) {
    let [n, m] = readListInt();
    const box = readListInt();
    const goal = readListInt();
    const right = solve(box.filter(i => i > 0), goal.filter(i => i > 0));

    const boxLeft = box
      .filter(i => i < 0)
      .map(i => -i)
      .reverse();
    const goalLeft = goal
      .filter(i => i < 0)
      .map(i => -i)
      .reverse();

    const left = solve(boxLeft, goalLeft);
    console.log(left + right);
  }
};

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 => string.trim());
  main();
});

const readLine = () => {
  return inputString[currentLine++];
};

const readInt = () => {
  return parseInt(inputString[currentLine++]);
};

const readListInt = () => {
  return inputString[currentLine++].split(" ").map(s => parseInt(s));
};

const solve = (box, goal) => {
  let mem = {};
  for (let i = 0; i < box.length; i++) {
    mem[box[i]] = true;
  }
  let res = 0;
  for (let i = 0; i < goal.length; i++) {
    if (mem[goal[i]]) res += 1;
  }

  for (let i = 0; i < goal.length; i++) {
    // Try to move to fill goal[i]
    // Find how many boxes we have to push to move to goal[i]
    let l = 0,
      r = box.length;
    let pos = null;
    while (true) {
      if (l > r) break;
      const m = Math.floor((l + r) / 2);
      if (box[m] <= goal[i]) {
        pos = m;
        l = m + 1;
      } else r = m - 1;
    }
    if (pos === null) continue;
    // Boxes now cover from goal[i] to goal[i] + pos
    const coverRange = goal[i] + pos;
    l = i;
    r = goal.length;
    pos = i;
    while (true) {
      if (l > r) break;
      const m = Math.floor((l + r) / 2);
      if (goal[m] <= coverRange) {
        pos = m;
        l = m + 1;
      } else r = m - 1;
    }
    const coverBoxes = pos - i + 1;
    // Calculate already covered goal from pos-th goal
    const already = goal.map(() => 0);
    for (let i = goal.length - 1; i >= 0; i--) {
      if (mem[goal[i]]) already[i] = 1;
    }
    for (let i = goal.length - 2; i >= 0; i--) {
      already[i] = already[i + 1] + already[i];
    }
    already.push(0);

    res = Math.max(res, coverBoxes + already[pos + 1]);
  }

  return res;
};

const main = () => {
  let test = readInt();
  while (test--) {
    const [n, m] = readListInt();
    const box = readListInt();
    const goal = readListInt();
    const left = solve(
      box
        .filter(i => i < 0)
        .map(i => -i)
        .reverse(),
      goal
        .filter(i => i < 0)
        .map(i => -i)
        .reverse()
    );
    const right = solve(box.filter(i => i > 0), goal.filter(i => i > 0));
    console.log(left + right);
  }
};

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 => string.trim());
  main();
});

const readLine = () => {
  return inputString[currentLine++];
};

const readInt = () => {
  return parseInt(inputString[currentLine++]);
};

const readListInt = () => {
  return inputString[currentLine++].split(" ").map(s => parseInt(s));
};

'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(read) {
  const rns = () => {
    return read().split(' ').filter(s => s !== '').map(Number);
  };
  const [n, m] = rns(),
        a = rns(),
        b = rns();
  const calc = () => {
    let sa = 0,
        sb = 0;
    for (; sa < n; sa++) {
      if (a[sa] > 0) break;
    }
    if (sa === n) return 0;
    for (; sb < m; sb++) {
      if (b[sb] > 0) break;
    }
    if (sb === m) return 0;
    let res = 0,
        pre = 0;
    for (let i = m - 1, j = n - 1, k = i; i >= 0; i--) {
      while (a[j] > b[i]) j--;
      if (a[j] === b[i]) {
        pre = 1;
        j--;
        i--;
      }
      if (j < sa || i < sb || i < 0) {
        res = Math.max(res, pre);
        break;
      }
      let num = j - sa + 1;
      for (; k >= 0 && b[i] - b[k] + 1 <= num; k--) {}
      res = Math.max(res, i - k + pre);
    }
    return res;
  };
  let res = calc();
  a.reverse();
  b.reverse();
  for (let i = 0; i < n; i++) a[i] = -a[i];
  for (let i = 0; i < m; i++) b[i] = -b[i];
  res += calc();
  return res;
}

function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < 100) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= 100) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r\n?/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

'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(read) {
  const rns = () => {
    return read().split(' ').filter(s => s !== '').map(Number);
  };
  const [n, m] = rns(),
        a = rns(),
        b = rns();
  const calc = () => {
    let sa = 0,
        sb = 0;
    for (; sa < n; sa++) {
      if (a[sa] > 0) break;
    }
    if (sa === n) return 0;
    for (; sb < m; sb++) {
      if (b[sb] > 0) break;
    }
    if (sb === m) return 0;
    let res = 0,
        pre = 0;
    for (let i = m - 1, j = n - 1, k = i; i >= 0; i--) {
      while (a[j] > b[i]) j--;
      let flag = 0;
      if (a[j] === b[i]) {
        pre = 1;
        j--;
        flag = 1;
      }
      if (j < sa || flag && (i - 1 < sa || !i)) {
        res = Math.max(res, pre);
        break;
      }
      let num = j - sa + 1;
      for (; k >= 0 && b[i] - b[k] - flag < num; k--) {}
      res = Math.max(res, i - k - flag + pre);
    }
    return res;
  };
  let res = calc();
  a.reverse();
  b.reverse();
  for (let i = 0; i < n; i++) a[i] = -a[i];
  for (let i = 0; i < m; i++) b[i] = -b[i];
  res += calc();
  return res;
}

function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < 100) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= 100) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r\n?/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();


David was given a red checkered rectangle of size $$$n \times m$$$. But he doesn't like it. So David cuts the original or any other rectangle piece obtained during the cutting into two new pieces along the grid lines. He can do this operation as many times as he wants.As a result, he will get a set of rectangles. Rectangles $$$1 \times 1$$$ are forbidden.David also knows how to paint the cells blue. He wants each rectangle from the resulting set of pieces to be colored such that any pair of adjacent cells by side (from the same piece) have different colors.What is the minimum number of cells David will have to paint?

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The next lines contain descriptions of test cases. The only line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n, m \leq 3 \cdot 10^4$$$, $$$n \cdot m \geq 2$$$).

For each test case print a single integer — the minimum number of cells David will have to paint blue.

NoteThe following pictures show how the initial rectangle can be split and cells colored blue.In the first test case:  In the second test case:  In the third test case:  In the fourth test case:

const readline = require('readline')

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

function solve(n, m) {
    // return Math.floor(n * m / 3) + ((n * m % 3) ? 1 : 0)
    if (n > m) return solve(m, n)
    // n < m
    if (!(n % 3) || !(m % 3)) return m * n / 3
    if (n === 1) return Math.floor(m / 3) + ((m % 3) ? 1 : 0)
    if (n === 2) return n * Math.floor(m / 3) + (m % 3)
    const r = n % 3
    return solve(n - r, m) + solve(r, m)
}

//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] = BigInt(next());
		}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 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 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 size = N * M;
		if(size % 3 == 0){
			myout(size / 3);
		}else{
			myout(Math.ceil(size / 3));
		}
	}
}

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 a = k[0], b = k[1];
        var ans = (a * b + 2) / 3;
        console.log(Math.floor(ans));
    }
});

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 a = k[0], b = k[1];
        var ans = (a * b + 2) / 3;
        console.log(Math.floor(ans));
    }
});

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [h, w] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (h < 2) console.log(Math.ceil(w / 3));
    else if (w < 2) console.log(Math.ceil(h / 3));
    else {
      console.log(Math.ceil((h * w) / 3));
    }
  }
};
solve();

'use strict';
const readline = require('readline');
const util = require('util');
const rl = readline.createInterface({
    input: process.stdin,
});
let pos = 0;
const words = [];
rl.on('line', (line) => {
    words.push.apply(words, line.split(' ').filter(s => s != ''));
});
rl.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(words[pos++]));
}
function nextStr() {
    return words[pos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
let n;
let m;
function solve() {
    if ((n % 3) == 0) {
        return m * Math.trunc(n / 3);
    }
    if ((m % 3) == 0) {
        return n * Math.trunc(m / 3);
    }
    let q1 = (n - n % 3) * (m - m % 3);
    let sum = Math.trunc(q1 / 3);
    let q2 = (m % 3) * (n - n % 3);
    sum += Math.trunc(q2 / 3);
    let q3 = (n % 3) * (m - m % 3);
    sum += Math.trunc(q3 / 3);
    let q4 = (n % 3) * (m % 3);
    sum += Math.max(1, Math.trunc(q4 / 2));
    return sum;
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        n = nextInt();
        m = nextInt();
        printf("%d\n", solve());
    }
}

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

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

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

// ********** Code Start **********
function main() {
  let a = parseInt(readline())
  while(a--){
    var b = readline().split(' ').map(Number)
    var c = ((b[0] * b[1]) + 2) / 3
    print(Math.floor(c))
  }
}

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

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

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

// ********** Code Start **********
function main() {
  var a = parseInt(readline())
  while(a--){
    var b = readline().split(' ').map(Number)
    var c = ((b[0] * b[1]) + 2) / 3
    print(Math.floor(c))
  }
}

var t = readline();

for (var i = 0; i < t; i++) {
  var n = readline().split(' ').map(Number);
  var ans;

  ans = Math.ceil((n[0] * n[1]) / 3);
  print(ans);

}

const readline = require('readline')

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

function solve(n, m) {
    // return Math.floor(n * m / 3) + ((n * m % 3) ? 1 : 0)
    if (n > m) return solve(m, n)
    // n < m
    if (!(n % 3) || !(m % 3)) return m * n / 3
    if (n === 1 || n === 2) return n * (Math.floor(m / 3) + ((m % 3) ? 1 : 0))
    const r = n % 3
    return solve(n - r, m) + solve(r, m)
}

const readline = require('readline')

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

function solve(n, m) {
    if (n > m) return solve(m, n)
    // n < m
    if (n & 1) {
        if (n === 1) {
            if (m === 1) return 0
            if (m === 2) return 1
            if (m % 3) {
                return Math.floor(m / 3) - 1 + 2
            } else {
                return Math.floor(m / 3)
            }
        }
        if (m & 1) {
            return Math.min(n * solve(1, m), m * solve(1, n))
        } else {
            return solve(n, m - 1) + solve(n, 1)
        }
    } else {
        if (n === 2 && m === 2) return 2
        if (m & 1) {
            return solve(n - 1, m) + solve(1, m)
        } else {
            return solve(n - 1, m - 1) + solve(1, n) + solve(1, m - 1)
        }
    }
}

const readline = require('readline')

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

function solve(n, m) {
    if (n > m) return solve(m, n)
    // n < m
    if (n & 1) {
        if (n === 1) {
            if (m === 1) return 0
            if (m === 2) return 1
            return Math.floor(m / 3) + (m % 3 ? solve(n, m % 3) : 0)
        }
        if (m & 1) {
            return Math.min(n * solve(1, m), m * solve(1, n))
        } else {
            return solve(n, m - 1) + solve(n, 1)
        }
    } else {
        if (n === 2 && m === 2) return 2
        if (m & 1) {
            return solve(n - 1, m) + solve(1, m)
        } else {
            return solve(n - 1, m - 1) + solve(1, n) + solve(1, m - 1)
        }
    }
}

const readline = require('readline')

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

function solve(n, m) {
    if (n > m) return solve(m, n)
    // n < m
    if (n & 1) {
        if (n === 1) return Math.floor(m / 2)
        if (m & 1) {
            return m * Math.floor(n / 2)
        } else {
            const h = m / 2
            return h & 1
                ? 2 * solve(n, h)
                : solve(n, h - 1) + solve(n, h + 1)
        }
    } else {
        const h = n / 2
        // if (m & 1) {
            return h & 1
                ? 2 * solve(h, m)
                : solve(h - 1, m) + solve(h + 1, m)
        // } else {
        // }
    }
}

const readline = require('readline')

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

function solve(n, m) {
    return Math.min(solve2(n, m), solve1(n, m))
}
function solve2(n, m) {
    if (n > m) return solve2(m, n)
    // n < m
    if (n & 1) {
        if (m & 1) {
            if (n === 1) return Math.floor(m / 2)
            return m * Math.floor(n / 2)
        } else {
            if (n === 1) {
                if (m === 2) return 1
                if (m === 4) return 2
                const h = m / 2
                return h & 1
                    ? 2 * solve2(n, h)
                    : solve2(n, h - 1) + solve2(n, h + 1)
            }
            return m * Math.floor(n / 2)
        }
    } else {
        if (m & 1) {
            return n * Math.floor(m / 2)
        } else {
            const h = m / 2
            return h & 1 ? 2 * solve2(n, h) : solve2(n, h - 1) + solve2(n, h + 1)
        }
    }
}
function solve1(n, m) {
    if (n > m) return solve1(m, n)
    // n < m
    if (n & 1) {
        if (m & 1) {
            if (n === 1) return Math.floor(m / 2)
            return m * Math.floor(n / 2)
        } else {
            if (m === 2) return 1 // 1 2
            return 2 * solve1(n, m / 2)
        }
    } else {
        if (m & 1) {
            return n * Math.floor(m / 2)
        } else {
            if (m === 2) return 2 // 2 2
            return solve1(n, m / 2 - 1) + solve1(n, m / 2 + 1)
        }
    }
}

const readline = require('readline')

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

function solve(n, m) {
    if (n > m) return solve(m, n)
    // n < m
    if (n & 1) {
        if (m & 1) {
            if (n === 1) return Math.floor(m / 2)
            return m * Math.floor(n / 2)
        } else {
            if (n === 1) {
                if (m === 2) return 1
                if (m === 4) return 2
                const h = m / 2
                return h & 1
                    ? 2 * solve(n, h)
                    : solve(n, h - 1) + solve(n, h + 1)
            }
            return m * Math.floor(n / 2)
        }
    } else {
        if (m & 1) {
            return n * Math.floor(m / 2)
        } else {
            const h = m / 2
            return h & 1 ? 2 * solve(n, h) : solve(n, h - 1) + solve(n, h + 1)
        }
    }
}

const readline = require('readline')

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

function solve(n, m) {
    if (n > m) return solve(m, n)
    // n < m
    if (n & 1) {
        if (m & 1) {
            if (n === 1) return Math.floor(m / 2)
            return m * Math.floor(n / 2)
        } else {
            if (m === 2) return 1 // 1 2
            return 2 * solve(n, m / 2)
        }
    } else {
        if (m & 1) {
            return n * Math.floor(m / 2)
        } else {
            if (m === 2) return 2 // 2 2
            return solve(n, m / 2 - 1) + solve(n, m / 2 + 1)
        }
    }
}

const readline = require('readline')

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

function solve(n, m) {
    if (n > m) return solve(m, n)
    // n < m
    if (n & 1) {
        if (n === 1) return Math.floor(m / 2)
        if (m & 1) {
            return m * Math.floor(n / 2)
        } else {
            return 2 * solve(n, m / 2)
        }
    } else {
        if (m & 1) {
            return n * Math.floor(m / 2)
        } else {
            return 2 * solve(n, m / 2)
        }
    }
}

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 a = k[0], b = k[1];
        var ans = a * b + (2 / 3);
        console.log(Math.floor(ans));
    }
});

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 a = k[0], b = k[1];
        var ans = a * b + 2 / 3;
        console.log(Math.floor(ans));
    }
});

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 a = k[0], b = k[1];
        var ans = a * b + 2 / 3;
        console.log(Math.floor(ans));
    }
});

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 a = k[1], b = k[2];
        var ans = ((a * b) + 2) / 3;
        console.log(Math.floor(ans));
    }
});

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 a = k[1], b = k[1];
        var ans = ((a * b) + 2) / 3;
        console.log(Math.floor(ans));
    }
});

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 a = k[0], b = k[1];
        var ans = ((a * b) + 2) / 3;
        console.log(Math.floor(ans));
    }
});

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 a = k[0], b = k[1];
        var ans = ((a * b) + 2) / 3;
        console.log((ans));
    }
});

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 a = k[0], b = k[1];
        var ans = ((a * b) + 2) / 3;
        console.log(Math.floor(ans));
    }
});

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [h, w] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (h < 2) console.log(Math.ceil(w / 3));
    else if (w < 2) console.log(Math.ceil(w / 3));
    else {
      console.log(Math.ceil((h * w) / 3));
    }
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [h, w] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (h < 2) console.log(Math.ceil(w / 3));
    else if (w < 2) console.log(Math.ceil(w / 3));
    else {
      let t1 = Math.ceil(h / 3) * w;
      let t2 = Math.ceil(w / 3) * h;
      console.log(Math.min(t1, t2));
    }
  }
};
solve();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}

const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [h, w] = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (h < 2) console.log(Math.floor(w / 2));
    else if (w < 2) console.log(Math.floor(h / 2));
    else {
      let t1 = Math.floor(h / 2) * w;
      let t2 = Math.floor(w / 2) * h;
      console.log(Math.min(t1, t2));
    }
  }
};
solve();