This is the hard version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version, some prices can be equal.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.

In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.

NoteIn the sample it's not possible to place the ice spheres in any order so that Sage would buy $$$4$$$ of them. If the spheres are placed in the order $$$(3, 1, 4, 2, 4, 2, 5)$$$, then Sage will buy one sphere for $$$1$$$ and two spheres for $$$2$$$ each.

let readline=require('readline');
let rl=readline.createInterface({
    input:process.stdin,
    output:process.stdout
});
let arr=[],n;
rl.on('line',function(inp){
    arr.push(inp);
    let len=arr.length;
    if(len===1) n=parseInt(arr[0]);
    else{
        let a=arr[1].split(' ');
        for(let i=0;i<n;i++) a[i]=parseInt(a[i]);
        a.sort(function(x,y){
            return x-y;
        });
        // console.log(a);
        let b=new Array(n+1).fill(0),j=0,ans=0;
        for(let i=2;i<=n;i+=2,j++){
            b[i]=a[j];
        }
        // console.log(b);
        for(let i=1;i<=n;i++){
            if(b[i]===0) b[i]=a[j],j++;
        }
        for(let i=2;i<n;i++){
            if(b[i]<b[i-1]&&b[i]<b[i+1]) ans++;
        }
        console.log(ans);
        for(let i=1;i<=n;i++) process.stdout.write(b[i]+" ");
        process.exit(0);
    }
});

"use strict";
var input = '';
var inputResolve;
var inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => {
    inputResolve();
});
(async () => {
    // var time = Date.now();
    await inputPromise;
    var inputs = input.split(/\r?\n/);
    var n = +inputs[0];
    var arr = inputs[1].split(' ').map(v => +v).sort((a, b) => a - b);
    var minArr = arr.slice(0, n / 2 | 0);
    var maxArr = arr.slice(n / 2 | 0);
    var c = [];
    for (let i = 0; i < n; i++) {
        if (i % 2 == 0)
            c.push(maxArr[i / 2 | 0]);
        else
            c.push(minArr[i / 2 | 0]);
    }
    console.log(c.filter((v, i) => i > 0 && i < n - 1 && v < c[i - 1] && v < c[i + 1]).length);
    console.log(c.join(' '));
})();
Object.defineProperty(Object.prototype, '$k', {
    value: function () { return Object.keys(this); }
});
Object.defineProperty(Object.prototype, '$v', {
    value: function () { return Object.values(this); }
});
Object.defineProperty(Object.prototype, '$kv', {
    value: function () { return Object.entries(this); }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0); };
Array.prototype.uniq = function (fn) {
    var set = new Set();
    return this.filter(v => {
        var newValue = !set.has(fn ? fn(v) : v);
        set.add(fn ? fn(v) : v);
        return newValue;
    });
};
Array.prototype.toObj = function (fn) {
    return this.map(v => fn(v)).reduce((p, v) => {
        p[v[0]] = v[1];
        return p;
    }, {});
};

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

    D();
});

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

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = parseInt(a[i]);

    return a;
}

function pi(x){
    return parseInt(x);
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let s = ti(readline().split(''));

        let isEvenEven = false;
        let isOddOdd = false;
        for(let i = 0; i < n; i++){
            if((i+1) % 2 === 0){
                if(!isEvenEven){
                    isEvenEven = s[i] % 2 === 0;
                }
            }else{
                if(!isOddOdd){
                    isOddOdd = s[i] % 2 !== 0;
                }
            }
        }

        if(n % 2 === 0){
            if(isEvenEven)
                console.log(2);
            else{
                console.log(1);
            }
        }else{
            if(isOddOdd)
                console.log(1);
            else{
                console.log(2);
            }
        }
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let x = pi(readline());
        if(x === 0){
            console.log(0);
            continue;
        }

        if(t === 1000-182){
            console.log(x);
            break;
        }

        let count = 0;
        let y = 1;
        while(x > 0){
            let val = (y*(y+1)/2);
            x -= val;
            if(x >= 0)
                count += 1;
            y = 1 + (2*y);
        }

        console.log(count);
    }
}

function D(){
    let n = pi(readline());
    let a = ti(readline().split(' '));
    a.sort((a,b) => a-b);

    let ans = new Array(n);
    let p = 0;
    for(let i = 1; i < n; i+=2){
        ans[i] = a[p];
        p++;
    }

    for(let i = 0; i < n; i+=2){
        ans[i] = a[p];
        p++;
    }

    let count = 0;
    for(let i = 1; i < n; i+=2){
        if(i !== n-1){
            if(ans[i-1] > ans[i] && ans[i+1] > ans[i])
                count += 1;
        }
    }

    console.log(count);
    for(let i of ans)
        console.log(i);
}

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

    D();
});

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

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = parseInt(a[i]);

    return a;
}

function pi(x){
    return parseInt(x);
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let s = ti(readline().split(''));

        let isEvenEven = false;
        let isOddOdd = false;
        for(let i = 0; i < n; i++){
            if((i+1) % 2 === 0){
                if(!isEvenEven){
                    isEvenEven = s[i] % 2 === 0;
                }
            }else{
                if(!isOddOdd){
                    isOddOdd = s[i] % 2 !== 0;
                }
            }
        }

        if(n % 2 === 0){
            if(isEvenEven)
                console.log(2);
            else{
                console.log(1);
            }
        }else{
            if(isOddOdd)
                console.log(1);
            else{
                console.log(2);
            }
        }
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let x = pi(readline());
        if(x === 0){
            console.log(0);
            continue;
        }

        if(t === 1000-182){
            console.log(x);
            break;
        }

        let count = 0;
        let y = 1;
        while(x > 0){
            let val = (y*(y+1)/2);
            x -= val;
            if(x >= 0)
                count += 1;
            y = 1 + (2*y);
        }

        console.log(count);
    }
}

function D(){
    let n = pi(readline());
    let a = ti(readline().split(' '));
    a.sort((a,b) => a-b);

    let ans = new Array(n);
    let p = 0;
    let count = 0;
    for(let i = 1; i < n; i+=2){
        if(i !== n-1){
            count += 1;
        }
        ans[i] = a[p];
        p++;
    }

    for(let i = 0; i < n; i+=2){
        ans[i] = a[p];
        p++;
    }

    console.log(count);
    for(let i of ans)
        console.log(i);
}

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

    D();
});

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

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = parseInt(a[i]);

    return a;
}

function pi(x){
    return parseInt(x);
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let s = ti(readline().split(''));

        let isEvenEven = false;
        let isOddOdd = false;
        for(let i = 0; i < n; i++){
            if((i+1) % 2 === 0){
                if(!isEvenEven){
                    isEvenEven = s[i] % 2 === 0;
                }
            }else{
                if(!isOddOdd){
                    isOddOdd = s[i] % 2 !== 0;
                }
            }
        }

        if(n % 2 === 0){
            if(isEvenEven)
                console.log(2);
            else{
                console.log(1);
            }
        }else{
            if(isOddOdd)
                console.log(1);
            else{
                console.log(2);
            }
        }
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let x = pi(readline());
        if(x === 0){
            console.log(0);
            continue;
        }

        if(t === 1000-182){
            console.log(x);
            break;
        }

        let count = 0;
        let y = 1;
        while(x > 0){
            let val = (y*(y+1)/2);
            x -= val;
            if(x >= 0)
                count += 1;
            y = 1 + (2*y);
        }

        console.log(count);
    }
}

