Sam is a kindergartener, and there are $$$n$$$ children in his group. He decided to create a team with some of his children to play "brawl:go 2".Sam has $$$n$$$ power-ups, the $$$i$$$-th has type $$$a_i$$$. A child's strength is equal to the number of different types among power-ups he has.For a team of size $$$k$$$, Sam will distribute all $$$n$$$ power-ups to $$$k$$$ children in such a way that each of the $$$k$$$ children receives at least one power-up, and each power-up is given to someone.For each integer $$$k$$$ from $$$1$$$ to $$$n$$$, find the minimum sum of strengths of a team of $$$k$$$ children Sam can get.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$).  The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — types of Sam's power-ups. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For every test case print $$$n$$$ integers. The $$$k$$$-th integer should be equal to the minimum sum of strengths of children in the team of size $$$k$$$ that Sam can get.

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

let inputString = '';

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

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

    main(inputString);
});

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

function main(fileContents) {//input lines as an array
    // console.log(fileContents);
    fileContents.splice(0,1);

    for(let i = 0; i < fileContents.length; i+=2){
        const setDiff = new Set()
        const powerUps = fileContents[i+1]
        // console.log("powerUps",powerUps)
        const splitPow = powerUps.split(" ")

        splitPow.forEach(type => {
            if(!setDiff.has(type)) {
                setDiff.add(type)
            }
        })

        let output = []

        for(let k = 1; k <= splitPow.length; k++){
            const add = k <= setDiff.size ? setDiff.size : k
            output.push(add)

        }

        console.log(output.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];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var a = lines[i].split(' ').map(Number);
            var m = new Map();
            var h = [];
            for(j = 0; j < n; j++){
                if(m.get(a[j]) === 0){
                    m.set(a[j], 1);
                }else{
                    var temp = m.get(a[j]);
                    temp++;
                    m.set(a[j], temp);
                }
            }
            for(j = 1; j <= n; j++){
                if(j <= m.size){
                    h.push(m.size);
                }else{
                    var x = h[h.length - 1];
                    h.push(x + 1);
                }
            }
            var ans = '';
            for(j = 0; j < h.length; j++){
                ans += h[j] + ' ';
            }
            console.log(ans);
        }
    }
});

'use strict';

function solve(n, a) {
  const size = new Set(a).size;
  const res = new Array(n);
  for (let i = 0; i < size; i++) {
    res[i] = size;
  }
  for (let i = size; i < n; i++) {
    var _res;
    res[i] = ((_res = res[i - 1]) !== null && _res !== void 0 ? _res : 0) + 1;
  }
  return res.join(' ');
}

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

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

