A basketball competition is held where the number of players in a team does not have a maximum or minimum limit (not necessarily $$$5$$$ players in one team for each match). There are $$$N$$$ candidate players in the competition that will be trained by Pak Chanek, the best basketball coach on earth. The $$$i$$$-th candidate player has a power of $$$P_i$$$.Pak Chanek will form zero or more teams from the $$$N$$$ candidate players on the condition that each candidate player may only join in at most one team. Each of Pak Chanek's teams will be sent to compete once with an enemy team that has a power of $$$D$$$. In each match, the team sent is said to defeat the enemy team if the sum of powers from the formed players is strictly greater than $$$D$$$.One of Pak Chanek's skills is that when a team that has been formed plays in a match, he can change the power of each player in the team to be equal to the biggest player power from the team.Determine the maximum number of wins that can be achieved by Pak Chanek.

The first line contains two integers $$$N$$$ and $$$D$$$ ($$$1 \le N \le 10^5$$$, $$$1 \le D \le 10^9$$$) — the number of candidate players and the power of the enemy team. The second line contains $$$N$$$ integers $$$P_1, P_2, \ldots, P_N$$$ ($$$1 \le P_i \le 10^9$$$) — the powers of all candidate players.

A line containing an integer representing the maximum number of wins that can be achieved by Pak Chanek.

NoteThe $$$1$$$-st team formed is a team containing players $$$4$$$ and $$$6$$$. The power of each player in the team becomes $$$100$$$. So the total power of the team is $$$100 + 100 = 200 > 180$$$.The $$$2$$$-nd team formed is a team containing players $$$1$$$, $$$2$$$, and $$$5$$$. The power of each player in the team becomes $$$90$$$. So the total power of the team is $$$90 + 90 + 90 = 270 > 180$$$.

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}
let i=0;let j=players.length;

while(true){
    if(j===0||j<bigger(players[i],d)){break;}
    j=j-bigger(players[i],d)
    i++;

    sol++;

}
console.log(sol);
}

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

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

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********
function main() {
    var input = readline().split(" ");
    var players = readline().split(" ");
//   var input = "6 180".split(" ");
//   var players = "90 80 70 60 50 100 2".split(" ");
  players = players.sort((a, b) => b - a);
  let minPoints = input[1],
    left = 0,
    right = players.length;
  while (left + Math.floor(minPoints / players[left]) < right) {
    right -= Math.floor(minPoints / players[left]);
    left++;
  }
  console.log(left);
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    /*

    */
    let a = readLine().trim().split(' ').map(string => {return parseInt(string.trim());});
    let N = a[0], D = a[1];
    a = readLine().trim().split(' ').map(string => {return parseInt(string.trim());});
    a.sort((a, b) => b - a); // For descending sort
    let i=0,count=0;
    while(N>0){
        N-=Math.ceil(D/a[i]);
        if(Math.ceil(D/a[i])*a[i] == D){
            N-=1;
        }
        // console.log(D,a[i],N);
        i++;
    }
    if(N<0){
        i--;
    }
    console.log(i);
    }

'use strict';

var readline = require('readline');

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

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

async function solve(r) {
  const rns = async () => {
    return (await r()).split(' ').filter(s => s !== '').map(Number);
  };
  const [n, m] = await rns();
  const a = await rns();
  a.sort((a, b) => a - b);
  let left = 0,
      right = n - 1;
  let res = 0;
  while (left <= right) {
    let num = a[right];
    while (left < right && num <= m) {
      num += a[right];
      left++;
    }
    if (num > m) res++;
    right--;
  }
  return res;
}

async function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      res[i] = await solve(r);
    }
    return res.join('\n');
  } catch (error) {
    console.log('zdebug' + error);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
async function read() {
  return (await it.next()).value;
}
void async function () {
  const output = await main(read);
  process.stdout.write(output);
}();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}
let i=0;let j=players.length;

while(true){
    if(j===0||j<bigger(players[i],d)){break;}
    j=players.length-bigger(players[i],d)
    i++;

    sol++;

}
console.log(sol);
}

function main(){
var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}

while(true){
    if(players.length<bigger(players[0],d)){break;}
    players.splice(players.length-bigger(players[0],d)+1,bigger(players[0],d)-1)
    players.shift();
    sol++;

}
console.log(sol,sol,sol,1,2,3);

}

function main(){
var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}

while(true){
    if(players.length<bigger(players[0],d)){break;}
    players.splice(players.length-bigger(players[0],d)+1,bigger(players[0],d)-1)
    players.shift();
    sol++;

}
console.log(sol+" ");

}

function main(){
var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}

while(true){
    if(players.length<bigger(players[0],d)){break;}
    players.splice(players.length-bigger(players[0],d)+1,bigger(players[0],d)-1)
    players.shift();
    sol++;

}
console.log(sol);

}

function main(){
var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}

while(true){
    if(players.length<bigger(players[0],d)){console.log(2);break;}
    players.splice(players.length-bigger(players[0],d)+1,bigger(players[0],d)-1)
    players.shift();
    sol++;

}

}

function main(){
var num = [6, 180];

var n=num[0];
var d=num[1];
var players= [90, 80, 70, 60, 50, 100];
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}

while(true){
    if(players.length<bigger(players[0],d)){console.log(sol);break;}
    players.splice(players.length-bigger(players[0],d)+1,bigger(players[0],d)-1);
    players.shift();
    sol++;

}

}

function main(){
var num = readline().split(" ").map(x => parseInt(x));

var n=num[0];
var d=num[1];
var players= readline().split(" ").map(x => parseInt(x));
players.sort(function(a, b){return b-a});
var sol=0;

function bigger(p,d){
    if(p>d){return 1;}
    else {
        if(d%p===0){return d/p+1;}
        else{return Math.ceil(d/p)}
    }
}

while(true){
    if(players.length<bigger(players[0],d)){console.log(sol);break;}
    players.splice(players.length-bigger(players[0],d)+1,bigger(players[0],d)-1)
    players.shift();
    sol++;

}

}

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

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

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********
function main() {
  var input = readline().split(" ");
  var players = readline().split(" ");
  //   var input = "6 180".split(" ");
  //   var players = "90 80 70 60 50 100 2 2".split(" ");
  players = players.sort((a, b) => b - a);
  let minPoints = input[1],
    left = 0,
    right = players.length;
  while (left + Math.floor(minPoints / players[left]) < right) {
    console.log(left, right, players[left]);
    right -= Math.floor(minPoints / players[left]);
    left++;
  }
}

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

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

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
  var input = readline().split(" ");
  var players = readline().split(" ");
  //   var input = "60 180".split(" ");
  //   var players = "90 80 70 60 50 100".split(" ");
  let minPoints = input[1];
  let counter = 0;
  players = players.sort((a, b) => b - a);
  while (players.length > Math.ceil(minPoints / players[0])) {
    let wannaPlayer = Math.floor(minPoints / players[0]);
    players.splice(0, 1);
    for (let i = 0; i < wannaPlayer; i++) {
      players.length--;
    }
    counter++;
  }
  console.log(counter);
}

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

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

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}
// ********** Code Start **********
function main() {
    var input = readline().split(" ");
    var players = readline().split(" ");
//   var input = "6 180".split(" ");
//   var players = "90 80 70 60 50 100 2 2".split(" ");
  let leng = players.length;
  let minPoints = input[1];
  players = players.sort((a, b) => b - a);
  let i = 0;
  while (leng > Math.ceil(minPoints / players[i])) {
    // console.log("leng befor is " + leng);
    // console.log("player" + i + "=" + players[i]);
    leng -= Math.ceil(minPoints / players[i]);
    i++;
  }
  console.log(i);
}
// main();

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

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

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}
// ********** Code Start **********
function main() {
  var input = readline().split(" ");
  var players = readline().split(" ");
  //   var input = "6 180".split(" ");
  //   var players = "100 90 80 70 60 50 2 2".split(" ");
  let leng = players.length;
  let minPoints = input[1];
  let counter = 0;
  players = players.sort((a, b) => b - a);
  let i = 0;
  while (leng > 0) {
    // console.log("leng befor is " + leng);
    // console.log("player" + i + "=" + players[i]);
    leng -= Math.ceil(minPoints / players[i]);
    i++;
  }
  console.log(i - 1);
}

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

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

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
  let input = readline().split(" ");
  let players = readline().split(" ");
  let minPoints = input[1];
  let counter = 0;
  players = players.sort((a, b) => b - a);
  while (players.length - Math.ceil(minPoints / players[0]) > 0) {
    let wannaPlayer = Math.floor(minPoints / players[0]);
    players.splice(0, 1);
    for (let i = 0; i < wannaPlayer; i++) {
      players.length--;
    }
    counter++;
  }
  console.log(counter);
}

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

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