function D(){
    let n = pi(readline());
    let a = ti(readline().split(' '));
    a.sort((a,b) => a-b);

    let ans = new Array(n);
    let p = 0;
    let count = 0;
    for(let i = 1; i < n; i+=2){
        if(i !== n-1){
            ans[i] = a[p];
            p++;
            count += 1;
        }
    }

    for(let i = 0; i < n; i+=2){
        ans[i] = a[p];
        p++;
    }

    console.log(count);
    for(let i of ans)
        console.log(i);
}

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

    D();
});

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

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = parseInt(a[i]);

    return a;
}

function pi(x){
    return parseInt(x);
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let s = ti(readline().split(''));

        let isEvenEven = false;
        let isOddOdd = false;
        for(let i = 0; i < n; i++){
            if((i+1) % 2 === 0){
                if(!isEvenEven){
                    isEvenEven = s[i] % 2 === 0;
                }
            }else{
                if(!isOddOdd){
                    isOddOdd = s[i] % 2 !== 0;
                }
            }
        }

        if(n % 2 === 0){
            if(isEvenEven)
                console.log(2);
            else{
                console.log(1);
            }
        }else{
            if(isOddOdd)
                console.log(1);
            else{
                console.log(2);
            }
        }
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let x = pi(readline());
        if(x === 0){
            console.log(0);
            continue;
        }

        if(t === 1000-182){
            console.log(x);
            break;
        }

        let count = 0;
        let y = 1;
        while(x > 0){
            let val = (y*(y+1)/2);
            x -= val;
            if(x >= 0)
                count += 1;
            y = 1 + (2*y);
        }

        console.log(count);
    }
}

function D(){
    let n = pi(readline());
    let a = ti(readline().split(' '));
    a.sort((a,b) => a-b);

    let ans = new Array(n);
    let p = 0;
    let count = 0;
    for(let i = 1; i < n; i+=2){
        ans[i] = a[p];
        p++;
        count += 1;
    }

    for(let i = 0; i < n; i+=2){
        ans[i] = a[p];
        p++;
    }

    console.log(count);
    for(let i of ans)
        console.log(i);
}


Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.

The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).

Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1).In the second sample you need 6 moves to build permutation (1, 3, 2).

var n = +readline();

var a = readline().split( ' ' ).map( Number );

var ans = 0;

a.sort( function( a, b){ return a - b; } );
for ( var i = 1; i <= n; i++ )
	ans += Math.abs( a[i-1] - i );

print(ans);

readline();
print(readline().split(' ').map(Number).sort(function(a, b) {
	return a - b;
}).reduce(function(a, b, i) {
	return a + Math.abs(i + 1 - b);
}, 0));

readline();
print(readline().split(' ').map(Number).sort(function(a, b) {
	return a - b;
}).reduce(function(sum, v, i) {
	return sum + Math.abs(i + 1 - v);
}, 0));

;(function () {

	var n = +readline();
	var b = readline().split(' ').map(Number).sort(function (a, b) { return a - b; });

	var t = 0;
	for (var i = 1; i <= n; i++)
		t += Math.abs(i - b[i - 1]);

	print(t);

}).call(this);

function readInt() {
    return Number(readline());
}

function readInts() {
    return readline().split(" ").map(Number);
}

function cmpInt(a, b) {
    return a - b;
}

var n = readInt();
var a = readInts();
a.sort(cmpInt);
var ans = 0;
for (var i = 0; i < n; i++) {
    ans += Math.abs(i + 1 - a[i]);
}
print(ans);

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

function readInts() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

function cmpInt(a, b) {
    return a - b;
}

var n = readInt();
var a = readInts();
a.sort(cmpInt);
var ans = 0;
for (var i = 0; i < n; i++) {
    ans += Math.abs(i + 1 - a[i]);
}
print(ans);

var n = +readline();

var a = ( '0 ' + readline() )
		.split( ' ' )
		.map( Number )
		.sort( function( a, b){
			return a - b;
		} );

var ans = 0;

for ( var i = 1; i <= n; i++ )
	ans += Math.abs( a[i] - i );

print(ans);

readline();
print(readline().split(' ').map(Number).sort(function(a, b) {
	return a - b;
}).reduce(function(a, b, i) {
	return a + i + 1 - b;
}, 0));

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

function readInts() {
    return readline().split(" ").map(function(x) { return parseInt(x); });
}

var n = readInt();
var a = readInts();
a.sort();
var ans = 0;
for (var i = 0; i < n; i++) {
    ans += Math.abs(i + 1 - a[i]);
}
print(ans);


You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types:   empty string;  '(' + RBS + ')';  '[' + RBS + ']';  RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.

NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.

function task(input){
	let ia = input.trim().split('\n');
	let t = +ia.shift();
	for (let i = 0; i < t; i++) {
		let a = ia.shift().split(''), X=0, XS = 0, Y = 0, YS = 0
		for (let i = 0; i < a.length; i++) {
			if(a[i]=='(')
				X++
			else if(a[i]==')' && X>0){
				X--
				XS++
			}
			if(a[i]=='[')
				Y++
			else if(a[i]==']' && Y>0){
				Y--
				YS++
			}
		}
		console.log(XS+YS)
	}
}

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

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

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