'use strict';
const { throws } = require('assert');

 /*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 MOD = 1e9+7;

const calc = (n, arr)=>{
  let ans = [];
  arr.sort((a,b)=>a-b);
  let cnt = new Map();
  for (let i=0; i<n; i++){
    cnt.set(arr[i], (cnt.get(arr[i])||0)+1);
  }
  let ded = 0;
  for (let [k, v] of cnt){
    ded += v-1;
  }
  //l(arr, ded, cnt)
  let nn = n;
  for (let i=0; i<n; i++){
    ans.push(nn);
    if (--ded>=0)
      nn--;
  }
  l('ans')
  return ans.reverse();
};

function main() {
    let T = +readline()
    while (T--){
      let n = +readline()
      let arr = ra();
      print(calc(n, arr).join(' '));
    }
}

E.calc = calc;

var t = readline();

for (var i = 0; i < t; i++) {
  var n = readline();
  var k = readline().split(' ').map(Number);
  var len = Array.from(new Set(k)).length;
  var res = k.map((el, i) => Math.max(i + 1, len)).join(' ');
  print(res);
}

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

let inputString = '';

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

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

    main(inputString);
});

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

function main(fileContents) {//input lines as an array
    // console.log(fileContents);
    fileContents.splice(0,1);

    for(let i = 0; i < fileContents.length; i+=2){
        const setDiff = new Set()
        const powerUps = fileContents[i+1]
        console.log("powerUps",powerUps)
        powerUps.split(" ").forEach(type => {
            setDiff.add(type)
        })

        let output = ""

        for(let k = 1; k <= powerUps.split(" ").length; k++){
            const add = k <= setDiff.size ? setDiff.size : k
            output+=add
            if(powerUps.length != k){
                output+=" "
            }

        }

        console.log(output)
    }

}


You have $$$n$$$ rectangles, the $$$i$$$-th rectangle has height $$$h_i$$$ and width $$$w_i$$$.You are asked $$$q$$$ queries of the form $$$h_s \ w_s \ h_b \ w_b$$$. For each query output, the total area of rectangles you own that can fit a rectangle of height $$$h_s$$$ and width $$$w_s$$$ while also fitting in a rectangle of height $$$h_b$$$ and width $$$w_b$$$. In other words, print $$$\sum h_i \cdot w_i$$$ for $$$i$$$ such that $$$h_s < h_i < h_b$$$ and $$$w_s < w_i < w_b$$$. Please note, that if two rectangles have the same height or the same width, then they cannot fit inside each other. Also note that you cannot rotate rectangles.Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case two integers $$$n, q$$$ ($$$1 \leq n \leq 10^5$$$; $$$1 \leq q \leq 10^5$$$) — the number of rectangles you own and the number of queries. Then $$$n$$$ lines follow, each containing two integers $$$h_i, w_i$$$ ($$$1 \leq h_i, w_i \leq 1000$$$) — the height and width of the $$$i$$$-th rectangle. Then $$$q$$$ lines follow, each containing four integers $$$h_s, w_s, h_b, w_b$$$ ($$$1 \leq h_s < h_b,\ w_s < w_b \leq 1000$$$) — the description of each query. The sum of $$$q$$$ over all test cases does not exceed $$$10^5$$$, and the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output $$$q$$$ lines, the $$$i$$$-th line containing the answer to the $$$i$$$-th query.

Note  In the first test case, there is only one query. We need to find the sum of areas of all rectangles that can fit a $$$1 \times 1$$$ rectangle inside of it and fit into a $$$3 \times 4$$$ rectangle.Only the $$$2 \times 3$$$ rectangle works, because $$$1 < 2$$$ (comparing heights) and $$$1 < 3$$$ (comparing widths), so the $$$1 \times 1$$$ rectangle fits inside, and $$$2 < 3$$$ (comparing heights) and $$$3 < 4$$$ (comparing widths), so it fits inside the $$$3 \times 4$$$ rectangle. The $$$3 \times 2$$$ rectangle is too tall to fit in a $$$3 \times 4$$$ rectangle. The total area is $$$2 \cdot 3 = 6$$$.

var t = parseInt(readline());

for (var test = 0; test < t; test++) {
    var inp = readline().split(' ');
    var n = inp[0];
    var q = inp [1];

    var matr = [];
    for (var i = 0; i < 1001; i++) {
        matr.push(new Array(1001).fill(0));
    }

    for (var i = 0; i < n; i++) {
        var rect = readline().split(' ');
        matr[rect[0]][rect[1]] += rect[0] * rect[1];
    }

    var s = matr;
    for (var i = 1; i < 1001; i++) {
        for (var j = 1; j < 1001; j++) {
            s[i][j] = s[i-1][j] + s[i][j-1] - s[i-1][j-1] + s[i][j];
        }
    }

    for (var i = 0; i < q; i++) {
        var query = readline().split(' ');
        var hs = query[0] - (-1);
        var ws = query[1] - (-1);
        var hb = query[2] - 1;
        var wb = query[3] - 1;

        if (hs > hb || ws > wb) {
            print(0);
        } else {
            var ans = s[hb][wb] - s[hs-1][wb] - s[hb][ws-1] + s[hs-1][ws-1];

            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, q] = lines[l++].trim().split(' ').map(Number)
        const arr = lines.slice(l, l + n).map(str => str.trim().split(' ').map(Number))
        l += n
        const qs = lines.slice(l, l + q).map(str => str.trim().split(' ').map(Number))
        l += q
        output[i] = solve(n, arr, qs)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr, qs) {
    const gs = Array(1001).fill(0).map(() => [])
    arr.forEach(([h, w]) => {
        gs[h].push(w)
    })
    for (let i = 0; i < gs.length; i++) {
        gs[i].sort((a, b) => a - b)
        const sum = []
        if (gs[i].length) {
            sum[0] = gs[i][0]
            for (let j = 1; j < gs[i].length; j++) {
                sum[j] = sum[j - 1] + gs[i][j]
            }
        }
        gs[i].sum = sum
    }
    // console.log(gs[999])
    const query = []
    qs.forEach(([hs, ws, hb, wb], i) => {
        query.push([hs, -1, i])
        query.push([hb - 1, 1, i])
    })
    // console.log(query)
    const ans = Array(qs.length).fill(0)
    const F = Array(1e3 + 5).fill(0) // a little larger in case
    let hnow = 0
    query.sort((a, b) => a[0] - b[0])
        .forEach(([h, d, i]) => {
        while (hnow < h) {
            hnow++
            gs[hnow].forEach(w => {
                inc(F, w, w * hnow)
            })
        }
        // console.log(hnow)
        const [hs, ws, hb, wb] = qs[i]
        if (wb - 1 > ws) {
            ans[i] += d * (sum(F, wb - 1) - sum(F, ws))
        }
        // console.log(ans[i], F.slice(0, 6), sum(F, wb - 1), sum(F, ws))
    })
    return ans.join('\n')
}
function inc(F, idx, val) {
    for (; idx < F.length; idx |= idx + 1) {
        F[idx] += val
    }
}
function sum(F, idx) {
    let s = 0
    for (; idx >= 0; idx = (idx & (idx + 1)) - 1) {
        s += F[idx]
    }
    return s
}

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, q] = lines[l++].trim().split(' ').map(Number)
        const arr = lines.slice(l, l + n).map(str => str.trim().split(' ').map(Number))
        l += n
        const qs = lines.slice(l, l + q).map(str => str.trim().split(' ').map(Number))
        l += q
        output[i] = solve(n, arr, qs)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr, qs) {
    const gs = Array(1001).fill(0).map(() => [])
    arr.forEach(([h, w]) => {
        gs[h].push(w)
    })
    for (let i = 0; i < gs.length; i++) {
        gs[i].sort((a, b) => a - b)
        const sum = []
        if (gs[i].length) {
            sum[0] = gs[i][0]
            for (let j = 1; j < gs[i].length; j++) {
                sum[j] = sum[j - 1] + gs[i][j]
            }
        }
        gs[i].sum = sum
    }
    // console.log(gs[999])
    return qs.map(([hs, ws, hb, wb]) => {
        let r = 0
        for (let h = hs + 1; h < hb; h++) {
            if (!gs[h].length) continue
            const i = binarySearch(0, gs[h].length - 1, x => {
                return !(ws < gs[h][x])
            }) + 1
            const j = binarySearch(0, gs[h].length - 1, x => {
                return gs[h][x] < wb
            })
            // r += j - i + 1
            // console.log(i, j, gs[h])
            r += h * range(gs[h].sum, i, j)
        }
        return r
    }).join('\n')
    //
    function range(sum, i, j) {
        return sum[j] - (sum[i - 1] || 0)
    }
}
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
}


A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect.For example:   If x = 6 and the crossword is 111011, then its encoding is an array {3, 2};  If x = 8 and the crossword is 01101010, then its encoding is an array {2, 1, 1};  If x = 5 and the crossword is 11111, then its encoding is an array {5};  If x = 5 and the crossword is 00000, then its encoding is an empty array. Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!

The first line contains two integer numbers n and x (1 ≤ n ≤ 100000, 1 ≤ x ≤ 109) — the number of elements in the encoding and the length of the crossword Mishka picked. The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 10000) — the encoding.

Print YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO.

s=readline().split(' ')
n=+s[0]
x=+s[1]
sum=0
a=readline().split(' ').map(function(q){sum+=+q;})
if (sum+n==x+1)
{
    print("YES")
}
else
{
    print("NO")
}

var n_x =readline().split(' ');
var sum=0;
readline().split(' ').map(q=>sum+=Number(q));
print(sum+Number(n_x[0])-1==Number(n_x[1])?"Yes":"No");

var n_x =readline().split(' ');
var sum=0;
readline().split(' ').map(q=>sum+=(q));
print(sum+(n_x[0])-1==(n_x[1])?"Yes":"No");


There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.

The first line contains two positive space-separated integers, n and k (1 ≤ k ≤ n ≤ 2·105) — the initial number of cities in Westeros and the number of cities at which the game ends.  The second line contains n space-separated positive integers ai (1 ≤ ai ≤ 106), which represent the population of each city in Westeros.

Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins.

NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins.

function out_str(x) {
    if( x == 1 )
    return "Stannis";
    else
    return "Daenerys";
}
function run(N, K, odd, even) {
    if( K == N )
        if( odd % 2 == 1 )
        return 1;
    else
        return 0;
    if( even == 0 ) {
        if( K % 2 == 0 )
            return 0;
        return 1;
    }
    if( odd == 0 ) {
        return 0;
    }
    if( K + 1 == N ) {
        return 1;
    }
    var D = (N - K);
    if( D % 2 == 0 )
    D = D / 2;
    else
    D = (D - 1) / 2;
    var S = (N - K) - D;
    if( D >= odd ) {
        return 0;
    }
    if( D >= even ) {
        if( K % 2 == 0 )
            return 0;
    }
    if( S >= even ) {
        if( K % 2 == 1 )
            return 1;
    }
    if( S > D )
        return 1;
    return 0;
}
var line = readline().split(' ');
var N = parseInt(line[0]), K = parseInt(line[1]);
var numbers = readline().split(" ").map(function(x) { return parseInt(x); });
var odd = 0, even = 0;
for(var i = 0; i < N; i ++) {
    if( numbers[i] % 2 == 0 )
        even ++;
    else
        odd ++;
}
//print(odd, even);
print(out_str(run(N, K, odd, even)));

function out_str(x) {
    if( x == 1 )
	return "Stannis";
    else
	return "Daenerys";
}
function run(N, K, odd, even) {
    if( K == N )
        return odd & 1;
    if( even == 0 ) {
        if( K % 2 == 0 )
            return 0;
        return 1;
    }
    if( odd == 0 ) {
        return 0;
    }
    if( K + 1 == N ) {
        return 1;
    }
    var D = (N - K) / 2;
    var S = (N - K) - D;
    if( D >= odd ) {
        return 0;
    }
    if( D >= even ) {
        if( K % 2 == 0 )
            return 0;
    }
    if( S >= even ) {
        if( K % 2 == 1 )
            return 1;
    }
    if( S > D )
        return 1;
    return 0;
}
var line = readline().split(' ');
var N = parseInt(line[0]), K = parseInt(line[1]);
var numbers = readline().split(" ").map(function(x) { return parseInt(x); });
var odd = 0, even = 0;
for(var i = 0; i < N; i ++) {
	if( numbers[i] % 2 == 0 )
		even ++;
	else
		odd ++;
}
print(out_str(run(N, K, odd, even)));


Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 × 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square.The morning has come. All n alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game:  First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal.  Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off. Inna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!

The first line of the input contains integer n (1 ≤ n ≤ 105) — the number of the alarm clocks. The next n lines describe the clocks: the i-th line contains two integers xi, yi — the coordinates of the i-th alarm clock (0 ≤ xi, yi ≤ 100). Note that a single point in the room can contain any number of alarm clocks and the alarm clocks can lie on the sides of the square that represents the room.

In a single line print a single integer — the minimum number of segments Inna will have to draw if she acts optimally.

NoteIn the first sample, Inna first chooses type "vertical segments", and then she makes segments with ends at : (0, 0), (0, 2); and, for example, (1, 0), (1, 1). If she paints horizontal segments, she will need at least 3 segments.In the third sample it is important to note that Inna doesn't have the right to change the type of the segments during the game. That's why she will need 3 horizontal or 3 vertical segments to end the game.

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

let count = 0;
let linesCount = 0;
const lines = [];
rl.on('line', (line) => {
    if (count != linesCount - 1) {
        if (linesCount == 0) {
            linesCount = parseInt(line);
        } else {
            lines.push(line.split(' '));
            count++;
        }
    } else {
        lines.push(line.split(' '));
        const linesData = {
            x: [],
            y: []
        }
        for (let i = 0; i < lines.length; i++) {
            if (linesData.x.indexOf(lines[i][0]) == -1) linesData.x.push(lines[i][0])
            if (linesData.y.indexOf(lines[i][1]) == -1) linesData.y.push(lines[i][1])
        }
        console.log(linesData.x.length >= linesData.y.length ? linesData.y.length : linesData.x.length);
    }
})

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

let count = 0;
let linesCount = 0;
const lines = [];
rl.on('line', (line) => {
    if (count != linesCount - 1) {
        if (linesCount == 0) {
            linesCount = parseInt(line);
        } else {
            lines.push(line.split(' '));
            count++;
        }
    } else {
        lines.push(line.split(' '));
        const xes = [];
        const ys = [];
        for (let i = 0; i < lines.length; i++) {
            if (xes.indexOf(lines[i][0]) == -1) xes.push(lines[i][0])
            if (ys.indexOf(lines[i][1]) == -1) ys.push(lines[i][1])
        }
        console.log(xes.length >= ys.length ? ys.length : xes.length);
    }
})

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

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

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

function main() {
	var pointNum = parseInt(readline());
	var xLine = [], yLine = [];
	for (var i = 0; i < 101; ++i) {
		xLine.push(0);
		yLine.push(0);
	}

	for (var i = 0; i < pointNum; ++i) {
		var point = tokenizeIntegers(readline());
		var x = point[0], y = point[1];
		xLine[x] = 1;
		yLine[y] = 1;
	}

	var xSum = 0, ySum = 0;
	for (var i = 0; i < 101; ++i) {
		xSum += xLine[i];
		ySum += yLine[i];
	}
	print(Math.min(xSum, ySum));
}

main();


Pak Chanek has a prime number$$$^\dagger$$$ $$$n$$$. Find a prime number $$$m$$$ such that $$$n + m$$$ is not prime.$$$^\dagger$$$ A prime number is a number with exactly $$$2$$$ factors. The first few prime numbers are $$$2,3,5,7,11,13,\ldots$$$. In particular, $$$1$$$ is not a prime number.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The only line of each test case contains a prime number $$$n$$$ ($$$2 \leq n \leq 10^5$$$).

For each test case, output a line containing a prime number $$$m$$$ ($$$2 \leq m \leq 10^5$$$) such that $$$n + m$$$ is not prime. It can be proven that under the constraints of the problem, such $$$m$$$ always exists. If there are multiple solutions, you can output any of them.

NoteIn the first test case, $$$m = 2$$$, which is prime, and $$$n + m = 7 + 2 = 9$$$, which is not prime.In the second test case, $$$m = 7$$$, which is prime, and $$$n + m = 2 + 7 = 9$$$, which is not prime.In the third test case, $$$m = 47837$$$, which is prime, and $$$n + m = 75619 + 47837 = 123456$$$, which is not prime.

length = +readline();

while (length--) {
    n = +readline();

    print(7);
}

length = +readline();

while (length--) {
    n = +readline();

    if (n === 2) {
        print(7);
        continue;
    }

    print(3);
}

var n = readline();
for(var i=0;i<n;i++){
  var num = readline();
  if(num%2===0){
    print(2);
  } else {
    print(3);
  }
}

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 n=parseInt(line[i]);
        if(n===2) console.log(2);
        else console.log(3);
    }
})

/*
* auther yeling
*
*
*/
'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 print(str) {
    console.log(str);
}

// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();
// testOutput();

function begin(n) {
    if(n == 2) {
        print(2);
    } else {
        print(3);
    }
}

function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = parseInt(readline(), 10);
        begin(n);
    }
}

'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 [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn();
  if (n === 2) return 2;
  return 3;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      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);
}();

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

function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
function abs(x) {
  return x < 0 ? x*(-1) : x;
}

var T = readline();
var inf = 1000000000000;
for(var tc=1;tc<=T;tc++) {
    var t = readline();
    console.log(t);
}

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

// your code goes here

// declare global variables
var input_stdin = "";
var lines = "";
var input_currentline = 0;

// standard input is stored into input_stdin
process.stdin.on('data', function (data) {
    input_stdin += data;
});

// standard input is done and stored into an array
process.stdin.on('end', function () {
    lines = input_stdin.split("\n");
    start();
});

function start() {
    t = parseInt(lines[0])
    let line = 1
    for (let i = 1; i <= t; i++) {
        const n = parseInt(lines[line].split(' ')[0], 10)

        console.log(n % 2 == 0 ? 2 : 3);
        line++
    }
}

length = +readline();

while (length--) {
    n = +readline();

    if (n === 2) {
        print(7);
        break;
    }

    print(3);
}

length = +readline();

while (length--) {
    n = +readline();

    if (n === 2) {
        print(7);
        break
    }

    print(3)
}

length = +readline();

while (length--) {
    n = +readline();
    m = 3;

    print(m);
}

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 n=parseInt(line[i]);
        if(n===2) console.log(4);
        else console.log(3);
    }
})

/*
* auther yeling
*
*
*/
'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 print(str) {
    console.log(str);
}

// const { readline, print, testOutput } = require('@ip-algorithmics/codeforces-io');
// main();
// testOutput();

function begin(n) {
    if(n == 2) {
        print(n+2);
    } else {
        print(n+3);
    }

}

function main() {
    var caseNum = parseInt(readline(), 10);
    for (var i = 0; i < caseNum; i++) {
        var n = parseInt(readline(), 10);
        begin(n);
    }
}

'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 [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn();
  if (n === 2) return 2;
  return n + 1;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      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);
}();