process.stdin.on("data", (inputStdin) => {
  inputString += inputStdin;
});
process.stdin.on("end", () => {
  inputString = inputString.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

// ********** Code Start **********

function main() {
  var input = readline().split(" ");
  var players = readline().split(" ");
  let playersLength = input[0];
  let minPoints = input[1];
  let counter = 0;
  players = players.sort((a, b) => b - a);
  while (players.length - Math.floor(minPoints / players[0]) > 0) {
    let wannaPlayer = Math.floor(minPoints / players[0]);
    players.splice(0, 1);
    for (let i = 0; i < wannaPlayer; i++) {
      players.length--;
    }
    counter++;
  }
  return counter;
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    /*

    */
    let a = readLine().trim().split(' ').map(string => {return parseInt(string.trim());});
    let N = a[0], D = a[1];
    a = readLine().trim().split(' ').map(string => {return parseInt(string.trim());});
    a.sort((a, b) => b - a); // For descending sort
    let i=0;
    while(N>0){
        if(D>a[i]){
            N-=Math.ceil(D/a[i]);
        }else{
            N-=1;
        }
        i++;
    }
    i--;
    console.log(i);
    }

'use strict';

var readline = require('readline');

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

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

async function solve(r) {
  const rns = async () => {
    return (await r()).split(' ').filter(s => s !== '').map(Number);
  };
  const [n, m] = await rns();
  const a = await rns();
  a.sort((a, b) => a - b);
  let left = 0,
      right = n - 1;
  let res = 0;
  while (left <= right) {
    let num = a[right];
    while (left < right && num < m) {
      num += a[right];
      left++;
    }
    if (num >= m) res++;
    right--;
  }
  return res;
}

async function main(r) {
  try {
    let t = 1;
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      res[i] = await solve(r);
    }
    return res.join('\n');
  } catch (error) {
    console.log('zdebug' + error);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
const it = rl[Symbol.asyncIterator]();
async function read() {
  return (await it.next()).value;
}
void async function () {
  const output = await main(read);
  process.stdout.write(output);
}();


An agent called Cypher is decrypting a message, that contains a composite number $$$n$$$. All divisors of $$$n$$$, which are greater than $$$1$$$, are placed in a circle. Cypher can choose the initial order of numbers in the circle.In one move Cypher can choose two adjacent numbers in a circle and insert their least common multiple between them. He can do that move as many times as needed.A message is decrypted, if every two adjacent numbers are not coprime. Note that for such constraints it's always possible to decrypt the message.Find the minimal number of moves that Cypher should do to decrypt the message, and show the initial order of numbers in the circle for that.

The first line contains an integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. Next $$$t$$$ lines describe each test case. In a single line of each test case description, there is a single composite number $$$n$$$ $$$(4 \le n \le 10^9)$$$ — the number from the message. It's guaranteed that the total number of divisors of $$$n$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case in the first line output the initial order of divisors, which are greater than $$$1$$$, in the circle. In the second line output, the minimal number of moves needed to decrypt the message. If there are different possible orders with a correct answer, print any of them.

NoteIn the first test case $$$6$$$ has three divisors, which are greater than $$$1$$$: $$$2, 3, 6$$$. Regardless of the initial order, numbers $$$2$$$ and $$$3$$$ are adjacent, so it's needed to place their least common multiple between them. After that the circle becomes $$$2, 6, 3, 6$$$, and every two adjacent numbers are not coprime.In the second test case $$$4$$$ has two divisors greater than $$$1$$$: $$$2, 4$$$, and they are not coprime, so any initial order is correct, and it's not needed to place any least common multiples.In the third test case all divisors of $$$30$$$ greater than $$$1$$$ can be placed in some order so that there are no two adjacent numbers that are coprime.

"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 t = +inputs[0];
    var p = [2];
    for (let i = 3; i < 1e5; i += 2) {
        let prime = true;
        for (let v of p) {
            if (v * v > i)
                break;
            if (i % v == 0) {
                prime = false;
                break;
            }
        }
        if (prime)
            p.push(i);
    }
    for (let i = 0; i < t; i++) {
        var x = +inputs[i + 1];
        var c = Array(p.length).fill(0);
        for (let j = 0;; j++) {
            if (p[j] * p[j] > x) {
                if (x > 1) {
                    p.push(x);
                    c[p.length - 1] = 1;
                }
                break;
            }
            while (x % p[j] == 0) {
                x /= p[j];
                c[j]++;
            }
        }
        var cp = c.map((v, i) => v ? p[i] : 0).filter(v => v);
        c = c.filter(v => v);
        let mark = {};
        let arr = [];
        for (let i = 0; i < c.length; i++) {
            let bit = Array(c.length).fill(0);
            bit[i] = 1;
            arr.push(bit);
            mark[bit.join('')] = 1;
            bit = Array(c.length).fill(0);
            bit[i] = 1;
            bit[(i + 1) % c.length] = 1;
            arr.push(bit);
            mark[bit.join('')] = 1;
        }
        if (c.length <= 2)
            arr.pop();
        let c2 = 2 ** c.length;
        while (arr.length < c2 - 1) {
            for (let i = 1; i < c2; i++) {
                let bit = Array(c.length).fill(0);
                for (let j = 0; j < c.length; j++)
                    bit[j] = i & (1 << j) ? 1 : 0;
                if (mark[bit.join('')])
                    continue;
                if (bit.some((v, i) => arr[arr.length - 1][i] == v)) {
                    arr.push(bit);
                    mark[bit.join('')] = 1;
                }
            }
        }
        // console.log(arr);
        var c0 = [...arr[0]];
        var p0 = 1;
        var pp = [];
        function gen(i) {
            if (i == c.length)
                return pp.push(p0);
            if (!c0[i])
                return gen(i + 1);
            for (let j = 1; j <= c[i]; j++) {
                p0 *= cp[i] ** j;
                gen(i + 1);
                p0 /= cp[i] ** j;
            }
        }
        var arrGen = [];
        for (let i = 0; i < arr.length; i++) {
            c0 = arr[i].slice();
            p0 = 1;
            pp = [];
            gen(0);
            arrGen[i] = pp;
        }
        if (c.length == 2)
            arrGen[2].push(arrGen[1].pop());
        console.log(arrGen.flat().join(' '));
        console.log(c.length == 2 && c.every(v => v == 1) ? 1 : 0);
    }
})();
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;
    }, {});
};