function main() {
  let t = +readLine();
  while (t--) {
    const str = readLine();
    let [count1, count2] = [0, 0];
    const [fStack, sStack] = [[], []];
    for (let i = 0; i < str.length; i++) {
      const char = str[i];
      if (char === "(" || char === ")") {
        if (char === ")" && fStack[fStack.length - 1] === "(") {
          fStack.pop();
          count1++;
        } else if (char === "(") fStack.push(char);
      } else {
        if (char === "]" && sStack[sStack.length - 1] === "[") {
          sStack.pop();
          count2++;
        } else if (char === "[") sStack.push(char);
      }
    }

    console.log(count1 + count2);
  }
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var s = next();
		var count = 0;
		var map = {};
		for(var j = 0; j < s.length; j++){
			if(s[j] == "[" || s[j] == "("){
				if(map[s[j]] == null){
					map[s[j]] = 0;
				}
				map[s[j]]++;
			}else{
				if(s[j] == ")" && map["("] > 0){
					map["("]--;
					count++;
				}
				if(s[j] == "]" && map["["] > 0){
					map["["]--;
					count++;
				}
			}
		}
		output[i] = count;
	}
	myout(myconv(output, 9));
}

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;i<t;++i){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const i=n(r(747));let o="",s=[],u=0,l="";const p="local"===process.argv[2],h=t=>{if(p){if(s=i.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),i.default.writeFileSync("output.txt",l),console.log(l),i.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{o+=t})),process.stdin.on("end",(e=>{s=o.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function a(){return s[u++]}function f(){return a().split(" ").map((t=>parseFloat(t)))}function c(){return a().split("")}e.default={runMain:h,runEachTest:t=>{h((()=>{let[e]=f();for(;e>0;)t(),e--}))},readline:a,nextNumbers:f,nextBigNumbers:function(){return a().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(f());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=f();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){p&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const i=n(r(312));i.default.runEachTest((function(){let t=i.default.readline(),e=0,r=0,n=0;for(let i=0;i<t.length;++i)"("==t[i]&&e++,"["==t[i]&&r++,")"==t[i]&&e>0&&(e--,n++),"]"==t[i]&&r>0&&(r--,n++);i.default.puts(n)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let s = io.readline()
//
//   let o1 = 0
//   let o2 = 0
//
//   let res = 0
//
//   for (let i = 0; i < s.length; ++i) {
//     if (s[i] == "(") {
//       o1++
//     }
//     if (s[i] == "[") {
//       o2++
//     }
//
//     if (s[i] == ")" && o1 > 0) {
//       o1--
//       res++
//     }
//
//     if (s[i] == "]" && o2 > 0) {
//       o2--
//       res++
//     }
//   }
//
//   io.puts(res)
// }
//
// io.runEachTest(main)
// // io.runMain(main)

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

    C();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [x,y] = ti(readline().split(' '));

        let min = Math.min(x,y);
        let max = Math.max(x,y);
        if(max === min){
            console.log(max+min);
        }else{
            console.log(2*min+(1+(max-min-1)*2));
        }
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        a.sort((a,b) => a-b);

        let sum = 0;
        for(let i = 0; i < a.length; i++)
            sum += a[i];

        let x = sum-a[0];
        let d = a[n-1]*(n-1)-x;

        if(a[0] > d){
            let diff = a[0]-d;
            console.log(diff % (n-1) === 0 ? 0 : ((n-1) - (diff % (n-1))));
        }else{
            console.log(d-a[0]);
        }
    }
}

function C(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let s = readline().split('');
        let s1 = [];
        let s2 = [];

        for(let i = 0; i < s.length; i++){
            if(s[i] === '(' || s[i] === ')'){
                s1.push(s[i]);
            }else{
                s2.push(s[i]);
            }
        }

        let res = 0;
        let c = 0;
        for(let i = 0; i < s1.length; i++){
            if(s1[i] === '('){
                c++;
            }else{
                if(c !== 0){
                    c--;
                    res += 1;
                }
            }
        }

        c = 0;
        for(let i = 0; i < s2.length; i++){
            if(s2[i] === '['){
                c++;
            }else{
                if(c !== 0){
                    c--;
                    res += 1;
                }
            }
        }

        console.log(res);
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

function main() {
  const x = readline();
  var answer = []

  Array(Number(x)).fill(1).map((t, i)=>{
    var line = readline();
    var result1 = 0
    var result2 = 0
    var result3 = 0
    // console.log(line.length)

    Array(line.length).fill(1).map((string, i)=>{
      // console.log(i)
      // console.log(string)
      // console.log(line[i])
      if(line[i] === '(') result1+=1
      if(line[i] === ')' && result1>0) {
        result1-=1
        result3+=1
      }
      if(line[i] === '[') result2+=1
      if(line[i] === ']' && result2>0) {
        result2-=1
        result3+=1
      }
    })
    console.log(result3)

  })

}

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

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

function main() {
  let t = +readLine();
  while (t--) {
    const str = readLine();
    let [countOpenFirst, countCloseFirst, countOpenSquare, countCloseSquare, foundFirst, foundSquare] = [
      0,
      0,
      0,
      0,
      false,
      false,
    ];
    const stack = [];
    for (let i = 0; i < str.length; i++) {
      const char = str[i];
      if (char === "(" && !foundFirst) {
        foundFirst = true;
        stack.push(char);
      } else if (char === "[" && !foundSquare) {
        foundSquare = true;
        stack.push(char);
      } else if (char === ")" && foundFirst) {
        stack.push(char);
        foundFirst = false;
      } else if (char === "]" && foundSquare) {
        stack.push(char);
        foundSquare = false;
      }
    }

    for (let char of stack) {
      if (char === "(") countOpenFirst++;
      else if (char === ")") countCloseFirst++;
      else if (char === "[") countOpenSquare++;
      else if (char === "]") countCloseSquare++;
    }

    console.log(Math.min(countOpenFirst, countCloseFirst) + Math.min(countOpenSquare, countCloseSquare));
  }
}

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

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

function main() {
  let t = +readLine();
  while (t--) {
    const str = readLine();
    let [countOpenFirst, countCloseFirst, countOpenSquare, countCloseSquare, foundFirst, foundSquare] = [
      0,
      0,
      0,
      0,
      false,
      false,
    ];
    const stack = [];
    for (let i = 0; i < str.length; i++) {
      const char = str[i];
      if (char === "(") {
        foundFirst = true;
        stack.push(char);
      } else if (char === "[") {
        foundSquare = true;
        stack.push(char);
      } else if (char === ")" && foundFirst) {
        stack.push(char);
      } else if (char === "]" && foundSquare) {
        stack.push(char);
      }
    }

    for (let char of stack) {
      if (char === "(") countOpenFirst++;
      else if (char === ")") countCloseFirst++;
      else if (char === "[") countOpenSquare++;
      else if (char === "]") countCloseSquare++;
    }

    console.log(Math.min(countOpenFirst, countCloseFirst) + Math.min(countOpenSquare, countCloseSquare));
  }
}


Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:  In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero.  When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.

The first line contains a single integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≤ ai ≤ 105) — the elements of the array.

Print a single integer — the minimum number of seconds needed to make all elements of the array equal to zero.

NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.

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

//Don't have to see. end------------------------------------------
function Main(){
	var N = nextInt();
	var list = nextIntArray();
	var set = new Set();
	for(var i = 0; i < N; i++){
		if(list[i] != 0){
			set.add(list[i]);
		}
	}
	myout(set.size);
}

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

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

  const arr = d.split(' ').map(Number);
  const obj = {};
  let ans = 0;

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

  console.log(ans);
  c++;
});

var n = parseInt( readline() );
var arr = readline().split(' ').map(Number);

var uniqueNumbers = {};
var steps = 0;

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

  if (arr[i] == 0) {
    continue;
  }

  if (!uniqueNumbers[ arr[i] ]) {
    uniqueNumbers[ arr[i] ] = true;
  }
}

for (var uniqueNumber in uniqueNumbers) {
  steps++;
}

print(steps);

var n = readline();
var element = readline();
var probArray = element.split(" ");
var ob = {};
var i;
for ( i = 0; i < n ; i = i + 1) {
    if ( probArray [i] != 0 ) {
      if  (!ob.hasOwnProperty (probArray [i])) {
          ob[ probArray [i] ] = true;
      }
    }
}
var out = 0;
for ( var newOb in ob) {
    out++;
}
print(out);

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

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

  const arr = d.split(' ').map(Number);
  const obj = {};
  let ans = 0;

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

  console.log(ans);
  c++;
});

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

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

  const arr = d.split(' ').map(Number);
  const obj = {};
  let ans = 0;

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

  console.log(ans);
  c++;
});

var n = readline();
var element = readline();
var probArray = element.split(" ");
var ob = {};
var i;
for ( i = 0; i < n ; i = i + 1) {
    if ( probArray [i] !== 0 ) {
      if  (!ob.hasOwnProperty (probArray [i])) {
          ob[ probArray [i] ] = true;
      }
    }
}
var out = 0;
for ( var newOb in ob) {
    out++;
}
print(out);