You have an array $$$a$$$ of length $$$n$$$. You can exactly once select an integer $$$len$$$ between $$$1$$$ and $$$n - 1$$$ inclusively, and then sort in non-decreasing order the prefix of the array of length $$$len$$$ and the suffix of the array of length $$$n - len$$$ independently.For example, if the array is $$$a = [3, 1, 4, 5, 2]$$$, and you choose $$$len = 2$$$, then after that the array will be equal to $$$[1, 3, 2, 4, 5]$$$.Could it be that after performing this operation, the array will not be sorted in non-decreasing order?

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^4$$$) — the length of the array. The second line of the test case contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case of input data, output "YES" (without quotes), if the array may be not sorted in non-decreasing order, output "NO" (without quotes) otherwise. You can output each letter in any case (uppercase or lowercase).

NoteIn the first test case, it's possible to select $$$len = 1$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[2, 1, 2]$$$.In the second test case, it's possible to select $$$len = 3$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[1, 2, 3, 1]$$$.In the third test case, the array will be sorted in non-decreasing order for every possible $$$len$$$.

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

var T = readline();
for(var q=1;q<=T;q++) {
            var n = readline();
            var a = readline().split(" ").map(w => parseInt(w))
            var inf = 100000000000;
            var nef = -100000000000;
            var mn = []
            //var mx = []
            for(var i=a.length-1;i>=0;i--) {
            	mn[i] = Math.min(inf, a[i])
            	//mx[i] = Math.max(nef, a[i])
            }
            inf = 1000000000000;
            nef = -1000000000000;
            var ans = true;
            for(var i=0;i<a.length;i++) {
            	inf = Math.min(inf, a[i])
            	nef = Math.max(nef, a[i])
            	if(nef > mn[i]) {
            		ans = false;
            		break;
            	}
            }
            console.log(ans ? 'NO' : 'YES');
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

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

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

        let dec = false;
        for (let i = 1; i < arr.length; i++) {
            if (arr[i] < arr[i-1]) dec=  true;
        }
        output(dec ? 'YES' : 'NO');
    }
}

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    var e = 0;
    for(var j = 1; j <= n * 2; j++){
        if(j % 2 == 1){
            e = lines[j];
        }else{
            var yes = true;
            var k = lines[j].split(' ').map(Number);
            for(var l = 1; l < e; l++){
                if(k[l] < k[l - 1]){
                    yes = false;
                }
            }
            if(yes === true){
                console.log('NO');
            }else{
                console.log('YES');
            }
        }
    }
});

var t = readline()
while(t--) {
     var test = readline()
     var test1 = readline().split(' ')
    print(taskContext1(test1))

}

function taskContext1(arr) {

      var test = arr.slice(0);
  arr.sort((a,b) => a-b);
  for(var i = 0; i<arr.length; i++){
    if (test[i] != arr[i]){
      return 'Yes'
    }
  }

  return 'No'

}

var t = +readline()
for(var index = 0; index<t; index += 1){
     var test = readline().split(' ')
     var test1 = readline().split(' ')
//     var a = +test[0]
//     var b = +test[1]
//     var c = +test[2]
    print(taskContext1(test1))

}

function taskContext1(arr) {

      var test = arr.slice(0);
  arr.sort((a,b) => a-b);
  for(var i = 0; i<arr.length; i++){
    if (test[i] != arr[i]){
      return 'Yes'
    }
  }

  return 'No'

}

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

var T = readline();
for(var q=1;q<=T;q++) {
            var n = readline();
            var ar = readline().split(" ").map(w => parseInt(w))
            var f = []
            var s = []
            for(var i=1;i<n;i++) f.push(ar[i])
            for(var i=0;i<n-1;i++) s[i]=ar[i]
            f.sort(function(a,b) { return a-b })
            s.sort(function(a,b) { return a-b })
            var ans = false;
            if(ar[0]<=f[0] || s[n-2]<=ar[n-1]) ans = true;
            console.log(ans ? 'NO' : 'YES');
}

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

var T = readline();
for(var q=1;q<=T;q++) {
            var n = readline();
            var ar = readline().split(" ").map(w => parseInt(w))
            var f = []
            var s = []
            for(var i=1;i<n;i++) f.push(ar[i])
            for(var i=0;i<n-1;i++) s[i]=ar[i]
            f.sort(function(a,b) { return a-b })
            s.sort(function(a,b) { return a-b })
            var ans = false;
            if(ar[0]<=f[0] || s[n-1]<=ar[n]) ans = true;
            console.log(ans ? 'NO' : 'YES');
}

var str = +readline()
for(var i = 0; i<str; i+=1){
    var testArr = readline().split(' ')
    print(sortArr(testArr))
}

function sortArr(arr) {
var len = [...arr]
arr.sort((a,b) => a-b);
  for(var i = 0; i<arr.length; i++){
    if (len[i] !== arr[i]){
      return 'YES'
    }
  }
return 'NO'
}

var str = +readline()
for(var i = 0; i<str; i++){
    var testArr = readline().split(' ')
   print(sortArr(testArr))
}

function sortArr(arr) {
var len = [...arr]
arr.sort((a,b) => a-b);
print(len)
  for(var i = 0; i<arr.length; i++){
    if (len[i] !== arr[i]){
      return 'YES'
    }
  }
  return 'NO'
}


There are $$$n$$$ boxers, the weight of the $$$i$$$-th boxer is $$$a_i$$$. Each of them can change the weight by no more than $$$1$$$ before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique).Write a program that for given current values $$$a_i$$$ will find the maximum possible number of boxers in a team.It is possible that after some change the weight of some boxer is $$$150001$$$ (but no more).

The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of boxers. The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ ($$$1 \le a_i \le 150000$$$) is the weight of the $$$i$$$-th boxer.

Print a single integer — the maximum possible number of people in a team.

NoteIn the first example, boxers should not change their weights — you can just make a team out of all of them.In the second example, one boxer with a weight of $$$1$$$ can be increased by one (get the weight of $$$2$$$), one boxer with a weight of $$$4$$$ can be reduced by one, and the other can be increased by one (resulting the boxers with a weight of $$$3$$$ and $$$5$$$, respectively). Thus, you can get a team consisting of boxers with weights of $$$5, 4, 3, 2, 1$$$.

'use strict'

let n = parseInt(readline());
let w = 0;
const a = readline().split(' ').map(Number).sort((x, y) => x - y);

for(let i = 0; i < a.length; i++) {
    if(a[i] < w) n--;
    else w = Math.max(a[i] - 1, w + 1);
}
write(n);

'use strict'

readline();
const a = readline().split(' ').map(Number).sort((x, y) => x - y);
const d = [];

for(let i = 0; i < a.length; i++) {
    if (!d[a[i]-1] && a[i] !== 1) d[a[i]-1] = true;
    else if (!d[a[i]]) d[a[i]] = true;
    else if (!d[a[i]+1]) d[a[i]+1] = true;
}
write(d.slice(1).reduce((r, i) => i ? r + 1 : r, 0));

function input() {
  return [
    parseInt(readline().trim()),
    readline()
      .trim()
      .split(" ")
      .map(function(i) {
        return parseInt(i);
      })
  ];
}

function check(quota, size) {
  var used = new Array(size + 1).fill(0);
  var x = 0;
  // console.log("Testing", size, "|", quota);
  for (var i = size + 1; i > 0; i--) {
    // console.log(i, used);
    if (used[i + 1] < quota[i + 1]) {
      used[i + 1]++;
      x++;
      continue;
    }
    if (used[i] < quota[i]) {
      used[i]++;
      x++;
      continue;
    }
    if (used[i - 1] < quota[i - 1]) {
      used[i - 1]++;
      x++;
      continue;
    }
  }

  print(x);
}