Many years ago Berland was a small country where only $$$n$$$ people lived. Each person had some savings: the $$$i$$$-th one had $$$a_i$$$ burles.The government considered a person as wealthy if he had at least $$$x$$$ burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that:   the government chooses some subset of people (maybe all of them);  the government takes all savings from the chosen people and redistributes the savings among the chosen people equally. For example, consider the savings as list $$$[5, 1, 2, 1]$$$: if the government chose the $$$1$$$-st and the $$$3$$$-rd persons then it, at first, will take all $$$5 + 2 = 7$$$ burles and after that will return $$$3.5$$$ burles to the chosen people. As a result, the savings will become $$$[3.5, 1, 3.5, 1]$$$.A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Next $$$2T$$$ lines contain the test cases — two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le x \le 10^9$$$) — the number of people and the minimum amount of money to be considered as wealthy. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial savings of each person. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per test case. For each test case print the maximum possible number of wealthy people after several (maybe zero) reforms.

NoteThe first test case is described in the statement.In the second test case, the government, for example, could carry out two reforms: $$$[\underline{11}, \underline{9}, 11, 9] \rightarrow [10, 10, \underline{11}, \underline{9}] \rightarrow [10, 10, 10, 10]$$$.In the third test case, the government couldn't make even one person wealthy.In the fourth test case, the government could choose all people to carry out a reform: $$$[\underline{9}, \underline{4}, \underline{9}] \rightarrow [7\frac{1}{3}, 7\frac{1}{3}, 7\frac{1}{3}]$$$.

'use strict';

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

const lines = [];
rl.on('line', line => {
  lines.push(line);
});

rl.on('close', main);

let rli = 0;
function readline() {
  return lines[rli++];
}

function main() {
  const times = parseInt(readline());
  for(let t = 0; t < times; ++t) {
    const rich = parseInt(readline().split(' ')[1]);
    const moneys = readline().split(' ').map(e => parseInt(e));
    moneys.sort((a,b) => b - a);
    let sum = 0;
    let result = 0;
    for(let i = 0; i < moneys.length; ++i) {
      if((sum + moneys[i])/(result + 1) >= rich) {
        sum = sum + moneys[i];
        result = result + 1;
      } else {
        break;
      }
    }
    write(`${result}\n`);
  }
}

// solved by: asmjaime

const readline = require('readline');

let input = [];

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

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

rl.on('close', () => {
	const test = parseInt(input[0]);
	for (let t=0; t < test; t++) {
		let inputNum = input[2*t+1].split(' ').map((a) => parseInt(a));
		let arr = input[2*t+2].split(' ').map((a) => parseInt(a));
		console.log(solution(inputNum, arr));
	}
});

function solution(nums, arr) {
	let n = nums[0];
	let bul = nums[1];
	arr = arr.sort((a, b) => a-b);
	let sum = 0;
	let count = 0;
	for (let j=n-1; j>=0; j--) {
		sum += arr[j];
		if (sum/(n-j) < bul) {
			break;
		}
		count += 1;
	}
	return count;
}

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

function solve(n, x, a) {
  a.sort((a, b) => b - a);
  let sum = 0;
  for(let i = 0; i < n; ++i) {
    sum += a[i];
    if (sum < x * (i + 1)) return i;
  }
  return n;
}

function main() {
  let currentLine = 0;
  const readLine = (_) => lines[currentLine++].split(' ').map((val) => parseInt(val));

  const test = readLine()[0];
  for (let t = 1; t <= test; ++t) {
    const [n, x] = readLine();
    const a = readLine();
    console.log(solve(n, x, a));
  }
}

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});
var lines=[],idx=0;
rl.on('line', line => {
    lines.push(line);
});
rl.on('close',main);
function read(){
    return lines[idx++];
}
function main(){
    var times=parseInt(read());
    while(times--){
        var tmp=read().split(' ');
        var size=parseInt(tmp[0]),mon=parseInt(tmp[1]);
        var arr=read().split(' ').map(s=>parseInt(s));
        arr.sort((a,b)=>{
            return b-a;
        });
        var avg=0,sum=0,num=0,ans=0;
        arr.forEach(idx=>{
            num++;
            if((sum+idx)/num>=mon){
                ans=num;
            }
            sum+=idx;
            avg=sum/num;
        });
        console.log(ans);
    }
}

t = +readline();
while (t-->0){
    ip = readline().split(' ').map(Number);
    n = ip[0];
    x = ip[1];
    poor = [];
    sum = 0;
    readline().split(' ').map(Number).forEach(a => {
        if (a >= x){
            sum += a;
        } else {
            poor.push(a);
        }
    });

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

    count = n - poor.length;
    for (i=0;i<poor.length;i++){
        if ((sum + poor[i])/(count+1) >= x){
            sum += poor[i];
            count++;
        } else {
            break;
        }
    }
    print(count);
}

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
//atcoderのサンプルは最後に改行入れること
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
    var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var n = one[0];
    var x = one[1];
    var sum = 0;
    var list = nextIntArray();
    list.sort(function(a,b){
    	return a - b;
    });
    for(var j = 0; j < n; j++){
      sum += list[j];
    }
    for(var j = 0; j < n; j++){
      if(sum / (n - j) >= x){
        output[i] = n - j;
        break;
      }
      sum -= list[j];
    }
    if(output[i] == null){
      output[i] = 0;
    }
  }
  myout(myconv(output,9));
}

var range = readline();

for(var i=0;i<range;i++) {
    var input = readline().split(" ").map(x=> parseInt(x));
    var saving = readline().split(" ").map(x => parseInt(x));

    saving.sort((a,b) => b - a);
    var minAverage = input[1];
    var sum = 0;
    var count = 0;

    for(var j=0;j<saving.length;j++) {
        sum = sum + saving[j];
        var avg = sum / (j+1);

        if(avg >= minAverage) {
            count++;
        } else {
            break;
        }
    }

    print(count);
}

t = +readline();
while (t-->0){
    ip = readline().split(' ').map(Number);
    n = ip[0];
    x = ip[1];
    poor = [];
    sum = 0;
    readline().split(' ').map(Number).forEach(a => {
        if (a >= x){
            sum += a;
        } else {
            poor.push(a);
        }
    })
    count = n - poor.length;
    for (i=0;i<poor.length;i++){
        if ((sum + poor[i])/(count+1) >= x){
            sum += poor[i];
            count++;
        } else {
            break;
        }
    }
    print(count);
}

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
//atcoderのサンプルは最後に改行入れること
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
    var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var n = one[0];
    var x = one[1];
    var sum = 0;
    var list = nextIntArray();
    list.sort(function(a,b){
    	return a - b;
    });
    for(var j = 0; j < n; j++){
      sum += list[j];
    }
    for(var j = 0; j < n; j++){
      if(sum / (n - j) >= x){
        output[i] = n - j;
        break;
      }
      sum -= list[i];
    }
    if(output[i] == null){
      output[i] = 0;
    }
  }
  myout(myconv(output,9));
}


Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $$$(0, 0)$$$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $$$OX$$$ or $$$OY$$$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.Alexey wants to make a polyline in such a way that its end is as far as possible from $$$(0, 0)$$$. Please help him to grow the tree this way.Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of sticks Alexey got as a present. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$) — the lengths of the sticks.

Print one integer — the square of the largest possible distance from $$$(0, 0)$$$ to the tree end.

NoteThe following pictures show optimal trees for example tests. The squared distance in the first example equals $$$5 \cdot 5 + 1 \cdot 1 = 26$$$, and in the second example $$$4 \cdot 4 + 2 \cdot 2 = 20$$$.

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 temp = d.split(' ').map(Number);
  const mid = BigInt(temp.length) / 2n;
  temp.sort((a, b) => a - b);

  const arr = temp.map(BigInt);

  const leftSum = arr.filter((x, idx) => idx < mid).reduce((a, x) => a + x, 0n);
  const rightSum = arr.filter((x, idx) => idx >= mid).reduce((a, x) => a + x, 0n);
  const ans = leftSum * leftSum + rightSum * rightSum;

  console.log(ans.toString());
  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 mid = Math.floor(arr.length / 2);
  arr.sort((a, b) => a - b);

  const leftSum = arr.filter((x, idx) => idx < mid).reduce((a, x) => a + x, 0);
  const rightSum = arr.filter((x, idx) => idx >= mid).reduce((a, x) => a + x, 0);
  const ans = leftSum * leftSum + rightSum * rightSum;

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