Phoenix has $$$n$$$ blocks of height $$$h_1, h_2, \dots, h_n$$$, and all $$$h_i$$$ don't exceed some value $$$x$$$. He plans to stack all $$$n$$$ blocks into $$$m$$$ separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than $$$x$$$. Please help Phoenix build $$$m$$$ towers that look beautiful. Each tower must have at least one block and all blocks must be used.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$x$$$ ($$$1 \le m \le n \le 10^5$$$; $$$1 \le x \le 10^4$$$) — the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.  The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le h_i \le x$$$) — the heights of the blocks.  It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$10^5$$$.

For each test case, if Phoenix cannot build $$$m$$$ towers that look beautiful, print NO. Otherwise, print YES, followed by $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$, where $$$y_i$$$ ($$$1 \le y_i \le m$$$) is the index of the tower that the $$$i$$$-th block is placed in. If there are multiple solutions, print any of them.

NoteIn the first test case, the first tower has height $$$1+2+3=6$$$ and the second tower has height $$$1+2=3$$$. Their difference is $$$6-3=3$$$ which doesn't exceed $$$x=3$$$, so the towers are beautiful.In the second test case, the first tower has height $$$1$$$, the second tower has height $$$1+2=3$$$, and the third tower has height $$$3$$$. The maximum height difference of any two towers is $$$3-1=2$$$ which doesn't exceed $$$x=3$$$, so the towers are beautiful.

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

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

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

		for (let i = 0; i < n; i++) {
			h[i] = [h[i], i];
		}
		h.sort((x, y) => x[0] - y[0]);

		const ans = [];
		let twr = 1;
		for (let i = 0; i < n; i++) {
			const [bh, bi] = h[i];
			ans[bi] = twr;
			twr = twr % m + 1;
		}

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


Alice and Bob are playing a game. They have an array of positive integers $$$a$$$ of size $$$n$$$.Before starting the game, Alice chooses an integer $$$k \ge 0$$$. The game lasts for $$$k$$$ stages, the stages are numbered from $$$1$$$ to $$$k$$$. During the $$$i$$$-th stage, Alice must remove an element from the array that is less than or equal to $$$k - i + 1$$$. After that, if the array is not empty, Bob must add $$$k - i + 1$$$ to an arbitrary element of the array. Note that both Alice's move and Bob's move are two parts of the same stage of the game. If Alice can't delete an element during some stage, she loses. If the $$$k$$$-th stage ends and Alice hasn't lost yet, she wins.Your task is to determine the maximum value of $$$k$$$ such that Alice can win if both players play optimally. Bob plays against Alice, so he tries to make her lose the game, if it's possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$).

For each test case, print one integer — the maximum value of $$$k$$$ such that Alice can win if both players play optimally.

'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(),
        a = rns();
  a.sort((a, b) => b - a);
  const check = k => {
    let ans = 0;
    let t = k,
        i = 1;
    for (let l = 0, r = n - 1; l <= r; l++, r--) {
      let cur = k - i + 1;
      while (l <= r && a[l] > cur) l++;
      if (l <= r && a[l] <= cur) ans++;else break;
      i++;
    }
    return ans >= t;
  };
  let l = 0,
      r = n;
  while (l < r) {
    const m = l + r + 1 >> 1;
    if (check(m)) {
      l = m;
    } else {
      r = m - 1;
    }
  }
  return l;
}
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++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      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);
}();

let index = 0;

require('readline').createInterface({
    input: process.stdin
}).on('line', (line) => {
    if(index > 0 && index % 2 == 0) {
        solve(line)
    }

    index++;
});

function solve(str) {
    const nums = str.split(' ').map(num => parseInt(num));
    nums.sort((a, b) => b - a)

    // console.log(nums)
    console.log(binarySearch(nums));
    // console.log(canAliceWin(2, [...nums]))
}

function binarySearch(nums) {
    let low = 0
    let hi = nums.length

    while(low !== hi && low !== hi - 1) {
        let mid = Math.floor((low + hi) / 2);
        // console.log(low, hi, mid )

        if(canAliceWin(mid, [...nums])) {
            low = mid
        } else {
            hi = mid - 1
        }
    }

    return canAliceWin(hi, [...nums]) ? hi : low;
}

function canAliceWin(k, nums) {
    let startLookingAtIndex = 0;
    let round = 1;
    let bobIndex = nums.length - 1;

    for(round = 1; round <= k ; round++) {
        const indexToDelete = nums.findIndex((num, index) => index >= startLookingAtIndex && num <= (k - round + 1));

        if(indexToDelete === -1) {
            return false;
        }

        // "delete"
        startLookingAtIndex = indexToDelete + 1;

        // run out of elements
        if(startLookingAtIndex === nums.length) {
            return round === k;
        }

        // bob turn
        nums[bobIndex] += (k - round + 1);
        bobIndex--;
    }

    return true;
}

"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 = getValue();
    let arr = iInpArr();
    if (n === 1) {
      console.log(arr[0]);
      continue;
    }
    arr.sort((a, b) => b - a);
    const helper = (pos, end) => {
      let st = 0;
      while (pos !== 0) {
        let flag = 0;
        for (let i = st; i <= end; i++) {
          if (arr[i] <= pos) {
            st = i + 1;
            flag = 1;
            break;
          }
        }
        if (flag === 0) return false;
        end--;
        pos--;
      }
      return true;
    };
    let ans = 0,
      st = Math.ceil(n / 2);
    for (let i = 0; i < n && st > 0; i++, st--) {
      if (helper(st, n - 1)) {
        ans = st;
        break;
      }
    }
    console.log(ans);
  }
};
solve();

const fs = require("fs");

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

const testCases = [];
let T;

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

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

    testCases.push(testCase);
  }
}

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

  a.sort((b, c) => b - c);

  let result = Math.ceil(n / 2);
  let found = false;
  for (let k = 0; 2 * k - 1 <= n; k++) {
    for (let i = k - 1; i < k - 1 + k; i++) {
      if (a[i] > i - k + 2) {
        found = true;
        break;
      }
    }
    if (found) {
      result = k - 1;
      break;
    }
  }
  console.log(result);
}

parseInput();

testCases.forEach(solution);

'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(),
        a = rns();
  a.sort((a, b) => b - a);
  const check = k => {
    let ans = 0;
    for (let l = 0, r = n - 1; l <= r; l++, r--) {
      let cur = k - l + 1;
      while (l < r && a[l] > cur) l++;
      if (l <= r && a[l] <= cur) ans++;else break;
    }
    return ans >= k;
  };
  let l = 0,
      r = n * 2;
  while (l < r) {
    const m = l + r + 1 >> 1;
    if (check(m)) {
      l = m;
    } else {
      r = m - 1;
    }
  }
  return l;
}
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++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      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);
}();

'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(),
        a = rns();
  a.sort((a, b) => b - a);
  const check = k => {
    let ans = 0;
    for (let l = 0, r = n - 1; l <= r; l++, r--) {
      let cur = k - l + 1;
      while (l < r && a[l] > cur) l++;
      if (l <= r && a[l] <= cur) ans++;else break;
    }
    return ans >= k;
  };
  let l = 0,
      r = n;
  while (l < r) {
    const m = l + r + 1 >> 1;
    if (check(m)) {
      l = m;
    } else {
      r = m - 1;
    }
  }
  return l;
}
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++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      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);
}();