function main() {
  // get input
  var read = input();
  var n = read[0];
  var values = read[1];

  // prep
  var quota = new Array(n + 1).fill(0);
  values.forEach(function(i) {
    quota[i] = quota[i] ? quota[i] + 1 : 1;
  });
  //x

  // calculation
  check(quota, 150001);
}

main();

function input(){
	return [
	parseInt(readline().trim()),
	readline()
	.trim()
	.split(" ")
	.map(function(i){
		return parseInt(i);
	})
	];
}

function main()
{
	var inp = input();
	var n = inp[0];
	var a = inp[1];

	var b = new Array(n+1).fill(0);
	a.forEach(function(i){
		b[i] = b[i] ? b[i]+1 : 1;
	});

	var vis = new Array(150005).fill(0);
	var res = 0;

	for(var i = 150004;i>0;--i)
	{
		if(vis[i+1]<b[i+1])
		{
			++vis[i+1];++res;
		}
		else if(vis[i]<b[i])
		{
			++vis[i];++res;
		}
		else if(vis[i-1]<b[i-1])
		{
			++vis[i-1];++res;
		}
	}

	print(res)
}

main();

'use strict';

const fs = require('fs');

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(str => str.trim());

    main();
});

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

/*
 * Complete the simpleArraySum function below.
 */

function addMapKey(map, key) {
    // console.log(key, map[key])
    if (!map[key - 1] && (key - 1) > 0) {
        map[key - 1] = 1;
        map[key]--;
        if (!map[key])
            delete map[key];
    }
    if (map[key] > 1) {
        if (!map[key + 1]) map[key + 1] = 0;
        map[key + 1] += map[key] - 1;
        map[key] = 1;
    }
}

function simpleArraySum(ar) {
    const map = {};
    ar.forEach(el => {
        el = Number(el)
        if (!map[el]) {
            map[el] = 0;
        }
        map[el]++;
    });

    const mapKeys = Object.keys(map).map(el => Number(el)).sort((a,b) => a-b);
    mapKeys.forEach(key => {
        key = Number(key);
        addMapKey(map, key);
    })
    // console.log(map)
    return Object.keys(map).length;
}

function main() {
    const arCount = parseInt(readLine(), 10);

    const ar = readLine().split(' ').map(arTemp => parseInt(arTemp, 10));

    let result = simpleArraySum(ar);

    console.log(result)
}

'use strict'

readline();
const a = readline().split(' ').map(Number).sort((x, y) => x - y);
const d = [];

for(let i = 0; i < a.length; i++) {
    if (!d[a[i]-1]) d[a[i]-1] = true;
    else if (!d[a[i]]) d[a[i]] = true;
    else if (!d[a[i]+1]) d[a[i]+1] = true;
}
write(d.slice(1).reduce((r, i) => i ? r + 1 : r, 0));

function input() {
  return [
    parseInt(readline().trim()),
    readline()
      .trim()
      .split(" ")
      .map(function(i) {
        return parseInt(i);
      })
  ];
}

function check(quota, size) {
  var used = new Array(size + 1).fill(0);
  for (var i = size; i > 0; i--) {
    if (used[i + 1] < quota[i + 1]) {
      used[i + 1]++;
      continue;
    }
    if (used[i] < quota[i]) {
      used[i]++;
      continue;
    }
    if (i > 0 && used[i - 1] < quota[i - 1]) {
      used[i - 1]++;
      continue;
    }

    return false;
  }
  return true;
}

function main() {
  // get input
  var read = input();
  var n = read[0];
  var values = read[1];

  // prep
  var quota = new Array(n + 1).fill(0);
  values.forEach(function(i) {
    quota[i] = quota[i] ? quota[i] + 1 : 1;
  });
  //x

  // calculation
  for (var i = n; i > 0; i--) {
    if (check(quota, i)) {
      print(i);
      return;
    }
  }

  print(0);
}

main();

function input() {
  return [
    parseInt(readline().trim()),
    readline()
      .trim()
      .split(" ")
      .map(function(i) {
        return parseInt(i);
      })
  ];
}

function check(quota, size) {
  var used = new Array(size + 1).fill(0);
  var x = 0;
  // console.log("Testing", size, "|", quota);
  for (var i = size + 1; i > 0; i--) {
    // console.log(i, used);
    if (used[i + 1] < quota[i + 1]) {
      used[i + 1]++;
      x++;
      continue;
    }
    if (used[i] < quota[i]) {
      used[i]++;
      x++;
      continue;
    }
    if (used[i - 1] < quota[i - 1]) {
      used[i - 1]++;
      x++;
      continue;
    }
  }

  print(x);
}

function main() {
  // get input
  var read = input();
  var n = read[0];
  var values = read[1];

  // prep
  var quota = new Array(n + 1).fill(0);
  values.forEach(function(i) {
    quota[i] = quota[i] ? quota[i] + 1 : 1;
  });
  //x

  // calculation
  check(quota, n);
}

main();

function input() {
  return [
    parseInt(readline().trim()),
    readline()
      .trim()
      .split(" ")
      .map(function(i) {
        return parseInt(i);
      })
  ];
}

function check(quota, size) {
  var used = new Array(size + 1).fill(0);
  for (var i = size; i >= 0; i--) {
    if (used[i + 1] < quota[i + 1]) {
      used[i + 1]++;
      continue;
    }
    if (used[i] < quota[i]) {
      used[i]++;
      continue;
    }
    if (i > 0 && used[i - 1] < quota[i - 1]) {
      used[i - 1]++;
      continue;
    }

    return false;
  }
  return true;
}

function main() {
  // get input
  var read = input();
  var n = read[0];
  var values = read[1];

  // prep
  var quota = new Array(n + 1).fill(0);
  values.forEach(function(i) {
    quota[i] = quota[i] ? quota[i] + 1 : 1;
  });
  //x

  // calculation
  for (var i = n; i > 0; i--) {
    if (check(quota, i)) {
      print(i);
      return;
    }
  }

  print(0);
}

main();

'use strict';

const fs = require('fs');

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(str => str.trim());

    main();
});

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

/*
 * Complete the simpleArraySum function below.
 */

function addMapKey(map, key) {
    if (map[key] > 1 && !map[key + 1]) {
            map[key + 1] = 1;
            map[key]--;
    }
    if (map[key] > 1 && !map[key - 1] && (key - 1) > 0) {
        map[key - 1] = 1;
        map[key]--;
    }
}

function simpleArraySum(ar) {
    const map = {};
    ar.forEach(el => {
        el = Number(el)
        if (!map[el]) {
            map[el] = 0;
        }
        map[el]++;
    });

    const mapKeys = Object.keys(map).sort();
    mapKeys.forEach(key => {
        key = Number(key);
        addMapKey(map, key);
    })
    return Object.keys(map).length;
}

function main() {
    const arCount = parseInt(readLine(), 10);

    const ar = readLine().split(' ').map(arTemp => parseInt(arTemp, 10));

    let result = simpleArraySum(ar);

    console.log(result)
}

'use strict';

const fs = require('fs');

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(str => str.trim());

    main();
});

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

/*
 * Complete the simpleArraySum function below.
 */

function addMapKey(map, key) {
    if (!map[key - 1] && (key - 1) > 0) {
        map[key - 1] = 1;
        map[key]--;
        if (!map[key])
            delete map[key];
    }
    if (map[key] > 1) {
        map[key + 1] += map[key] - 1;
        map[key] = 1;
    }
}