There are $$$n$$$ points on a plane. The $$$i$$$-th point has coordinates $$$(x_i, y_i)$$$. You have two horizontal platforms, both of length $$$k$$$. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same $$$y$$$-coordinate) and have integer borders. If the left border of the platform is $$$(x, y)$$$ then the right border is $$$(x + k, y)$$$ and all points between borders (including borders) belong to the platform.Note that platforms can share common points (overlap) and it is not necessary to place both platforms on the same $$$y$$$-coordinate.When you place both platforms on a plane, all points start falling down decreasing their $$$y$$$-coordinate. If a point collides with some platform at some moment, the point stops and is saved. Points which never collide with any platform are lost.Your task is to find the maximum number of points you can save if you place both platforms optimally.You have to answer $$$t$$$ independent test cases.For better understanding, please read the Note section below to see a picture for the first test case.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le 10^9$$$) — the number of points and the length of each platform, respectively. The second line of the test case contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$), where $$$x_i$$$ is $$$x$$$-coordinate of the $$$i$$$-th point. The third line of the input contains $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$), where $$$y_i$$$ is $$$y$$$-coordinate of the $$$i$$$-th point. All points are distinct (there is no pair $$$1 \le i < j \le n$$$ such that $$$x_i = x_j$$$ and $$$y_i = y_j$$$). It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: the maximum number of points you can save if you place both platforms optimally.

NoteThe picture corresponding to the first test case of the example:Blue dots represent the points, red segments represent the platforms. One of the possible ways is to place the first platform between points $$$(1, -1)$$$ and $$$(2, -1)$$$ and the second one between points $$$(4, 3)$$$ and $$$(5, 3)$$$. Vectors represent how the points will fall down. As you can see, the only point we can't save is the point $$$(3, 7)$$$ so it falls down infinitely and will be lost. It can be proven that we can't achieve better answer here. Also note that the point $$$(5, 3)$$$ doesn't fall at all because it is already on the platform.

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

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

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

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

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

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

(async () => {
  await inputPromise;
  let inp = input.split(/\D+/).map(v => +v); r = 0;
  let t = inp[r++];
  For(1, t, i => {
    let [n, k] = inp.slice(r, r = r + 2);
    let x = inp.slice(r, r = r + n).sort((a, b) => a - b);
    let y = inp.slice(r, r = r + n);
    var f = []
    var start = 0;
    For(0, n - 1, i => {
      while (x[i] - x[start] > k) start++;
      f[i] = i - start + 1;
    });
    var fm = Arr(0, n - 1, (i, p) => Math.max(p, f[i]));
    var f2 = Arr(0, n - 1, i => f[i] + (fm[i - f[i]] || 0));
    console.log(Math.max(...f2));
  })
})();

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

    E();
});

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 [a,b] = ti(readline().split(' '));

        if(a === b){
            console.log(0);
            continue;
        }

        let d = Math.abs(a-b);
        if(d <= 10){
            console.log(1);
            continue;
        }else{
            if(d % 10 !== 0)
                console.log(1 + Math.floor(d/10));
            else
                console.log(d / 10);
        }
    }
}

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

        if(a > b){
            let temp = a;
            a = b;
            b = temp;
            temp = x;
            x = y;
            y = temp;
        }

        if(b - y >= n){
            b -= n;
            console.log(a*b);
        }else{
            n -= (b-y);
            b = y;
            if(a-x >= n){
                a -= n;
            }else{
                a = x;
            }

            console.log(a*b);
        }
    }
}

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

        let min = 99999999999999;
        let res = null;
        for(let i = 1; i <= x; i++){
            for(let j = 0; j <= y-x; j++){
                let inclX = false;
                let inclY = false;
                let op = new Array(n);
                for(let k = 0; k < n; k++){
                    if(k === 0){
                        op[k] = i;
                    }else{
                        op[k] = op[k-1] + j;
                    }

                    if(op[k] === x)
                        inclX = true;

                    if(op[k] === y)
                        inclY = true;
                }

                if(inclX && inclY){
                    if(min > op[n-1]){
                        min = op[n-1];
                        res = op;
                    }
                }
            }
        }

        for(let num of res)
            console.log(num);
    }
}

function D(){
    let t = pi(readline());
    let getSum = (str) => {
        let sum = 0;
        for(let i = 0; i < str.length; i++){
            sum += pi(str[i]);
        }
        return sum;
    }

    while(t > 0){
        t--;

        let [n, s] = ti(readline().split(' '));
        let str = JSON.stringify(n);
        let sum = getSum(str);
        let count = 0;
        let p = 0;
        while(sum > s){
            let m = Math.pow(10, p+1);
            let num = pi(str.substring(str.length-1-p,str.length));
            count += (m-num);
            n += (m-num);
            let c = pi(str[str.length-1-p]);
            sum -= (c-1);
            p++;
            str = JSON.stringify(n);
        }

        console.log(count);
    }
}

function E(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,k] = ti(readline().split(' '));
        let x = ti(readline().split(' '));
        let y = readline();
        x.sort((a,b) => a-b);
        let left = new Array(n);
        let right = new Array(n);
        let p1 = 0;
        let p2 = 0;

        if(n === 1){
            console.log(1);
            continue;
        }

        for(let i = 0; i < x.length; i++){
            while(p1 <= i && x[i] - x[p1] > k){
                p1++;
            }

            while(p2 < n && x[p2] - x[i] <= k){
                p2++;
            }

            p2 -= 1;

            left[i] = i-p1+1;
            right[i] = x[p2] - x[i] > k ? p2-i : p2-i+1;
        }
        // console.log(left);
        // console.log(right);

        for(let i = 1; i < n; i++){
            left[i] = Math.max(left[i], left[i-1]);
        }

        for(let i = n-2; i >= 0; i--){
            right[i] = Math.max(right[i], right[i+1]);
        }

        let max = 0;

        for(let i = 0; i < n-1; i++)
            max = Math.max(max, left[i] + right[i+1]);

        console.log(max);
    }
}


You're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest.The forestThe Biridian Forest is a two-dimensional grid consisting of r rows and c columns. Each cell in Biridian Forest may contain a tree, or may be vacant. A vacant cell may be occupied by zero or more mikemon breeders (there may also be breeders other than you in the forest). Mikemon breeders (including you) cannot enter cells with trees. One of the cells is designated as the exit cell.The initial grid, including your initial position, the exit cell, and the initial positions of all other breeders, will be given to you. Here's an example of such grid (from the first example):  MovesBreeders (including you) may move in the forest. In a single move, breeders may perform one of the following actions:   Do nothing.  Move from the current cell to one of the four adjacent cells (two cells are adjacent if they share a side). Note that breeders cannot enter cells with trees.  If you are located on the exit cell, you may leave the forest. Only you can perform this move — all other mikemon breeders will never leave the forest by using this type of movement. After each time you make a single move, each of the other breeders simultaneously make a single move (the choice of which move to make may be different for each of the breeders).Mikemon battleIf you and t (t > 0) mikemon breeders are located on the same cell, exactly t mikemon battles will ensue that time (since you will be battling each of those t breeders once). After the battle, all of those t breeders will leave the forest to heal their respective mikemons.Note that the moment you leave the forest, no more mikemon battles can ensue, even if another mikemon breeder move to the exit cell immediately after that. Also note that a battle only happens between you and another breeders — there will be no battle between two other breeders (there may be multiple breeders coexisting in a single cell).Your goalYou would like to leave the forest. In order to do so, you have to make a sequence of moves, ending with a move of the final type. Before you make any move, however, you post this sequence on your personal virtual idol Blog. Then, you will follow this sequence of moves faithfully.Goal of other breedersBecause you post the sequence in your Blog, the other breeders will all know your exact sequence of moves even before you make your first move. All of them will move in such way that will guarantee a mikemon battle with you, if possible. The breeders that couldn't battle you will do nothing.Your taskPrint the minimum number of mikemon battles that you must participate in, assuming that you pick the sequence of moves that minimize this number. Note that you are not required to minimize the number of moves you make.