'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(),
        a = rns();
  a.sort((a, b) => b - a);
  const check = k => {
    let ans = 0;
    for (let l = 0, r = n - 1; l <= r; l++, r--) {
      let cur = k - l + 1;
      while (l <= r && a[l] > cur) l++;
      if (l <= r && a[l] <= cur) ans++;
    }
    return ans >= k;
  };
  let l = 0,
      r = n;
  while (l < r) {
    const m = l + r + 1 >> 1;
    if (check(m)) {
      l = m;
    } else {
      r = m - 1;
    }
  }
  return l;
}
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++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      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);
}();

'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(),
        a = rns();
  a.sort((a, b) => b - a);
  const check = k => {
    let ans = 0;
    for (let l = 0, r = n - 1; l <= r; l++, r--) {
      while (l <= r && a[l] > k) l++;
      if (l <= r && a[l] <= k) ans++;
    }
    return ans >= k;
  };
  let l = 0,
      r = n;
  while (l < r) {
    const m = l + r + 1 >> 1;
    if (check(m)) {
      l = m;
    } else {
      r = m - 1;
    }
  }
  return l;
}
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++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      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);
}();

let index = 0;

require('readline').createInterface({
    input: process.stdin
}).on('line', (line) => {
    if(index > 0 && index % 2 == 0) {
        solve(line)
    }

    index++;
});

function solve(str) {
    const nums = str.split(' ').map(num => parseInt(num));
    nums.sort((a, b) => b - a)

    // console.log(nums)
    console.log(binarySearch(nums));
    // console.log(canAliceWin(2, [...nums]))
}

function binarySearch(nums) {
    let low = 0
    let hi = nums.length

    while(low !== hi && low !== hi - 1) {
        let mid = Math.floor((low + hi) / 2);
        // console.log(low, hi, mid )

        if(canAliceWin(mid, [...nums])) {
            low = mid
        } else {
            hi = mid - 1
        }
    }

    return canAliceWin(hi, [...nums]) ? hi : low;
}

function canAliceWin(k, nums) {
    let startLookingAtIndex = 0;
    let round = 1;
    for(round = 1; round <= k ; round++) {
        const indexToDelete = nums.findIndex((num, index) => index >= startLookingAtIndex && num <= (k - round + 1));

        if(indexToDelete === -1) {
            return false;
        }

        // "delete"
        startLookingAtIndex = indexToDelete + 1;

        // run out of elements
        if(startLookingAtIndex === nums.length) {
            return round === k;
        }

        // bob turn
        const indexToModify = nums.findIndex((num, index) => index >= startLookingAtIndex && num <= (k - round));
        // console.log(indexToModify)
        if(indexToModify > -1) {
            nums[indexToModify] += (k - round + 1);
        }
    }

    return true;
}

let index = 0;

require('readline').createInterface({
    input: process.stdin
}).on('line', (line) => {
    if(index > 0 && index % 2 == 0) {
        solve(line)
    }

    index++;
});

function solve(str) {
    const nums = str.split(' ').map(num => parseInt(num));
    nums.sort((a, b) => b - a)

    // console.log(nums)
    console.log(binarySearch(nums));
    // console.log(canAliceWin(1, [...nums]))
}

function binarySearch(nums) {
    let low = 0
    let hi = nums.length

    while(low !== hi && low !== hi - 1) {
        let mid = Math.floor((low + hi) / 2);
        // console.log(low, hi, mid )

        if(canAliceWin(mid, [...nums])) {
            low = mid
        } else {
            hi = mid - 1
        }
    }

    return canAliceWin(hi, [...nums]) ? hi : low;
}

function canAliceWin(k, nums) {
    let startLookingAtIndex = 0;
    let round = 1;
    for(round = 1; round <= k ; round++) {
        const indexToDelete = nums.findIndex((num, index) => index >= startLookingAtIndex && num <= (k - round + 1));

        if(indexToDelete === -1) {
            return false;
        }

        // "delete"
        startLookingAtIndex = indexToDelete + 1;

        // run out of elements
        if(startLookingAtIndex === nums.length) {
            return round === k;
        }

        // bob turn
        nums[startLookingAtIndex] += (k - round + 1);
    }

    return true;
}

"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 = getValue();
    let arr = iInpArr();
    if (n === 1) {
      console.log(arr[0]);
      continue;
    }
    arr.sort((a, b) => b - a);
    const helper = (pos, st, end) => {
      while (pos !== 0 && st <= end) {
        if (arr[st] > pos) return false;
        pos--;
        st++;
        end--;
      }
      if (pos === 0) return true;
    };
    let ans = 0;
    for (let i = 0; i < n; i++) {
      if (helper(arr[i], i, n - 1)) {
        ans = arr[i];
        break;
      }
    }
    console.log(ans);
  }
};
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 = getValue();
    let arr = iInpArr();
    if (n === 1) {
      console.log(arr[0]);
      continue;
    }
    arr.sort((a, b) => b - a);
    const helper = (pos, st, end) => {
      while (pos !== 0 && st <= end) {
        if (arr[st] > pos) return false;
        pos--;
        st++;
        end--;
      }
      if (pos === 0) return true;
    };
    let ans = 0;
    for (let i = 0; i < n; i++) {
      if (helper(arr[i], i, n - i - 1)) {
        ans = arr[i];
        break;
      }
    }
    console.log(ans);
  }
};
solve();

const fs = require("fs");

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

const testCases = [];
let T;

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

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

    testCases.push(testCase);
  }
}

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

  let result = a.filter((v) => v == 1).length;
  if (result == n && n > 1) result = n - 1;
  console.log(result);
}

parseInput();

testCases.forEach(solution);

const fs = require("fs");

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

const testCases = [];
let T;

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

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

    testCases.push(testCase);
  }
}

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

  let result = a.filter((v) => v == 1).length;
  console.log(result);
}

parseInput();

testCases.forEach(solution);