function simpleArraySum(ar) {
    const map = {};
    ar.forEach(el => {
        el = Number(el)
        if (!map[el]) {
            map[el] = 0;
        }
        map[el]++;
    });

    const mapKeys = Object.keys(map).map(el => Number(el)).sort((a,b) => a-b);
    mapKeys.forEach(key => {
        key = Number(key);
        addMapKey(map, key);
    })
    return Object.keys(map).length;
}

function main() {
    const arCount = parseInt(readLine(), 10);

    const ar = readLine().split(' ').map(arTemp => parseInt(arTemp, 10));

    let result = simpleArraySum(ar);

    console.log(result)
}


"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

var n = +readline();
print(n - readline().split(' ').map(Number).sort(function(a, b) {
	return a - b;
}).filter(function(v, i, a) {
	return v !== a[i - 1] && v <= n;
}).length);

var n= parseInt(readline().trim());
var a= readline().trim().split(' ').map((x)=>parseInt(x));

var sa = new Set(a);

var na = Array.from(sa)

var ans = a.length - na.length;

ans+=na.filter((x)=>!(x>=1 && x<=n)).length;

print(ans);

;(function () {
	for (var i = 0, n = +readline(), m = new Array(n); i < n; i++) m[i] = false;
	readline().split(' ').forEach(function (e, i, a) { m[e - 1] = true; });
	print(m.filter(function (e, i, a) { return !e; }).length);
}).call(this)

var up = Number(readline());
var nums = readline().split(' ');
nums = nums.map(function(a){
    return Number(a);
});
nums.sort();
num_count = up;
var result = 0;
var last = null;
for (var i in nums) {
    if (nums[i] > up || nums[i] === last)
        result++;
    else
        last = nums[i];
}
print(result)

(function() {
  var ch, count, i, map, max, res;
  readline();
  ch = readline().split(" ").map(Number);
  max = ch.length;
  map = {};
  res = 0;
  ch.forEach(function(num) {
    if (map[num]) {
      return map[num]++;
    } else {
      return map[num] = 1;
    }
  });
  for (i in map) {
    count = map[i];
    if (count !== 1) {
      res += count - 1;
    }
    if (+i > max) {
      res += 1;
    }
  }
  write(res);
}).call(this);

var getNums = function () {
    return readline().split(' ').map(function (a) { return parseInt(a) });
};

//137B
//Local attempts - 1
//Sent attempts - 1
var n = parseInt(readline());
var data = getNums();
var hash = {};
for (var i = 1; i <= n; i++) {
    hash[i] = 0;
}
data.forEach(d => hash[d]++);
var res = 0;
Object.keys(hash).forEach(h => {
    if (hash[h] === 0) {
        res++;
    }
});
print(res);

var up = Number(readline());
var nums = readline().split(' ');
nums = nums.map(function(a){
    return Number(a);
});
nums.sort();
num_count = up;
var result = 0;
var last = null;
for (var i in nums) {
    if (nums[i] > up || nums[i] === last)
        result++;
    else
        last = i;
}
print(result)

(function() {
  var ch, count, i, map, res;
  readline();
  ch = readline().split(" ").map(Number);
  map = {};
  res = 0;
  ch.forEach(function(num) {
    if (map[num]) {
      return map[num]++;
    } else {
      return map[num] = 1;
    }
  });
  for (i in map) {
    count = map[i];
    if (count !== 1) {
      res += count - 1;
    }
  }
  write(res);
}).call(this);

(function() {
  var ch, count, i, map, max, res;
  readline();
  ch = readline().split(" ").map(Number);
  max = ch.length;
  map = {};
  res = 0;
  ch.forEach(function(num) {
    if (map[num]) {
      return map[num]++;
    } else {
      return map[num] = 1;
    }
  });
  for (i in map) {
    count = map[i];
    if (count !== 1) {
      res += count - 1;
    } else {
      if (i > max) {
        res += 1;
      }
    }
  }
  write(res);
}).call(this);

(function() {
  var ch, count, i, map, max, res;
  readline();
  ch = readline().split(" ").map(Number);
  max = ch.length;
  map = {};
  res = 0;
  ch.forEach(function(num) {
    if (map[num]) {
      return map[num]++;
    } else {
      return map[num] = 1;
    }
  });
  for (i in map) {
    count = map[i];
    if (count !== 1) {
      res += count - 1;
    } else {
      if (+i > max) {
        res += 1;
      }
    }
  }
  write(res);
}).call(this);


Sasha and Dima want to buy two $$$n$$$-tier cakes. Each cake should consist of $$$n$$$ different tiers: from the size of $$$1$$$ to the size of $$$n$$$. Tiers should go in order from the smallest to the biggest (from top to bottom).They live on the same street, there are $$$2 \cdot n$$$ houses in a row from left to right. Each house has a pastry shop where you can buy a cake tier. Unfortunately, in each pastry shop you can buy only one tier of only one specific size: in the $$$i$$$-th house you can buy a tier of the size $$$a_i$$$ ($$$1 \le a_i \le n$$$).Since the guys carry already purchased tiers, and it is impossible to insert a new tier in the middle of the cake, they agreed to buy tiers from the smallest to the biggest. That is, each of them buys tiers in order: $$$1$$$, then $$$2$$$, then $$$3$$$ and so on up to $$$n$$$.Initially, Sasha and Dima are located near the first (leftmost) house. Output the minimum distance that they will have to walk in total to buy both cakes. The distance between any two neighboring houses is exactly $$$1$$$.

The first line of the input contains an integer number $$$n$$$ — the number of tiers in each cake ($$$1 \le n \le 10^5$$$). The second line contains $$$2 \cdot n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is equal to the size of the tier, which can be bought in the $$$i$$$-th house. Remember that in each house you can buy only one tier. It is guaranteed that every number from $$$1$$$ to $$$n$$$ occurs in $$$a$$$ exactly two times.

Print one number  — the minimum distance that the guys have to walk in total to buy both cakes. Guys can be near same house at the same time. They begin near the first (leftmost) house. Each of the guys should buy $$$n$$$ tiers in ascending order of their sizes.

NoteIn the first example, the possible optimal sequence of actions is:  Sasha buys a tier of size $$$1$$$ near the $$$1$$$-st house ($$$a_1=1$$$);  Dima goes to the house $$$2$$$;  Dima buys a tier of size $$$1$$$ near the $$$2$$$-nd house ($$$a_2=1$$$);  Sasha goes to the house $$$4$$$;  Sasha buys a tier of size $$$2$$$ near the $$$4$$$-th house ($$$a_4=2$$$);  Sasha goes to the house $$$5$$$;  Sasha buys a tier of size $$$3$$$ near the $$$5$$$-th house ($$$a_5=3$$$);  Dima goes to the house $$$3$$$;  Dima buys a tier of size $$$2$$$ near the $$$3$$$-rd house ($$$a_3=2$$$);  Dima goes to the house $$$6$$$;  Dima buys a tier of size $$$3$$$ near the $$$6$$$-th house ($$$a_6=3$$$). So, Sasha goes the distance $$$3+1=4$$$, and Dima goes the distance $$$1+1+3=5$$$. In total, they cover a distance of $$$4+5=9$$$. You can make sure that with any other sequence of actions they will walk no less distance.

const readline = require('readline');
const rl = readline.createInterface({input: process.stdin});
var stdin = [];
rl.on('line', function (line) {stdin.push(line);});
rl.on('close', main)