The first line consists of two integers: r and c (1 ≤ r, c ≤ 1000), denoting the number of rows and the number of columns in Biridian Forest. The next r rows will each depict a row of the map, where each character represents the content of a single cell:    'T': A cell occupied by a tree.  'S': An empty cell, and your starting position. There will be exactly one occurence of this in the map.  'E': An empty cell, and where the exit is located. There will be exactly one occurence of this in the map.  A digit (0-9): A cell represented by a digit X means that the cell is empty and is occupied by X breeders (in particular, if X is zero, it means that the cell is not occupied by any breeder).  It is guaranteed that it will be possible for you to go from your starting position to the exit cell through a sequence of moves.

A single line denoted the minimum possible number of mikemon battles that you have to participate in if you pick a strategy that minimize this number.

NoteThe following picture illustrates the first example. The blue line denotes a possible sequence of moves that you should post in your blog:  The three breeders on the left side of the map will be able to battle you — the lone breeder can simply stay in his place until you come while the other two breeders can move to where the lone breeder is and stay there until you come. The three breeders on the right does not have a way to battle you, so they will stay in their place.For the second example, you should post this sequence in your Blog:  Here's what happens. First, you move one cell to the right.  Then, the two breeders directly to the right of the exit will simultaneously move to the left. The other three breeder cannot battle you so they will do nothing.  You end up in the same cell with 2 breeders, so 2 mikemon battles are conducted. After those battles, all of your opponents leave the forest.  Finally, you make another move by leaving the forest.

function toInt(v){ return parseInt(v); }
function str(c, n){
	var ret = [];
	while(n--){
		ret.push(c);
	}
	return ret;
}
var _l = readline().split(' ');
var r = +_l[0] + 1;
var c = +_l[1] + 1;

var m = [];

m.push( str("T", c+1) );
for(var i=1; i<r; i++){
	m.push( ("T"+readline()+"T").split('') );
}
m.push( str("T", c+1) );
var start,end;
for(var i=1; i<r; i++){
	for(var j=1; j<c; j++){
		if(m[i][j]==='S'){
			start = [i,j];
			m[i][j] = '0';
		}else if(m[i][j]==='E'){
			end = [i,j];
			m[i][j] = '0';
		}
	}
}

var x = [1,-1,0,0];
var y = [0,0,1,-1];
var q = [end];
var i = 0;
var ret = 0;
while(i<q.length){
	var flg = false;
	for(var l=q.length; i<l; i++){
		var v = q[i];
		if( v[0]===start[0]&&v[1]===start[1]){
			flg = true;
		}else if(m[v[0]][v[1]]=='T'){
			continue;
		}else{
			ret += (parseInt( m[v[0]][v[1]] ));
		}

		m[v[0]][v[1]]='T';
		for(_i=0; _i<4; _i++){
			var xx = v[0] + x[_i];
			var yy = v[1] + y[_i];
			if(m[xx][yy]!=='T'){
				q.push([xx, yy]);
			}
		}
	}
	if(flg){
		break;
	}
}
print(ret);

function toInt(v){ return parseInt(v); }
function str(c, n){
	var ret = [];
	while(n--){
		ret.push(c);
	}
	return ret;
}
var _l = readline().split(' ');
var r = +_l[0] + 1;
var c = +_l[1] + 1;

var m = [];

m.push( str("T", c+1) );
for(var i=1; i<r; i++){
	m.push( ("T"+readline()+"T").split('') );
}
m.push( str("T", c+1) );
var start,end;
for(var i=1; i<r; i++){
	for(var j=1; j<c; j++){
		if(m[i][j]==='S'){
			start = [i,j];
			m[i][j] = '0';
		}else if(m[i][j]==='E'){
			end = [i,j];
			m[i][j] = '0';
		}
	}
}

var x = [1,-1,0,0];
var y = [0,0,1,-1];
var q = [end];
var i = 0;
var ret = 0;
while(i<q.length){
	var flg = false;
	for(var l=q.length; i<l; i++){
		var v = q[i];
		if( v[0]===start[0]&&v[1]===start[1]){
			flg = true;
		}else {
			ret += (parseInt( m[v[0]][v[1]] ));
		}

		m[v[0]][v[1]]='T';
		for(_i=0; _i<4; _i++){
			var xx = v[0] + x[_i];
			var yy = v[1] + y[_i];
			if(m[xx][yy]!=='T'){
				q.push([xx, yy]);
			}
		}
	}
	if(flg){
		break;
	}
}
print(ret);


Every December, VK traditionally holds an event for its employees named "Secret Santa". Here's how it happens.$$$n$$$ employees numbered from $$$1$$$ to $$$n$$$ take part in the event. Each employee $$$i$$$ is assigned a different employee $$$b_i$$$, to which employee $$$i$$$ has to make a new year gift. Each employee is assigned to exactly one other employee, and nobody is assigned to themselves (but two employees may be assigned to each other). Formally, all $$$b_i$$$ must be distinct integers between $$$1$$$ and $$$n$$$, and for any $$$i$$$, $$$b_i \ne i$$$ must hold.The assignment is usually generated randomly. This year, as an experiment, all event participants have been asked who they wish to make a gift to. Each employee $$$i$$$ has said that they wish to make a gift to employee $$$a_i$$$.Find a valid assignment $$$b$$$ that maximizes the number of fulfilled wishes of the employees.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. Each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of participants of the event. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$; $$$a_i \ne i$$$) — wishes of the employees in order from $$$1$$$ to $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print two lines. In the first line, print a single integer $$$k$$$ ($$$0 \le k \le n$$$) — the number of fulfilled wishes in your assignment. In the second line, print $$$n$$$ distinct integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$; $$$b_i \ne i$$$) — the numbers of employees assigned to employees $$$1, 2, \ldots, n$$$. $$$k$$$ must be equal to the number of values of $$$i$$$ such that $$$a_i = b_i$$$, and must be as large as possible. If there are multiple answers, print any.

NoteIn the first test case, two valid assignments exist: $$$[3, 1, 2]$$$ and $$$[2, 3, 1]$$$. The former assignment fulfills two wishes, while the latter assignment fulfills only one. Therefore, $$$k = 2$$$, and the only correct answer is $$$[3, 1, 2]$$$.

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 = rn();
		const a = rna();

		a.unshift(0);

		let ans = 0;
		const taken = Array(n+1);
		const asgnd = Array(n+1);
		for (let i = 1; i <= n; i++) {
			if (!taken[a[i]]) {
				asgnd[i] = a[i];
				taken[a[i]] = true;
				ans++;
			}
		}

		const avl = [];
		for (let i = 1; i <= n ; i++) {
			if (!taken[i]) {
				avl.push(i);
			}
		}

		for (let i = 1; i <= n; i++) {
			if (!asgnd[i]) {
				const x = avl.pop();
				if (i == x) {
					if (!avl.length) {
						let j = 1;
						while (a[j] != a[i] && j != i) {
							j++;
						}
						asgnd[j] = i;
						asgnd[i] = a[i];
					} else {
						asgnd[i] = avl.pop();
						avl.push(x);
					}
				} else {
					asgnd[i] = x;
				}
			}
		}

		console.log(ans);
		console.log(asgnd.slice(1).join(' '));
	}
}

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 = rn();
		const a = rna();

		a.unshift(0);

		let ans = 0;
		const taken = Array(n+1);
		const asgnd = Array(n+1);
		for (let i = 1; i <= n; i++) {
			if (!taken[a[i]]) {
				asgnd[i] = a[i];
				taken[a[i]] = true;
				ans++;
			}
		}

		const avl = [];
		for (let i = 1; i <= n ; i++)
			if (!taken[i]) avl.push(i);

		for (let i = 1, k = 0; i <= n; i++) {
			if (!asgnd[i]) {
				const x = avl.pop();
				if (i == x) {
					if (!avl.length) {
						let j = 1;
						while (a[j] != a[i] && j != i) j++;
						asgnd[j] = i;
						asgnd[i] = a[i];
					} else {
						asgnd[i] = avl.pop();
						avl.push(x);
					}
				} else {
					asgnd[i] = x;
				}
			}
		}

		console.log(ans);
		console.log(asgnd.slice(1).join(' '));
	}
}