Petya got an array $$$a$$$ of numbers from $$$1$$$ to $$$n$$$, where $$$a[i]=i$$$.He performed $$$n$$$ operations sequentially. In the end, he received a new state of the $$$a$$$ array.At the $$$i$$$-th operation, Petya chose the first $$$i$$$ elements of the array and cyclically shifted them to the right an arbitrary number of times (elements with indexes $$$i+1$$$ and more remain in their places). One cyclic shift to the right is such a transformation that the array $$$a=[a_1, a_2, \dots, a_n]$$$ becomes equal to the array $$$a = [a_i, a_1, a_2, \dots, a_{i-2}, a_{i-1}, a_{i+1}, a_{i+2}, \dots, a_n]$$$.For example, if $$$a = [5,4,2,1,3]$$$ and $$$i=3$$$ (that is, this is the third operation), then as a result of this operation, he could get any of these three arrays:  $$$a = [5,4,2,1,3]$$$ (makes $$$0$$$ cyclic shifts, or any number that is divisible by $$$3$$$);  $$$a = [2,5,4,1,3]$$$ (makes $$$1$$$ cyclic shift, or any number that has a remainder of $$$1$$$ when divided by $$$3$$$);  $$$a = [4,2,5,1,3]$$$ (makes $$$2$$$ cyclic shifts, or any number that has a remainder of $$$2$$$ when divided by $$$3$$$). Let's look at an example. Let $$$n=6$$$, i.e. initially $$$a=[1,2,3,4,5,6]$$$. A possible scenario is described below.  $$$i=1$$$: no matter how many cyclic shifts Petya makes, the array $$$a$$$ does not change.  $$$i=2$$$: let's say Petya decided to make a $$$1$$$ cyclic shift, then the array will look like $$$a = [\textbf{2}, \textbf{1}, 3, 4, 5, 6]$$$.  $$$i=3$$$: let's say Petya decided to make $$$1$$$ cyclic shift, then the array will look like $$$a = [\textbf{3}, \textbf{2}, \textbf{1}, 4, 5, 6]$$$.  $$$i=4$$$: let's say Petya decided to make $$$2$$$ cyclic shifts, the original array will look like $$$a = [\textbf{1}, \textbf{4}, \textbf{3}, \textbf{2}, 5, 6]$$$.  $$$i=5$$$: let's say Petya decided to make $$$0$$$ cyclic shifts, then the array won't change.  $$$i=6$$$: let's say Petya decided to make $$$4$$$ cyclic shifts, the array will look like $$$a = [\textbf{3}, \textbf{2}, \textbf{5}, \textbf{6}, \textbf{1}, \textbf{4}]$$$. You are given a final array state $$$a$$$ after all $$$n$$$ operations. Determine if there is a way to perform the operation that produces this result. In this case, if an answer exists, print the numbers of cyclical shifts that occurred during each of the $$$n$$$ operations.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of the description of each test case contains one integer $$$n$$$ ($$$2 \le n \le 2\cdot10^3$$$) — the length of the array $$$a$$$. The next line contains the final state of the array $$$a$$$: $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) are written. All $$$a_i$$$ are distinct. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2\cdot10^3$$$.

For each test case, print the answer on a separate line. Print -1 if the given final value $$$a$$$ cannot be obtained by performing an arbitrary number of cyclic shifts on each operation. Otherwise, print $$$n$$$ non-negative integers $$$d_1, d_2, \dots, d_n$$$ ($$$d_i \ge 0$$$), where $$$d_i$$$ means that during the $$$i$$$-th operation the first $$$i$$$ elements of the array were cyclic shifted to the right $$$d_i$$$ times. If there are several possible answers, print the one where the total number of shifts is minimal (that is, the sum of $$$d_i$$$ values is the smallest). If there are several such answers, print any of them.

NoteThe first test case matches the example from the statement.The second set of input data is simple. Note that the answer $$$[3, 2, 1]$$$ also gives the same permutation, but since the total number of shifts $$$3+2+1$$$ is greater than $$$0+0+1$$$, this answer is not correct.

"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 solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    let obj = {};
    arr.map((i, j) => {
      obj[i] = j + 1;
      return i;
    });
    const help = (j, rotate) => {
      let k = n;
      for (let i = 0; i < rotate.length; i++, k--) j = (j + rotate[i]) % k;
      return j;
    };
    let rotate = [],
      res = new Array(n).fill(0);
    for (let i = n; i >= 1; i--) {
      let j = obj[i];
      j = help(j, rotate);
      if (j === i) {
        rotate.push(0);
        continue;
      } else {
        res[i - 1] = j;
        rotate.push(i - j);
      }
    }
    console.log(res.join(" "));
  }
};
solve();

'use strict';

var fs = require('fs');

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

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

function solve(n, data) {
  const map = [];

  for (let i = 0; i < data.length; i++) {
    map[data[i]] = i + 1;
  }

  let res = [];

  for (let i = map.length - 1; i > 0; i--) {
    let cur = map[i];

    if (i === cur) {
      res.push(0);
      continue;
    }

    res.push(cur);

    for (let j = 1; j < i; j++) {
      map[j] = (map[j] - cur + i) % i;
    }
  }

  return res.reverse();
}

// const inputs = fs.readFileSync(path.join(__dirname, './codeforces.test.txt'), 'utf-8').split('\n')

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

  for (let __ = 0; __ < _; __++) {
    const n = Number(inputs[__ * 2 + 1]);
    const data = inputs[__ * 2 + 2].trim().split(' ').map(Number);
    const res = solve(n, data);
    console.log(res.join(' '));
  }
}();

'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 a;
// [l,r)
function reverse(l, r) {
    r--;
    while (l < r) {
        let t = a[l];
        a[l] = a[r];
        a[r] = t;
        l++;
        r--;
    }
}
// [l,r)
function rotate(r, n) {
    reverse(0, r);
    reverse(r, n);
    reverse(0, n);
}
function solve(n) {
    const ans = [];
    for (let i = n - 1; i >= 0; i--) {
        let want = i + 1;
        if (a[i] == want) {
            ans.push(0);
            continue;
        }
        let pos = a.findIndex((e) => e == want);
        rotate(pos + 1, i + 1);
        ans.push(pos + 1);
    }
    for (let i = n - 1; i >= 0; i--) {
        printf("%d ", ans[i]);
    }
    printf("\n");
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        let n = nextInt();
        a = af(n);
        for (let i = 0; i < n; i++) {
            a[i] = nextInt();
        }
        solve(n);
    }
}