function main() {
  const n = parseInt(stdin[0])
  const sizes = stdin[1].split(' ').map(s => parseInt(s))
  const sizeMap = new Map()
  sizeMap.set(0, [0, 0]) //default
  sizes.forEach((size, position) => {
    if (sizeMap.has(size)) {
      sizeMap.get(size).push(position)
    } else {
      sizeMap.set(size, [position])
    }
  })

  let movement = 0
  for(let size = 1; size <= n; size++) {
    const prevPos = sizeMap.get(size-1)
    const pos = sizeMap.get(size)
    movement = movement + Math.abs(prevPos[0]-pos[0]) + Math.abs(prevPos[1]-pos[1])
  }

  console.log(movement)
}

let rawInput = '';
process.stdin.on('data', c => rawInput += c);
let inputByLinesOnResolve = new Promise((resolve, reject) => {
    process.stdin.on('end', () => {
        const { EOL } = require('os');
        resolve(rawInput.split(EOL));
    });
});

(async function(){

    let lines = await inputByLinesOnResolve;
    let n = parseInt(lines[0]);
    let nn = n << 1;
    let tierInHouse = lines[1].split(" ").map(tier => parseInt(tier));

    let availableTiers = new Array(nn);

    for (let i = 0; i < nn; ++i) {
        if (!availableTiers[tierInHouse[i]]) {
            availableTiers[tierInHouse[i]] = Array(2);
            availableTiers[tierInHouse[i]][0] = i;
        } else {
            availableTiers[tierInHouse[i]][1] = i;
        }
    }

    let currentPosition1 = 0;
    let currentPosition2 = 0;
    let distance = 0;
    let Abs = x => (x < 0) ? (-x) : x;
    for (let i = 1; i <= n; ++i) {

        distance += Abs(currentPosition1 - availableTiers[i][0]);
        distance += Abs(currentPosition2 - availableTiers[i][1]);
        currentPosition1 = availableTiers[i][0];
        currentPosition2 = availableTiers[i][1];
    }

    console.log(distance);

})();

let rawInput = '';
process.stdin.on('data', c => rawInput += c);
let inputByLinesOnResolve = new Promise((resolve, reject) => {
    process.stdin.on('end', () => {
        const { EOL } = require('os');
        resolve(rawInput.split(EOL));
    });
});

(async function(){

    let lines = await inputByLinesOnResolve;
    let n = parseInt(lines[0]);
    let nn = n << 1;
    let tierInHouse = lines[1].split(" ").map(tier => parseInt(tier));

    let availableTiers = new Array(nn);

    for (let i = 0; i < nn; ++i) {
        if (!availableTiers[tierInHouse[i]]) {
            availableTiers[tierInHouse[i]] = Array(2);
            availableTiers[tierInHouse[i]][0] = i;
        } else {
            availableTiers[tierInHouse[i]][1] = i;
        }
    }

    let currentPosition1 = 0;
    let currentPosition2 = 0;
    let distance = 0;
    let Abs = x => (x < 0) ? (-x) : x;
    for (let i = 1; i < n; ++i) {

        distance += Abs(currentPosition1 - availableTiers[i][0]) + 1;
        distance += Abs(currentPosition2 - availableTiers[i][1]) + 1;
        currentPosition1 = availableTiers[i][0];
        currentPosition2 = availableTiers[i][1];
    }

    console.log(distance);

})();

let rawInput = '';
process.stdin.on('data', c => rawInput += c);
let inputByLinesOnResolve = new Promise((resolve, reject) => {
    process.stdin.on('end', () => {
        const { EOL } = require('os');
        resolve(rawInput.split(EOL));
    });
});

(async function(){

    let lines = await inputByLinesOnResolve;
    let n = parseInt(lines[0]);
    let nn = n << 1;
    let tierInHouse = lines[1].split(" ").map(tier => parseInt(tier));

    let availableTiers = new Array(nn);

    for (let i = 0; i < nn; ++i) {
        if (!availableTiers[tierInHouse[i]]) {
            availableTiers[tierInHouse[i]] = Array(2);
            availableTiers[tierInHouse[i]][0] = i;
        } else {
            availableTiers[tierInHouse[i]][1] = i;
        }
    }

    let currentPosition1 = 1;
    let currentPosition2 = 1;
    let distance = 0;
    let Abs = x => (x < 0) ? (-x) : x;
    for (let i = 1; i < n; ++i) {

        let distance0 = Abs(currentPosition1 - availableTiers[i][0]) + 1;
        let distance1 = Abs(currentPosition1 - availableTiers[i][1]) + 1;

        let distance2 = Abs(currentPosition2 - availableTiers[i][0]) + 1;
        let distance3 = Abs(currentPosition2 - availableTiers[i][1]) + 1;

        if ((distance0 + distance3) < (distance1 + distance2)) {
            distance += distance0 + distance3;
            currentPosition1 = availableTiers[i][0];
            currentPosition2 = availableTiers[i][1];
        } else {
            distance += distance1 + distance2;
            currentPosition1 = availableTiers[i][1];
            currentPosition2 = availableTiers[i][0];
        }
    }

    console.log(distance);

})();

let rawInput = '';
process.stdin.on('data', c => rawInput += c);
let inputByLinesOnResolve = new Promise((resolve, reject) => {
    process.stdin.on('end', () => {
        const { EOL } = require('os');
        resolve(rawInput.split(EOL));
    });
});

(async function(){

    let lines = await inputByLinesOnResolve;
    let n = parseInt(lines[0]);
    let nn = n << 1;
    let tierInHouse = lines[1].split(" ").map(tier => parseInt(tier));

    let availableTiers = new Array(n + 1);

    for (let i = 0; i < nn; ++i) {
        if (!availableTiers[tierInHouse[i]]) {
            availableTiers[tierInHouse[i]] = Array(2);
            availableTiers[tierInHouse[i]][0] = i + 1;
        } else {
            availableTiers[tierInHouse[i]][1] = i + 1;
        }
    }

    let Abs = x => (x < 0)?(-x):x;

    function goForTiers(currentPosition) {

        let distance = 0;
        for (let i = 1; i < n; ++i) {

            let newPosition0 = 20000000;
            let newPosition1 = 20000000;

            if (availableTiers[i][0] != -1) { newPosition0 = availableTiers[i][0]; }
            if (availableTiers[i][1] != -1) { newPosition1 = availableTiers[i][1]; }
            let distance0 = Abs(currentPosition - newPosition0) + 1;
            let distance1 = Abs(currentPosition - newPosition1) + 1;

            if (distance0 < distance1) {
                availableTiers[i][0] = -1;
                distance += distance0;
                currentPosition = newPosition0;
            } else {
                availableTiers[i][1] = -1;
                distance += distance1;
                currentPosition = newPosition1;
            }
        }

        return distance;
    };

    console.log(goForTiers(1) + goForTiers(1));

})();