'use strict';

function solve(n, a) {
  a = a.map(num => num - 1);
  let res = [],
      set = new Set([...new Array(n).keys()]);
  const g = Array.from({
    length: n
  }, () => []);
  for (let [i, j] of a.entries()) {
    if (set.has(j)) {
      res[i] = j;
      set.delete(j);
    }
    g[j].push(i);
  }
  const nums = [...set];
  for (let i = 0; i < n; i++) {
    if (res[i] === undefined) {
      const num = nums.pop();
      if (num === i) {
        for (let j of g[a[i]]) {
          if (j !== i) {
            res[i] = a[i];
            res[j] = num;
            break;
          }
        }
      } else {
        res[i] = num;
      }
    }
  }
  let len = 0;
  for (let i = 0; i < n; i++) {
    if (res[i] === a[i]) len++;
  }
  return `${len}\n${res.map(num => num + 1).join(' ')}`;
}

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

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

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 = rn();
		const a = rna();

		a.unshift(0);

		let ans = 0;
		const taken = Array(n+1);
		const asgnd = Array(n+1);
		for (let i = 1; i <= n; i++) {
			if (!taken[a[i]]) {
				asgnd[i] = a[i];
				taken[a[i]] = true;
				ans++;
			}
		}

		const avl = Array(n+1);
		for (let i = 1; i <= n ; i++) {
			if (!taken[i]) {
				avl.push(i);
			}
		}

		for (let i = 1; i <= n; i++) {
			if (!asgnd[i]) {
				const x = avl.pop();
				if (i == x) {
					if (!avl.length) {
						let j = 1;
						while (a[j] != a[i] && j != i) {
							j++;
						}
						asgnd[j] = i;
						asgnd[i] = a[i];
					} else {
						asgnd[i] = avl.pop();
						avl.push(x);
					}
				} else {
					asgnd[i] = x;
				}
			}
		}

		console.log(ans);
		console.log(asgnd.slice(1).join(' '));
	}
}

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 = rn();
		const a = rna();

		a.unshift(0);

		let ans = 0;
		const taken = Array(n+1);
		const asgnd = Array(n+1);
		for (let i = 1; i <= n; i++) {
			if (!taken[a[i]]) {
				asgnd[i] = a[i];
				taken[a[i]] = true;
				ans++;
			}
		}

		const avl = [];
		for (let i = 1; i <= n ; i++)
			if (!taken[i]) avl.push(i);

		for (let i = 1, k = 0; i <= n; i++) {
			if (!asgnd[i]) {
				const x = avl.pop();
				if (i == x) {
					//if (!avl.length) {
						//let j = 1;
						//while (a[j] != a[i] && j != i) j++;
						//asgnd[j] = i;
						//asgnd[i] = a[i];
					//} else {
						asgnd[i] = avl.pop();
						avl.push(x);
					//}
				} else {
					asgnd[i] = x;
				}
			}
		}

		console.log(ans);
		console.log(asgnd.slice(1).join(' '));
	}
}

'use strict';

function solve(n, a) {
  let res = [],
      set = new Set(Array.from({
    length: n
  }, (_, i) => i + 1));
  for (let [i, num] of a.entries()) {
    if (set.has(num)) {
      res[i] = num;
      set.delete(num);
    }
  }
  let len = n - set.size;
  const nums = [...set];
  for (let i = 0; i < n; i++) {
    if (res[i] === undefined) {
      res[i] = nums.pop();
    }
  }
  return `${len}\n${res.join(' ')}`;
}

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

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


A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least i is found so that namei does not yet exist in the database.

The first line contains number n (1 ≤ n ≤ 105). The following n lines contain the requests to the system. Each request is a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters.

Print n lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken.

var a = parseInt( readline() );

var map = {};

while(a--){

	var name = readline();
	if( map.hasOwnProperty(name) ){
		map[name]++;
		print(name + map[name]);
	}else{
		print('OK');
		map[name] = 0;
	}
}

var n = +readline();
var obj = {};

for(i = 0; i < n; i++){
	input = readline();
	if(input in obj){
		obj[input]++;
		print(input + obj[input]);
	}
	else{
		obj[input] = 0;
		print("OK");
	}
}

var n = parseInt(readline());
var m = {};
for (var i = 0; i < n; i++) {
    var a = readline();
    if (!!m[a]) {
        var b = a + m[a];
        write(b+'\n');
        m[a] = m[a] + 1;
        m[b] = 1;

    } else {
        m[a] = 1;
        write('OK'+'\n');
    }
}

function registrationSystem (userName){
	if (!mySet.hasOwnProperty(userName)){
		mySet[userName] = 0;
		print('OK');
	}
	else{
		mySet[userName] += 1;
		var newUser = userName + mySet[userName].toString();
		mySet[newUser] = 0;
		print(newUser)
	}
}
var mySet = {};
var queries = parseInt(readline());
for (var i = 0; i < queries; i ++){
	registrationSystem(readline());
}

;(function () {

	var n = +readline();
	var base = {};

	while (n--) {
		var name = readline();
		if (base.hasOwnProperty(name)) {
			base[name]++;
			print(name + base[name]);
		} else {
			base[name] = 0;
			print('OK');
		}
	}

}).call(this);

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var queryNum = integers[0];

	var names = {};

	for (var i = 0; i < queryNum; i += 1) {
		var query = trim(readline());
		if (names[query] == undefined) {
			print("OK");
			names[query] = 1;
		}
		else {
			print(query+names[query]);
			names[query] += 1;
		}
	}
}

main();

readline = readline || ''
write = write || ''
print = print || ''

readline()

var ns = {}
var ln
while (ln = readline()) ns[ln] ? print(ln + ns[ln]++) : (print('OK'), ns[ln] = 1)

'use strict'

var names = {};
for (var i = parseInt(readline()); i; i--) {
    let name = readline();
    if (names[name]) { write(`${name}${names[name]++}\n`); }
    else { write('OK\n'); names[name] = 1; }
}

'use strict'

const names = {};
for (let i = parseInt(readline()); i; i--) {
    const name = readline();
    if (names[name]) { write(`${name}${names[name]++}\n`); }
    else { write('OK\n'); names[name] = 1; }
}

readline(); x = {};
while(i = readline()) x[i] ? print(i + x[i]++) : (print('OK'), x[i] = 1);

var n = +readline();
var names = {};
for (var i = 0; i < n; i++) {
    var name = readline();
    if (names[name]) { print(`${name}${names[name]}`); names[name] += 1; }
    else { print('OK'); names[name] = 1; }
}

var n = +readline();
var obj = {}, str;

for(var i = 0; i < n; i++) {
    str = readline();
    if (!obj[str]) {
        print('OK');
        obj[str] = 1;
    } else {
        var str2 = str + obj[str];
        obj[str]++;
        print(str2);
        obj[str2] = 1;
    }
}

//print(res);

n = Number(readline());
var names = {};
while (n--) {
    str = readline();
    if (names[str] === undefined) { print('OK'); names[str] = 1; }
    else {print(str + names[str]); names[str]++ }
}