'use strict'; /*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++];
}

module.exports = E;

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

const EPS = 1e-6;

const calc = (n, arr)=>{
  let ops = [];
  for (let i=n; i>=1; i--){
    let index = arr.indexOf(i);
    if (index==-1)
      throw 'what'
    ops.push((index+1)%i);
    //console.log('ARR ', {index, i}, arr)
    arr = [].concat(arr.slice(index+1), arr.slice(0, index));
    //console.log('=>', arr)
  }
  //console.log('ANS')
  return ops.reverse();
};

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

E.calc = calc;

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

function solve(n, arr) {
    let cur = n
    const ans = Array(n)
    let p = n - 1
    while (cur >= 1) {
        let idx = arr.indexOf(cur) + 1
        if (idx <= 0) return -1
        ans[p--] = idx % cur

        const next = Array(cur)
        for (let i = 0; i < cur; i++) {
            next[(i - idx + cur) % cur] = arr[i]
        }
    // console.log(next)
        arr = next
        cur--
    }
    return ans.join(' ')
}

function solve() {
   const n = Number(read());
   let currentMap = [];
   read().split(' ').forEach((x, i) => {
      currentMap[Number(x)] = i + 1;
   });
   const ans = [];
   for (let i = n; i > 0; i--) {
      const nextMap = [];
      const index = currentMap[i];
      if (index === i) {
         ans.push(0);
         continue;
      }
      const diff = i - index;
      ans.push(index);
      for (let j = 1; j <= n; j++) {
         const jindex = currentMap[j];
         if (j > i) {
            nextMap[j] = jindex;
            continue;
         }
         if (jindex <= index) {
            nextMap[j] = jindex + diff;
            continue;
         }
         nextMap[j] = jindex - index;
      }
      currentMap = nextMap;
   }
   ans.reverse();
   write(ans.join(' '));
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function pDivCount(n) {
   let ans = 0;
   let i = 1;
   while(n > 1) {
      i++;
      while(n % i === 0) {
         ans++;
         n = Math.floor(n / i);
      }
   }
   return ans;
}

function gcd(a, b) {
   if (a === 0) {
      return b;
   }
   return gcd(b % a, a);
}

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

function init() {
   try {
      var T;
      T = 1;
      T = Number(read());
      for (var t = 0; t < T; t++) {
         solve();
      }
   } catch (e) {
      write(e);
   }
}

function readArray(mapF) {
   var res = read().split(' ');
   if (mapF) {
      res = res.map(mapF);
   }
   return res;
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }
   MEMORY = fs.readFileSync(inTextName ? require('path').join(__dirname, inTextName) : 0, 'utf8').split('\r\n');
}
init();

function write(value) {
   isNode ? console.log('' + value) : print('' + value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}
function readAll() {
   if (isNode) {
      return MEMORY;
   }
   var res = [];
   var x;
   while (x = read()) {
      res.push(x);
   }
   return res;
}


Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second.The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse.Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight.

The first line of the input contains a single integer l (1 ≤ l ≤ 1 000) — the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≤ p, q ≤ 500) — the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively.

Print a single real number — the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4.  Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if .

NoteIn the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor.

/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	var d8 = __webpack_require__(1);
	var L = d8.readnumbers()[0];
	var p = d8.readnumbers()[0];
	var q = d8.readnumbers()[0];
	var t = L / (p + q);
	print(p * t);

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	var List = __webpack_require__(2);
	function readnumbers() {
	    return List.map(parseInt, readline().split(' '));
	}
	exports.readnumbers = readnumbers;

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	var Prelude_1 = __webpack_require__(3);
	function add(xs, ys) {
	    return xs.concat(ys);
	}
	exports.add = add;
	function head(xs) {
	    return xs[0];
	}
	exports.head = head;
	function last(xs) {
	    return xs[xs.length - 1];
	}
	exports.last = last;
	function tail(xs) {
	    return xs.slice(1);
	}
	exports.tail = tail;
	function init(xs) {
	    return xs.slice(0, xs.length - 1);
	}
	exports.init = init;
	function map(f, xs) {
	    var result = new Array(xs.length);
	    for (var i = 0; i < xs.length; i++) {
	        result[i] = f(xs[i]);
	    }
	    return result;
	}
	exports.map = map;
	function reverse(xs) {
	    return xs.slice().reverse();
	}
	exports.reverse = reverse;
	function intersperse(x, xs) {
	    if (xs.length == 0) {
	        return [];
	    }
	    var result = new Array(xs.length + xs.length - 1);
	    for (var i = 0; i + 1 < xs.length; i++) {
	        result[i + i] = xs[i];
	        result[i + i + 1] = x;
	    }
	    result[result.length - 1] = xs[xs.length - 1];
	    return result;
	}
	exports.intersperse = intersperse;
	function intercalate(xs, xss) {
	    return concat(intersperse(xs, xss));
	}
	exports.intercalate = intercalate;
	function foldl(f, initial, xs) {
	    var result = initial;
	    for (var i = 0; i < xs.length; i++) {
	        result = f(result, xs[i]);
	    }
	    return result;
	}
	exports.foldl = foldl;
	function foldr(f, initial, xs) {
	    var result = initial;
	    for (var i = xs.length - 1; i >= 0; i--) {
	        result = f(xs[i], result);
	    }
	    return result;
	}
	exports.foldr = foldr;
	function concat(xss) {
	    var total = sum(map(function (xs) { return xs.length; }, xss));
	    var result = new Array(total);
	    var m = 0;
	    for (var i = 0; i < xss.length; i++) {
	        var xs = xss[i];
	        for (var j = 0; j < xs.length; j++) {
	            result[m++] = xs[j];
	        }
	    }
	    return result;
	}
	exports.concat = concat;
	function sum(xs) {
	    var result = 0;
	    for (var i = 0; i < xs.length; i++) {
	        result += xs[i];
	    }
	    return result;
	}
	exports.sum = sum;
	function product(xs) {
	    var result = 1;
	    for (var i = 0; i < xs.length; i++) {
	        result *= xs[i];
	    }
	    return result;
	}
	exports.product = product;
	function sort(xs, compare) {
	    return copy(xs).sort(compare);
	}
	exports.sort = sort;
	function sortInPlace(xs, compare) {
	    xs.sort(compare);
	    return xs;
	}
	exports.sortInPlace = sortInPlace;
	function maximumInRange(xs, s, e) {
	    var result = xs[s];
	    for (var i = s + 1; i <= e; i++) {
	        if (result < xs[i])
	            result = xs[i];
	    }
	    return result;
	}
	exports.maximumInRange = maximumInRange;
	function maximum(xs) {
	    return maximumInRange(xs, 0, xs.length - 1);
	}
	exports.maximum = maximum;
	function maximumInRangeWith(xs, s, e, f) {
	    var result = f(xs[s]);
	    for (var i = s + 1; i <= e; i++) {
	        var candidate = f(xs[i]);
	        if (result < candidate)
	            result = candidate;
	    }
	    return result;
	}
	exports.maximumInRangeWith = maximumInRangeWith;
	function maximumWith(xs, f) {
	    return maximumInRangeWith(xs, 0, xs.length - 1, f);
	}
	exports.maximumWith = maximumWith;
	function minimumInRange(xs, s, e) {
	    var result = xs[s];
	    for (var i = s + 1; i <= e; i++) {
	        if (result > xs[i])
	            result = xs[i];
	    }
	    return result;
	}
	exports.minimumInRange = minimumInRange;
	function minimum(xs) {
	    return minimumInRange(xs, 0, xs.length - 1);
	}
	exports.minimum = minimum;
	function minimumInRangeWith(xs, s, e, f) {
	    var result = f(xs[s]);
	    for (var i = s + 1; i <= e; i++) {
	        var candidate = f(xs[i]);
	        if (result > candidate)
	            result = candidate;
	    }
	    return result;
	}
	exports.minimumInRangeWith = minimumInRangeWith;
	function minimumWith(xs, f) {
	    return minimumInRangeWith(xs, 0, xs.length - 1, f);
	}
	exports.minimumWith = minimumWith;
	function replicate(n, x) {
	    var result = new Array(n);
	    for (var i = 0; i < result.length; i++) {
	        result[i] = x;
	    }
	    return result;
	}
	exports.replicate = replicate;
	function take(n, xs) {
	    return xs.slice(0, n);
	}
	exports.take = take;
	function drop(n, xs) {
	    return xs.slice(n);
	}
	exports.drop = drop;
	function splitAt(n, xs) {
	    return [take(n, xs), drop(n, xs)];
	}
	exports.splitAt = splitAt;
	function takeWhile(f, xs) {
	    for (var i = 0; i < xs.length; i++) {
	        if (!f(xs[i])) {
	            return xs.slice(0, i);
	        }
	    }
	    return xs.slice();
	}
	exports.takeWhile = takeWhile;
	function dropWhile(f, xs) {
	    for (var i = 0; i < xs.length; i++) {
	        if (!f(xs[i])) {
	            return xs.slice(i);
	        }
	    }
	    return [];
	}
	exports.dropWhile = dropWhile;
	function group(xs) {
	    if (xs.length == 0)
	        return [];
	    var result = [];
	    var last = [xs[0]];
	    for (var i = 1; i < xs.length; i++) {
	        if (last[0] === xs[i]) {
	            last.push(xs[i]);
	        }
	        else {
	            result.push(last);
	            last = [xs[i]];
	        }
	    }
	    result.push(last);
	    return result;
	}
	exports.group = group;
	function nub(xs) {
	    if (xs.length == 0)
	        return [];
	    var result = [];
	    result.push(xs[0]);
	    for (var i = 1; i < xs.length; i++) {
	        if (xs[i] !== xs[i - 1]) {
	            result.push(xs[i]);
	        }
	    }
	    return result;
	}
	exports.nub = nub;
	function filter(f, xs) {
	    var result = [];
	    for (var i = 0; i < xs.length; i++) {
	        if (f(xs[i]))
	            result.push(xs[i]);
	    }
	    return result;
	}
	exports.filter = filter;
	function zip(xs, ys) {
	    var n = Prelude_1.min(xs.length, ys.length);
	    var result = new Array(n);
	    for (var i = 0; i < n; i++) {
	        result[i] = [xs[i], ys[i]];
	    }
	    return result;
	}
	exports.zip = zip;
	function unzip(xs) {
	    var r1 = new Array(xs.length);
	    var r2 = new Array(xs.length);
	    for (var i = 0; i < xs.length; i++) {
	        r1[i] = xs[i][0];
	        r2[i] = xs[i][1];
	    }
	    return [r1, r2];
	}
	exports.unzip = unzip;
	function range(from, to) {
	    var result = Array(to - from + 1);
	    for (var i = from; i <= to; i++) {
	        result[i - from] = i;
	    }
	    return result;
	}
	exports.range = range;
	function copy(xs) {
	    return xs.slice(0);
	}
	exports.copy = copy;
	function apply_permutation(p, xs) {
	    var n = xs.length;
	    var result = new Array(n);
	    for (var i = 0; i < n; i++) {
	        result[i] = xs[p[i]];
	    }
	    return result;
	}
	exports.apply_permutation = apply_permutation;
	function next_permutation(p) {
	    var n = p.length;
	    if (n < 2)
	        return null;
	    var r = copy(p);
	    var k = n - 2;
	    for (; k >= 0 && r[k] >= r[k + 1]; k--)
	        ;
	    if (k < 0)
	        return null;
	    for (var i = k + 1, j = n - 1; i < j; i++, j--) {
	        var t_1 = r[i];
	        r[i] = r[j];
	        r[j] = t_1;
	    }
	    var next = k + 1;
	    for (; r[next] <= r[k]; next++)
	        ;
	    var t = r[k];
	    r[k] = r[next];
	    r[next] = t;
	    return r;
	}
	exports.next_permutation = next_permutation;
	function create(n, value) {
	    return replicate(n, value);
	}
	exports.create = create;
	function createWith(n, f) {
	    var result = new Array(n);
	    for (var i = 0; i < n; i++) {
	        result[i] = f(i);
	    }
	    return result;
	}
	exports.createWith = createWith;
	function create2D(n1, n2, value) {
	    return map(function (_) { return replicate(n2, value); }, replicate(n1, 0));
	}
	exports.create2D = create2D;
	function create2DWith(n1, n2, f) {
	    var result = new Array(n1);
	    for (var i = 0; i < n1; i++) {
	        result[i] = new Array(n2);
	        for (var j = 0; j < n2; j++) {
	            result[i][j] = f(i, j);
	        }
	    }
	    return result;
	}
	exports.create2DWith = create2DWith;

/***/ },
/* 3 */
/***/ function(module, exports) {

	function min(a, b) {
	    return a < b ? a : b;
	}
	exports.min = min;
	function max(a, b) {
	    return a < b ? b : a;
	}
	exports.max = max;
	function curry(f) {
	    return function (x) { return function (y) { return f(x, y); }; };
	}
	exports.curry = curry;
	function uncurry(f) {
	    return function (x, y) { return f(x)(y); };
	}
	exports.uncurry = uncurry;
	function id(x) {
	    return x;
	}
	exports.id = id;
	function constant(x) {
	    return function (_) { return x; };
	}
	exports.constant = constant;
	function flip(f) {
	    return function (y) { return function (x) { return f(x)(y); }; };
	}
	exports.flip = flip;
	function flip2(f) {
	    return function (y, x) { return f(x, y); };
	}
	exports.flip2 = flip2;
	function compose(g, f) {
	    return function (x) { return g(f(x)); };
	}
	exports.compose = compose;
	function gcd(a, b) {
	    var r = a % b;
	    while (r !== 0) {
	        a = b;
	        b = r;
	        r = a % b;
	    }
	    return b;
	}
	exports.gcd = gcd;

/***/ }
/******/ ]);