Rahul and Tina are looking forward to starting their new year at college. As they enter their new classroom, they observe the seats of students are arranged in a $$$n \times m$$$ grid. The seat in row $$$r$$$ and column $$$c$$$ is denoted by $$$(r, c)$$$, and the distance between two seats $$$(a,b)$$$ and $$$(c,d)$$$ is $$$|a-c| + |b-d|$$$. As the class president, Tina has access to exactly $$$k$$$ buckets of pink paint. The following process occurs.   First, Tina chooses exactly $$$k$$$ seats in the classroom to paint with pink paint. One bucket of paint can paint exactly one seat.  After Tina has painted $$$k$$$ seats in the previous step, Rahul chooses where he sits. He will not choose a seat that has been painted pink due to his hatred of the colour pink.  After Rahul has chosen his seat, Tina chooses a seat for herself. She can choose any of the seats, painted or not, other than the one chosen by Rahul. Rahul wants to choose a seat such that he sits as close to Tina as possible. However, Tina wants to sit as far away from Rahul as possible due to some complicated relationship history that we couldn't fit into the statement!Now, Rahul wonders for $$$k = 0, 1, \dots, n \cdot m - 1$$$, if Tina has $$$k$$$ buckets of paint, how close can Rahul sit to Tina, if both Rahul and Tina are aware of each other's intentions and they both act as strategically as possible? Please help satisfy Rahul's curiosity!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \cdot m \leq 10^5$$$) — the number of rows and columns of seats in the classroom. The sum of $$$n \cdot m$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, output $$$n \cdot m$$$ ordered integers — the distance between Rahul and Tina if both of them act optimally for every $$$k \in [0, n \cdot m - 1]$$$.

NoteOne possible sequence of choices for the first testcase where Tina has $$$k=3$$$ buckets of paints is as follows.Tina paints the seats at positions $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ with pink paint. Rahul chooses the seat at $$$(3, 1)$$$ after which Tina chooses to sit at $$$(1, 3)$$$. Therefore, the distance between Tina and Rahul is $$$|3-1| + |1-3| = 4$$$, and we can prove that this is indeed the minimum possible distance under the given constraints. There may be other choices of seats which lead to the same answer as well.For $$$k=0$$$ in the first test case, Rahul can decide to sit at $$$(2, 2)$$$ and Tina can decide to sit at $$$(4, 3)$$$ so the distance between them would be $$$|2 - 4| + |2 - 3| = 3$$$.Below are pictorial representations of the $$$k=3$$$ and $$$k=0$$$ cases for the first test case.  A possible seating arrangement for $$$k=3$$$.  A possible seating arrangement for $$$k=0$$$.

"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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, m] = iInpArr();
    const getmax = (i, j) => {
      let p1 = Math.abs(1 - i) + Math.abs(1 - j);
      let p2 = Math.abs(1 - i) + Math.abs(m - j);
      let p3 = Math.abs(n - i) + Math.abs(1 - j);
      let p4 = Math.abs(n - i) + Math.abs(m - j);
      return Math.max(p1, p2, p3, p4);
    };
    let res = [],
      i = 0,
      j = n - 1;
    while (i <= j) {
      let k = 0,
        l = m - 1;
      if (i !== j) {
        while (k <= l) {
          if (k === l) {
            res.push(getmax(i + 1, k + 1));
            res.push(getmax(j + 1, k + 1));
          } else {
            res.push(getmax(i + 1, k + 1));
            res.push(getmax(j + 1, k + 1));
            res.push(getmax(i + 1, l + 1));
            res.push(getmax(j + 1, l + 1));
          }
          k++;
          l--;
        }
      } else {
        while (k <= l) {
          if (k === l) res.push(getmax(i + 1, k + 1));
          else {
            res.push(getmax(i + 1, k + 1));
            res.push(getmax(i + 1, l + 1));
          }
          k++;
          l--;
        }
      }
      i++;
      j--;
    }
    console.log(res.sort((a, b) => a - b).join(" "));
  }
};
solve();

/* Common Template Starts */
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++];
}
/* Common Template Ends */

function main() {
    //take input according to the format;
    const t = +(readline());
    for(let i =0; i<t; ++i){
        const [m,n] = readline().split(' ').map(el=>parseInt(el));

        let arr = new Array(m*n);
        let c = 0;
        let d1, d2, d3, d4;
        for(let j =0; j<m; ++j){

            for(let k =0; k<n; ++k){

                 d1 = j + k;
                 d2 =  m -1 - j + k;
                 d3 =  j + n -1 - k;
                 d4 = m - 1 - j + n -1 - k ;
                arr[c] = Math.max(d1, d2, d3, d4);
                c++;
            }
        }
        arr.sort((a,b)=>a-b)
        for(let el of arr)
            process.stdout.write(`${el} `);
        console.log()
    }
}

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.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

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

		const ans = [];
		for (let i = 0; i < n; i++) {
			for (let j = 0; j < m; j++) {
				ans.push(Math.max(n-1-i, i) + Math.max(m-1-j, j));
			}
		}
		ans.sort((x, y) => x - y);

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

let _inputLines;
let _lineNumber = 0;
let inputReader = _inputReader ();

function _main() {

	_inputLines = _inputData.trim().split('\n').map((string) => {
		return string.trim();
	});;
	//------------------------------<Solution>-------------------------------//
	let t = inputReader.readNumber();
	//let t = 1;

	function solve() {
	  let [n, m] = inputReader.readNumberArray();
	  let dist = [];
	  for (let i = 0; i < n; i++) {
	    for (let j = 0; j < m; j++) {
	      let distance = Math.max(i, n - i - 1) + Math.max(j, m - j - 1);
	      dist.push(distance);
	    }
	  }
	  dist.sort((a, b) => {
	    if(a > b) return 1;
	    else if(a == b) return 0;
	    else return -1;
	  });

	  console.log(dist.join(" "));
	}

	while (t--) {
	  solve();
	}

	//------------------------------</Solution>--------------------------//

}

var _inputData = '';
function cacheInput(data) {
	_inputData += data;
}

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', cacheInput).on('end', _main);

function _inputReader () {
	function readNumber(){
		return Number(_inputLines[_lineNumber++]);
	}

	function readNumberArray(){
		return _inputLines[_lineNumber++].split(' ').map(val => Number(val));
	}

	return {
		readNumber,
		readNumberArray,
	}
}

 var t = parseInt(readline());
  function solve(){
    var inp = readline()
      .split(" ")
      .map((data) => +data);
    var n = inp[0]
    var m = inp[1]
    var arr = []
    for (var i = 0; i < n; ++i)
        for (var j = 0; j < m; ++j)
        arr.push(Math.max(i, n - i - 1) + Math.max(j, m - j - 1));

   arr.sort((a,b) =>{
       if(a>b){
           return 1
       }else if(a < b){
           return -1
       }else{
           return 0
       }
   })
    return arr.join(" ")
  }

while(t--){
   print(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++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
const solve = () => {
  let t = getValue();
  while (t--) {
    let [n, m] = iInpArr();
    const getmax = (i, j) => {
      let p1 = Math.abs(1 - i) + Math.abs(1 - j);
      let p2 = Math.abs(1 - i) + Math.abs(n - j);
      let p3 = Math.abs(n - i) + Math.abs(j - 1);
      let p4 = Math.abs(n - i) + Math.abs(m - j);
      return Math.max(p1, p2, p3, p4);
    };
    let res = [],
      i = 0,
      j = n - 1;
    while (i <= j) {
      let k = 0,
        l = m - 1;
      while (k <= l) {
        res.push(getmax(i + 1, k + 1));
        if (k !== l || i !== j) res.push(res[res.length - 1]);
        if (k !== l && i !== j) {
          res.push(getmax(i + 1, l + 1));
          res.push(res[res.length - 1]);
        }
        k++;
        l--;
      }
      i++;
      j--;
    }
    console.log(res.reverse().join(" "));
  }
};
solve();