n=Number(readline())
r={}
while (n) {
	w=readline()
	if (w in r) {
		r[w]++;
		print(w+r[w]);
	}
	else {
		r[w]=0;
		print("OK");
	}
	n--;
}

'use strict'

String.prototype.getNumber = function() {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  })[0];
}

let n = readline().getNumber(),
    dict = {};

for (let i = 0; i < n; i++) {
  let name = readline();
  if (dict[name]) {
    write(name+(dict[name]++)+'\n');
  } else {
    dict[name] = 1;
    write('OK\n');
  }
}

var o = {
};
var n = readline();
	for (var i=0; i<n; i++){
	    var s = readline();

		if(s in o){
			o[s]++;
			print(s+o[s]);
		}
		else {
		print("OK");
		o[s]=0;
		}
	};

var n = +readline();

var cache = {};
for (var i = 0; i < n; i++) {
    var s = readline();
    if(cache[s]) {
        print(s + cache[s]++)
    }else {
        print('OK');
        cache[s] = 1;
    }
}

n=+readline()
dup={};
while(n--) {
    s=readline();
    if (!dup[s]) {
        print('OK');
        dup[s]=1;
    } else {
        print(s+dup[s]);
        dup[s]=dup[s]+1;
    }
}

var n = parseInt(readline());
var i, j=0, user, userList = {};

for (i=0; i<n; i++){
    user = readline();
    if (user in userList){
        userList[user]++;
        print(user + userList[user]);
    } else {
        userList[user] = 0;
        print('OK');
    }
}

var n = parseInt(readline());
var o = {}; var ii = 0;
for (var i = 0; i < n; i++) {
	var s = readline();
  	if (o[s]) {
      print (s + o[s]);
      o[s] += 1;
    } else {
      o[s] = 1;
      print ('OK');
    }
}

function find(array, name)
{
	if (array[name] !== undefined)
	    {
	    	    return true;
	    }
	  return false;
}

var namesArray = [];
var currentName = null;
for (var counter = +readline(); counter; counter--)
    {
    	    if(!find(namesArray,currentName = readline()))
           {
                namesArray[currentName] = 0;
                print("OK");
                continue;
           }
         print(currentName + ++namesArray[currentName]);
    }

n=Number(readline())
X={}
for (i=0; i<n; ++i) {
    x=readline()
    if (x in X) {
        ++X[x]
        print(`${x}${X[x]}`)
    } else {
        X[x]=0
        print('OK')
    }
}

var n = readline(), str = new Map();
for(var i = 0; i < n; i++) {
    var ss = readline();
    if(str.has(ss)) {
        str.set(ss,str.get(ss) + 1);
        print(ss + str.get(ss));
    }
    else {
        str.set(ss, 0);
        print('OK');
    }
}

var n = parseInt(readline());
var nextInput;
var count = {};

for(var i = 0; i < n ; i++){
    nextInput = readline();
    count[nextInput] ? print(nextInput + count[nextInput]++) : (print("OK"), count[nextInput] = 1);
}

"use strict";

var n = parseInt(readline());
var map = Object.create(null);
for (var i = 0; i < n; i++) {
  var str = readline();
  var prevCount = map[str];
  map[str] = prevCount ? prevCount + 1 : 1;
  if (prevCount) {
    print(str + prevCount);
  } else {
    print("OK");
  }
}

'use strict';
const rl = require('readline')
  .createInterface({ input: process.stdin, output: process.stdout });
const write = (...args) => {
  process.stdout.write(args.join(' '));
};

const lines = [];
rl.on('line', line => {
  lines.push(line);
});

rl.on('close', main);
let rli = 0;

function readline() {
  return lines[rli++];
};

function main() {
  const size = parseInt(readline());
  const registredMap = {};
  for(let i = 0; i < size; ++i){
    const user = readline();
    if(registredMap[user] === undefined) {
      registredMap[user] = 0;
      write("OK\n");
    } else {
      registredMap[user]++;
      write(`${user}${registredMap[user]}\n`);
    }
  }
}

//solved by: asmjaime

'use strict';

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

let input = '';
let currentLine = 0;

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

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

  main();
});

function main() {
  const map = {};

  input.forEach((item, index) => {
    if (index !== 0) {
      if(map[item] !== undefined){
        console.log(`${item}${map[item]}`);
        map[item] += 1;
      } else {
        map[item] = 1;
        console.log('OK');
      }
    }
  });
}

const readline = require('readline')

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

let counts = 0
let inputs = []
let register = {}

RL.on('line', line => {
  const len = inputs.length
  if (!counts) {
    counts = line
  } else if (len < counts) {
    inputs.push(line)
    if (len === counts - 1) {
      solution()
    }
  }
})

function solution() {
  inputs.map(input => {
    if (register[input]) {
      console.log(`${input}${register[input]}`)
      register[input] += 1
    } else {
      console.log('OK')
      register[input] = 1
    }
  })
}

const mainFunction = (lines) => {
    let n = +lines[0],
        map = new Map()
    for (let i = 1; i <= n; i++) {
        let string = lines[i]
        if (map.has(string)) {
            let key = +map.get(string)
            map.delete(string)
            map.set(string, ++key)
            console.log(string + map.get(string))
        } else {
            map.set(string, 0)
            console.log("OK")
        }
    }
}

const { EOL } = require('os')
if (__filename.substr(9, 4) != "azer") {
    let yourInputData = ''
    process.stdin.on('data', i => yourInputData += i)
    process.stdin.on('end', () => mainFunction(yourInputData.split(EOL)))
} else {
    const fileSystem = require("fs");
    mainFunction(fileSystem.readFileSync('input.txt', 'utf8').split(EOL))
}

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

const input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  const map = {};
  input.forEach((x, i) => {
    if (i === 0) return;

    if (map[x] !== undefined) {
      console.log(`${x}${map[x]}`);
      map[x] += 1;
    } else {
      map[x] = 1;
      console.log('OK');
    }
  });
});

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

const input = [];

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

readLine.on("line", (line) => input.push(line));
readLine.on("close", () => {
  let n = parseInt(input[0]);
  const map = {};

  for (let i = 1; i <= n; i += 1) {
    const name = input[i];

    if (map[name] === undefined) {
      console.log(`OK`);
      map[name] = 0;
    } else {
      map[name]++;
      console.log(`${name}${map[name]}`);
    }
  }
});

"use strict";
// registration system
// https://codeforces.com/contest/4/problem/C

const readline = require('readline');
let rl = readline.createInterface(process.stdin, process.stdout);

const registered = new Map();
let count=0;
let lines;

rl.on('line', input => {
    if (lines) {
        if (registered.has(input)) {
            registered.set(input, registered.get(input)+1);
            console.log(`${input}${registered.get(input)}`);
        }
        else {
            registered.set(input, 0);
            console.log('OK');
        }
        count++;
        if (count>=lines) process.exit(0);
    }
    else {
        lines = parseInt(input);
    }
    // console.log(input);
});

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

let inputString = "";
let currentLine = 0;

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

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

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

  main();
});
// main();

////////////////////////////////////////////////////////////////////////

function main() {
  let inputNum = parseInt(readline());
  let database = {};
  for (let i = 0; i < inputNum; i++) {
    let inputString = readline();
    if (database[inputString] === undefined) {
      database[inputString] = 0;
      console.log("OK");
    } else {
      database[inputString]++;
      console.log(inputString + database[inputString]);
    }
  }
}

let fs = require("fs");

let txt = fs.readFileSync(0, "utf-8").split(/[\r\n]/).filter(data => data.length > 0);
for (let i = 0; i < txt.length; i ++) {
    if(!isNaN(txt[i]*1)){
        let tab=[];
        for (let i1 = i+1; i1 < i+1+txt[i]*1; i1++) {
            tab.push(txt[i1]);
        }
        doit(tab);
    }
}