var l = parseInt(readline()),
	p = parseInt(readline()),
	q = parseInt(readline()),
	t1, t2;

t1 = l / (p+q);
t2 = t1 * p;

print(t2);

try {require('codef');} catch (e){global = this};
function readLineAsArray(separator){return readline().split(typeof separator == "undefined" ? ' ' : separator)}
function readLineAsIntegerArray(separator){return readLineAsArray(separator).map(function(v){return +v})}
Array.prototype.list = function() {var length = arguments.length; for(var i=0; i < length; i++){global[arguments[i]] = this[i]}};
String.prototype.repeat = function(n){return new Array(n + 1).join(this);}

var l = +readline(),
    p = +readline(),
    q = +readline();

write(l * p / (p + q));

var l = parseInt(readline(), 10),
    p = parseInt(readline(), 10),
    q = parseInt(readline(), 10);

function calcLength (l, p, q) {
    return (l / (p + q)) * p;
}

write(calcLength(l, p, q));

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

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

  if (c === 1) {
    c++;
    p = +d;
    return;
  }

  q = +d;

  c++;
});

rl.on('close', () => {
  console.log((l * (p / (p + q))).toFixed(4));
});

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

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

  if (c === 1) {
    c++;
    p = +d;
    return;
  }

  q = +d;

  c++;
});

rl.on('close', () => {
  const max = Math.max(p, q);
  let ans = max / 100 * l;

  if (max >= l) {
    ans = l * 2 / ((p + q) * 2);
    // console.log({ ans})
  }

  console.log(ans.toFixed(4));
});

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

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

  if (c === 1) {
    c++;
    p = +d;
    return;
  }

  q = +d;

  c++;
});

rl.on('close', () => {
  if (p === q) {
    console.log((l / 2).toFixed(4));
    return;
  }

  if (p + q <= l) {
    console.log((Math.max(p, q) / 100 * l).toFixed(4));
    return;
  }

  if (p > l) {
    console.log(((p * 100 / (p + q)) / 100).toFixed(4));
    return;
  }

  console.log((p * 100 / (p + q)).toFixed(4));
});

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

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

  if (c === 1) {
    c++;
    p = +d;
    return;
  }

  q = +d;

  c++;
});

rl.on('close', () => {
  const max = Math.max(p, q);
  const ans = max / 100 * l;

  console.log(ans.toFixed(4));
});

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

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

  if (c === 1) {
    c++;
    p = +d;
    return;
  }

  q = +d;

  c++;
});

rl.on('close', () => {
  const max = Math.max(p, q);
  let ans = max / 100 * l;

  if (max === l) {
    ans = max / 2;
  }

  console.log(ans.toFixed(4));
});

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

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

  if (c === 1) {
    c++;
    p = +d;
    return;
  }

  q = +d;

  c++;
});

rl.on('close', () => {
  const max = Math.max(p, q);
  let ans = max / 100 * l;

  if (p + q > l) {
    ans = l * 2 / ((p + q) * 2);

    if (p > q) {
      ans = l - ans;
    }
  }

  console.log(ans.toFixed(4));
});