function doit(tab) {
    let register=[];
    let enter=[];
    tab.forEach(data => {
        let r=register.indexOf(data);
        if(r!=-1){
            console.log(data+enter[r]);
            ++enter[r];
        }else{
            console.log("OK");
            register.push(data);
            enter.push(1);
        }
    });

}

;(function () {

	var n = +readline();
	var b = [];

	for (var i = 0; i < n; i++) {
		var s = readline();
		var k = b.indexOf(s);

		if (k === -1) {
			b.push(s);
			print('OK');
		} else {
			k = b.filter(function (e) { return e == s; }).length;
			b.push(s + k);
			print(b.slice(-1));
		}
	}

}).call(this);

var names = {};
for (var i = parseInt(readline()); i; i--) {
    var name = readline();
    if (names[name]) { write(`${name}${names[name]++}`); }
    else { write('OK'); names[name] = 1; }
}

'use strict'

String.prototype.getNumber = function() {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  })[0];
}

let n = readline().getNumber(),
    dict = {};

for (let i = 0; i < n; i++) {
  let name = readline();
  if (dict[name]) {
    write(name+(dict[name]++));
  } else {
    dict[name] = 1;
    write('OK');
  }
}

var n = readline();
var str = "";

	for (var i=0; i<n; i++){
	    var s = readline();
		var reg = new RegExp("\b"+s+"\b", "g");
		if(reg.test(str))
		{
			s=s+"1"
			print(s);
			str+=s+ " ";
		}
		else {print("OK")
			str+=s+" ";}
	}

var n = readline();
var str = "";

	for (var i=0; i<n; i++){
	    var s = readline();
		var reg = new RegExp(s, "g");
		if(reg.test(str))
		{
			s=s+"1"
			print(s);
			str+=" "+s;
		}
		else {print("OK");
			str+=" "+s;}
	}

var n = readline();
var str = "";

	for (var i=0; i<n; i++){
	    var s = readline();
		var reg = new RegExp(s, "g");
		if(reg.test(str))
		{
			s=s+"1"
			print(s);
			str+=" "+s;
		}
		else {print("OK")
			str+=" "+s;}
	}

var n = readline();
var str = "";
var x = 1;
	for (var i=0; i<n; i++){
	    var s = readline();
		var reg = new RegExp("\\b"+s+"\\b", "g");
		if(reg.test(str))
		{
			s=s+x
			print(s);
			str+=" "+s;
			x++;
		}
		else {print("OK");
			str+=" "+s; x=0;}
	}

var n = readline();
var str = "";

	for (var i=0; i<n; i++){
	    var s = readline();
		var reg = new RegExp("^"+s+"$", "g");
		if(reg.test(str))
		{
			s=s+"1"
			print(s);
			str+=s+ " ";
		}
		else {print("OK")
			str+=s+" ";}
	}

var n = readline();
var str = "";

	for (var i=0; i<n; i++){
	    var s = readline();
		var reg = new RegExp("^"+s+"$", "g");
		if(reg.test(str))
		{
			s=s+"1"
			print(s);
			str+=s;
		}
		else {print("OK")
			str+=s;}
	}

var n = readline();
var str = "";

	for (var i=0; i<n; i++){
	    var s = readline();
		var reg = new RegExp((s));
		if(reg.test(str))
		{
			s=s+"1"
			print(s);
			str+=s;
		}
		else {print("OK")
			str+=s;}
	}

var n = readline();
var str = "";

	for (var i=0; i<n; i++){
	    var s = readline();
		var reg = new RegExp("\b"+s+"\b", "g");
		if(reg.test(str))
		{
			s=s+"1"
			print(s);
			str+=s;
		}
		else {print("OK")
			str+=s;}
	}

var n = readline();
var str = "";

	for (var i=0; i<n; i++){
	    var s = readline();
		var reg = new RegExp(s);
		if(reg.test(str))
		{
			s=s+"1"
			print(s);
			str+=s;
		}
		else {print("OK")
			str+=s;}
	}

var n = readline();
var str = "";

	for (var i=0; i<n; i++){
	    var s = readline();
		var reg = new RegExp("\\b"+s+"\\b", "g");
		if(reg.test(str))
		{
			s=s+"1"
			print(s);
			str+=" "+s;
		}
		else {print("OK");
			str+=" "+s;}
	}

var inputs = parseInt(readline());
var arr = [];
var nextInput;

for(var i = 0; i < inputs; i++){
    nextInput = readline();
    if(arr.includes(nextInput)){
        var num = 1;
        while(arr.includes(nextInput)){
         nextInput =  nextInput+num;
         num++;
        }
        print(nextInput);
    }else{
        print("OK")
    }
    arr.push(nextInput);
}

'use strict';

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

let input = '';
let currentLine = 0;

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

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

  main();
});

function main() {
  const map = {};

  input.forEach((item, index) => {
    if (index !== 0) {
      if(map[item] !== undefined){
        console.log(`${item}${map[item]}`);
        map[item] += 1;
      } else {
        map[item] = 1;
        console.log('ОК');
      }
    }
  });
}

'use strict';

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

let input = '';
let currentLine = 0;

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

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

  main();
});

function main() {
  const map = {};

  input.forEach((item, index) => {
    if (index !== 0) {
      for (let i = ''; true; i += 1) {
        if (map[item + i] === undefined) {
          map[item + i] = 1;
          if (i === '') {
            console.log('OK');
          } else {
            console.log(item + i);
          }
          break;
        }
      }
    }
  });
}

const mainFunction = (lines) => {
    let n = +lines[0],
        map = new Map()
    for (let i = 1; i <= n; i++) {
        let string = lines[i]
        if (map.has(string)) {
            let key = +map.get(string)
            map.clear(string)
            map.set(string, ++key)
            console.log(string + map.get(string))
        } else {
            map.set(string, 0)
            console.log("OK")
        }
    }
}

const { EOL } = require('os')
if (__filename.substr(9, 4) != "azer") {
    let yourInputData = ''
    process.stdin.on('data', i => yourInputData += i)
    process.stdin.on('end', () => mainFunction(yourInputData.split(EOL)))
} else {
    const fileSystem = require("fs");
    mainFunction(fileSystem.readFileSync('input.txt', 'utf8').split(EOL))
}

"use strict";
// registration system
// https://codeforces.com/contest/4/problem/C

const readline = require('readline');
let rl = readline.createInterface(process.stdin, process.stdout);

const registered = new Map();
let count=0;
let lines;

rl.on('line', input => {
    if (lines) {
        if (registered.has(input)) {
            console.log(`${input}1`);
        }
        else {
            registered.set(input, 1);
            console.log('OK');
        }
        count++;
        if (count>=lines) process.exit(0);
    }
    else {
        lines = parseInt(input);
    }
    // console.log(input);
});


Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle.Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.

The first line contains integer n (1 ≤ n ≤ 100) — the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≤ ai, bi ≤ 1000) — the description of the i-th bottle.

In a single line print a single integer — the answer to the problem.

var tokenizer;
var index = 0;

function next(){
    while(tokenizer == null || index == tokenizer.length){
        tokenizer = readline().split(" ");
        index = 0;
    }
    var res = tokenizer[index++];
    return res;
}

function nextInt(){
    return parseInt(next());
}

function nextFloat(){
    return parseFloat(next());
}

function solve(){
    var n = nextInt();
    var a = [];
    var b = [];
    for(var i = 0; i < n; ++i){
        a[i] = nextInt();
        b[i] = nextInt();
    }
    var res = 0;
    for(var i = 0; i < n; ++i){
        var found = false;
        for(var j = 0; j < n; ++j){
            if(b[j] == a[i] && j != i) found = true;
        }
        if(!found) ++res;
    }
    print(res);
}
solve();