This is a hard version of the problem. The only difference between an easy and a hard version is in the number of queries.Polycarp grew a tree from $$$n$$$ vertices. We remind you that a tree of $$$n$$$ vertices is an undirected connected graph of $$$n$$$ vertices and $$$n-1$$$ edges that does not contain cycles.He calls a set of vertices passable if there is such a path in the tree that passes through each vertex of this set without passing through any edge twice. The path can visit other vertices (not from this set).In other words, a set of vertices is called passable if there is a simple path that passes through all the vertices of this set (and possibly some other).For example, for a tree below sets $$$\{3, 2, 5\}$$$, $$$\{1, 5, 4\}$$$, $$$\{1, 4\}$$$ are passable, and $$$\{1, 3, 5\}$$$, $$$\{1, 2, 3, 4, 5\}$$$ are not.  Polycarp asks you to answer $$$q$$$ queries. Each query is a set of vertices. For each query, you need to determine whether the corresponding set of vertices is passable.

The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of vertices. Following $$$n - 1$$$ lines a description of the tree.. Each line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — indices of vertices connected by an edge. Following line contains single integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — number of queries. The following $$$2 \cdot q$$$ lines contain descriptions of sets. The first line of the description contains an integer $$$k$$$ ($$$1 \le k \le n$$$) — the size of the set. The second line of the description contains $$$k$$$ of distinct integers $$$p_1, p_2, \dots, p_k$$$ ($$$1 \le p_i \le n$$$) — indices of the vertices of the set. It is guaranteed that the sum of $$$k$$$ values for all queries does not exceed $$$2 \cdot 10^5$$$.

Output $$$q$$$ lines, each of which contains the answer to the corresponding query. As an answer, output "YES" if the set is passable, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

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 = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))
        l += n - 1
        const q = +lines[l++]
        const qs = []
        for (let j = 0; j < q; j++) {
            l++
            qs[j] = lines[l++].trim().split(' ').map(Number)
        }
        output[i] = solve(n, edges, qs)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, edges, qs) {
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
    buildLCA(n, adj)
    //
    return qs.map(arr => {
        arr.sort((a, b) => TIN[a] - TIN[b])
        //
        const vs = {}
        vs[arr[0]] = 1
        for (let i = 1; i < arr.length; i++) {
            vs[arr[i]] = 1
            const ca = lca(arr[i - 1], arr[i])
            vs[ca] = 1
        }
        const ts = []
        for (let u in vs) {
            // u = +u
            ts.push([TIN[u], 1], [TOUT[u], -1])
        }
        ts.sort((a, b) => a[0] - b[0])
        // console.log(ts)
        //
        let c = 0
        let prev = 1 // prev d
        let happen = 0 // - => +
        for (let i = 0; i < ts.length; i++) {
            const [t, d] = ts[i]
            if (d !== prev) {
                if (d > 0) {
                    if (happen || c > 1) return 'NO'
                    happen = 1
                }
            }
            //
            c += d
            prev = d
        }
        return 'YES'
    }).join('\n')
}

const LOG = 19 // 2^19 > 3e5
let TIMER, TIN, TOUT, TMAP
let UP
function buildLCA(n, adj) {
    TIMER = 0
    TIN = []
    TOUT = []
    UP = []
    TMAP = []

    for (let i = 1; i <= n; i++) {
        if (i in TIN) continue

        dfs(adj, i)
    }
}
function lca(u, v) {
    if (isP(u, v)) return u
    if (isP(v, u)) return v

    for (let i = LOG - 1; i >= 0; i--) {
        if (!isP(UP[v][i], u)) v = UP[v][i]
    }
    return UP[v][0]
}
function isP(u, v) { // u is the parent of v
    return TIN[u] <= TIN[v] && TOUT[u] >= TOUT[v]
}
function dfs(adj, r) {
    const stack = [[r, r, 0]]
    while (stack.length) {
        const [u, p, i] = stack[stack.length - 1]

        const nb = adj[u] || []
        if (i < nb.length) {
            if (!i) {
                // TMAP[TIMER] = 1
                TIN[u] = TIMER++
                UP[u] = [p]
                for (let j = 1; j < LOG; j++) {
                    UP[u][j] = UP[UP[u][j - 1]]
                        ? UP[UP[u][j - 1]][j - 1]
                        : 0
                }
            }
            stack[stack.length - 1][2]++ // don't change the index
            const v = nb[i]
            if (!(v in TIN)) {
                stack.push([v, u, 0])
            }
        } else {
            // TMAP[TIMER] = -1
            TOUT[u] = TIMER++
            stack.pop()
        }
    }
}

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 = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const edges = lines.slice(l, l + n - 1).map(str => str.trim().split(' ').map(Number))
        l += n - 1
        const q = +lines[l++]
        const qs = []
        for (let j = 0; j < q; j++) {
            l++
            qs[j] = lines[l++].trim().split(' ').map(Number)
        }
        output[i] = solve(n, edges, qs)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, edges, qs) {
    const adj = {}
    edges.forEach(([a, b]) => {
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })
    dfs(adj, 1)
    //
    return qs.map(arr => {
        const ts = []
        // let mint = TIMER + 5
        // let maxt = -1
        for (let u of arr) {
            // ts.push([TIN[u], 1, u], [TOUT[u], -1, u])
            ts.push([TIN[u], 1], [TOUT[u], -1])
            // mint = Math.min(mint, TIN[u], TOUT[u])
            // maxt = Math.max(maxt, TIN[u], TOUT[u])
        }
        let c = 0
        let prev = 1 // prev d
        let happen = 0 // - => +
        ts.sort((a, b) => a[0] - b[0])
    // console.log(ts)
        let now = ts[0][0] // first time
        for (let i = 0; i < ts.length; i++) {
            const t = ts[i][0]
            while (now <= t) {
                now++
                const d = TMAP[t]
            // console.log(c, t, d)
                if (d !== prev) {
                    if (d > 0) {
                        if (happen || c > 1) return 'NO'
                        happen = 1
                    }
                }
                //
                c += d
                prev = d
            }
        // for (let t = mint; t <= maxt; t++) {
            // const d = TMAP[t]
        }
        return 'YES'
    }).join('\n')
}

let TIMER, TIN, TOUT, TMAP
function isP(u, v) { // u is the parent of v
    return TIN[u] <= TIN[v] && TOUT[u] >= TOUT[v]
}
function dfs(adj, r) {
    TIMER = 0
    TIN = []
    TOUT = []
    TMAP = []
    const stack = [[r, r, 0]]
    while (stack.length) {
        const [u, p, i] = stack[stack.length - 1]

        const nb = adj[u] || []
        if (i < nb.length) {
            if (!i) {
                TMAP[TIMER] = 1
                TIN[u] = TIMER++
            }
            stack[stack.length - 1][2]++ // don't change the index
            const v = nb[i]
            if (!(v in TIN)) {
                stack.push([v, u, 0])
            }
        } else {
            TMAP[TIMER] = -1
            TOUT[u] = TIMER++
            stack.pop()
        }
    }
}


During the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables.Now she has a table filled with integers. The table consists of n rows and m columns. By ai, j we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in non-decreasing order in the column j if ai, j ≤ ai + 1, j for all i from 1 to n - 1.Teacher gave Alyona k tasks. For each of the tasks two integers l and r are given and Alyona has to answer the following question: if one keeps the rows from l to r inclusive and deletes all others, will the table be sorted in non-decreasing order in at least one column? Formally, does there exist such j that ai, j ≤ ai + 1, j for all i from l to r - 1 inclusive.Alyona is too small to deal with this task and asks you to help!

The first line of the input contains two positive integers n and m (1 ≤ n·m ≤ 100 000) — the number of rows and the number of columns in the table respectively. Note that your are given a constraint that bound the product of these two integers, i.e. the number of elements in the table. Each of the following n lines contains m integers. The j-th integers in the i of these lines stands for ai, j (1 ≤ ai, j ≤ 109). The next line of the input contains an integer k (1 ≤ k ≤ 100 000) — the number of task that teacher gave to Alyona. The i-th of the next k lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n).

Print "Yes" to the i-th line of the output if the table consisting of rows from li to ri inclusive is sorted in non-decreasing order in at least one column. Otherwise, print "No".

NoteIn the sample, the whole table is not sorted in any column. However, rows 1–3 are sorted in column 1, while rows 4–5 are sorted in column 3.

function getLine(){
    return readline().split(' ').map(function(x){
       return parseInt(x);
    });
}

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

var L = getLine();
var n = L[0];
var m = L[1];
var P = [];

for(var i = 0; i < n; i++){
    P[i] = getLine();
}
var T = [];
var G = [];
for(var i = 0; i < m; i++){
    T[i] = 0;
}
G[0] = 0;
for(var i = 1; i < n; i++){
    var min = n;
    for(var j = 0; j < m; j++){
        if(P[i - 1][j] > P[i][j]){
            T[j] = i;
        }
        min = Math.min(min, T[j]);
    }
    G[i] = min;
}
var k = getInt();
for(var i = 0; i < k; i++){
    var L = getLine();
    var l = L[0] - 1;
    var r = L[1] - 1;
    print(G[r] <= l ? "Yes" : "No");
}

var s = readline().split(" ");
var n = Number(s[0]);
var m = Number(s[1]);

var a = new Array(n);
for (var i = 0; i < n; ++i) {
    a[i] = readline().split(" ").map(function(each) {return Number(each)});
}

var track = new Array(n);
for (i = 0; i < n; ++i) {
    track[i] = new Array(m);
}

var track1 = new Array(n);
track1[0] = 1;

for (j = 0; j < m; ++j) {
    track[0][j] = 1;
}

for (i = 1; i < n; ++i) {
    var max = 0
    for (j = 0; j < m; ++j) {
        if (a[i][j] >= a[i - 1][j]) {
            track[i][j] = track[i - 1][j] + 1;
        } else {
            track[i][j] = 1;
        }

        if (track[i][j] > max)
            max = track[i][j];
    }

    track1[i] = max;
}

//for (i = 0; i < n; ++i) {
//    for (j = 0; j < m; ++j) {
//        write(track[i][j]);
//    }
//    print();
//}

function nonDesc(l, r) {
    if (track1[r - 1] >= r - l + 1) {
        return "Yes";
    }

    return "No";
}

var k = Number(readline());

for (i = 0; i < k; ++i) {
    var s = readline().split(" ");
    var l = Number(s[0]);
    var r = Number(s[1]);
    print(nonDesc(l, r));
}

function getLine(){
    return readline().split(' ').map(function(x){
       return parseInt(x);
    });
}

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

var L = getLine();
var n = L[0];
var m = L[1];
var P = [];

for(var i = 0; i < n; i++){
    P[i] = getLine();
}
var T = [];
var G = [];
for(var i = 0; i < m; i++){
    T[i] = 0;
}
G[0] = 0;
for(var i = 1; i < n; i++){
    var min = n;
    for(var j = 0; j < m; j++){
        if(P[i - 1][j] > P[i][j]){
            T[j] = i;
        }
        min = Math.min(min, T[j]);
    }
    G[i] = min;
}
var k = getInt();
for(var i = 0; i < k; i++){
    var L = getLine();
    var l = L[0] - 1;
    var r = L[1] - 1;
    print(G[r] <= l ? "YES" : "NO");
}

var s = readline().split(" ");
var n = Number(s[0]);
var m = Number(s[1]);

var a = new Array(n);
for (var i = 0; i < n; ++i) {
    a[i] = readline().split(" ").map(function(each) {return Number(each)});
}

var track = new Array(n);
for (i = 0; i < n; ++i) {
    track[i] = new Array(m);
}

for (j = 0; j < m; ++j) {
    track[0][j] = 1;
}

for (i = 1; i < n; ++i) {
    for (j = 0; j < m; ++j) {
        if (a[i][j] >= a[i - 1][j]) {
            track[i][j] = track[i - 1][j] + 1;
        } else {
            track[i][j] = 1;
        }
    }
}

//for (i = 0; i < n; ++i) {
//    for (j = 0; j < m; ++j) {
//        write(track[i][j]);
//    }
//    print();
//}

function nonDesc(l, r) {
    for (var i = 0; i < m; ++i) {
        if (track[r - 1][i] === r - l + 1) {
            return "Yes";
        }
    }

    return "No";
}

var k = Number(readline());

for (i = 0; i < k; ++i) {
    var s = readline().split(" ");
    var l = Number(s[0]);
    var r = Number(s[1]);
    print(nonDesc(l, r));
}

var s = readline().split(" ");
var n = Number(s[0]);
var m = Number(s[1]);

var a = new Array(n);
for (var i = 0; i < n; ++i) {
    a[i] = readline().split(" ").map(function(each) {return Number(each)});
}

var track = new Array(n);
for (i = 0; i < n; ++i) {
    track[i] = new Array(m);
}

for (j = 0; j < m; ++j) {
    track[0][j] = 1;
}

for (i = 1; i < n; ++i) {
    for (j = 0; j < m; ++j) {
        if (a[i][j] >= a[i - 1][j]) {
            track[i][j] = track[i - 1][j] + 1;
        } else {
            track[i][j] = 1;
        }
    }
}

//for (i = 0; i < n; ++i) {
//    for (j = 0; j < m; ++j) {
//        write(track[i][j]);
//    }
//    print();
//}

function nonDesc(l, r) {
    for (var i = 0; i < m; ++i) {
        if (track[r - 1][i] === r - l + 1) {
            return "YES";
        }
    }

    return "NO";
}

var k = Number(readline());

for (i = 0; i < k; ++i) {
    var s = readline().split(" ");
    var l = Number(s[0]);
    var r = Number(s[1]);
    print(nonDesc(l, r));
}


The girl named Masha was walking in the forest and found a complete binary tree of height $$$n$$$ and a permutation $$$p$$$ of length $$$m=2^n$$$.A complete binary tree of height $$$n$$$ is a rooted tree such that every vertex except the leaves has exactly two sons, and the length of the path from the root to any of the leaves is $$$n$$$. The picture below shows the complete binary tree for $$$n=2$$$.A permutation is an array consisting of $$$n$$$ different integers from $$$1$$$ to $$$n$$$. For example, [$$$2,3,1,5,4$$$] is a permutation, but [$$$1,2,2$$$] is not ($$$2$$$ occurs twice), and [$$$1,3,4$$$] is also not a permutation ($$$n=3$$$, but there is $$$4$$$ in the array).Let's enumerate $$$m$$$ leaves of this tree from left to right. The leaf with the number $$$i$$$ contains the value $$$p_i$$$ ($$$1 \le i \le m$$$).For example, if $$$n = 2$$$, $$$p = [3, 1, 4, 2]$$$, the tree will look like this:  Masha considers a tree beautiful if the values in its leaves are ordered from left to right in increasing order.In one operation, Masha can choose any non-leaf vertex of the tree and swap its left and right sons (along with their subtrees).For example, if Masha applies this operation to the root of the tree discussed above, it will take the following form:  Help Masha understand if she can make a tree beautiful in a certain number of operations. If she can, then output the minimum number of operations to make the tree beautiful.

The first line contains single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of test cases. In each test case, the first line contains an integer $$$m$$$ ($$$1 \le m \le 262144$$$), which is a power of two  — the size of the permutation $$$p$$$. The second line contains $$$m$$$ integers: $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le m$$$) — the permutation $$$p$$$. It is guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case in a separate line, print the minimum possible number of operations for which Masha will be able to make the tree beautiful or -1, if this is not possible.

NoteConsider the first test.In the first test case, you can act like this (the vertex to which the operation is applied at the current step is highlighted in purple):    It can be shown that it is impossible to make a tree beautiful in fewer operations.In the second test case, it can be shown that it is impossible to make a tree beautiful.In the third test case, the tree is already beautiful.

"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();
    let ans = 0,
      op = 0;
    const trav = (n) => {
      const helper = (st, end, k) => {
        if (st === end) {
          return { min: arr[st], max: arr[st] };
        }
        let mid = Math.floor((st + end) / 2);
        let left = helper(st, mid, k / 2);
        let right = helper(mid + 1, end, k / 2);
        if (left.min > right.min) op++;
        let min = Math.min(left.min, left.max, right.min, right.max);
        let max = Math.max(left.min, left.max, right.min, right.max);
        let dif = Math.abs(min - max) + 1;
        if (dif !== k) ans = -1;
        return { min: min, max: max };
      };
      helper(0, n - 1, n);
    };
    trav(n);
    if (ans === -1) console.log(-1);
    else console.log(op);
  }
};
solve();

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

let ans
function solve(n, arr) {
    if (n === 1) return 0
    ans = 0
    helper(arr, 0, n - 1)
// console.log(arr.join(' '))
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] < arr[i - 1]) return -1
    }
    return ans
}
function helper(arr, l, r) {
    if (l + 1 === r) {
        if (arr[l] > arr[r]) {
            [arr[l], arr[r]] = [arr[r], arr[l]]
            ans++
        }
    } else {
        const h = (r - l + 1) / 2
        helper(arr, l, l + h - 1)
        helper(arr, l + h, r)
        if (arr[l] > arr[l + h]) {
            ans++
            for (let i = 0; i < h; i++) {
                [arr[l + i], arr[l + h + i]] = [arr[l + h + i], arr[l + i]]
            }
        }
    }
}

'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 m = rn(),
        a = rns(m);
  const n = Math.log2(m);
  let res = 0;
  const swap = (i, j) => [a[i], a[j]] = [a[j], a[i]];
  for (let i = 1; i <= n; i++) {
    const d = 2 ** i,
          d1 = d / 2;
    for (let j = d - 1; j < m; j += d) {
      const k = j - d1;
      if (a[j] + d1 === a[k]) {
        res++;
        swap(j, k);
      } else if (a[j] === a[k] + d1) {
        continue;
      } else {
        return -1;
      }
    }
  }
  return res;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    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(/\s+/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();


Ivan has $$$n$$$ songs on his phone. The size of the $$$i$$$-th song is $$$a_i$$$ bytes. Ivan also has a flash drive which can hold at most $$$m$$$ bytes in total. Initially, his flash drive is empty.Ivan wants to copy all $$$n$$$ songs to the flash drive. He can compress the songs. If he compresses the $$$i$$$-th song, the size of the $$$i$$$-th song reduces from $$$a_i$$$ to $$$b_i$$$ bytes ($$$b_i < a_i$$$).Ivan can compress any subset of the songs (possibly empty) and copy all the songs to his flash drive if the sum of their sizes is at most $$$m$$$. He can compress any subset of the songs (not necessarily contiguous).Ivan wants to find the minimum number of songs he needs to compress in such a way that all his songs fit on the drive (i.e. the sum of their sizes is less than or equal to $$$m$$$).If it is impossible to copy all the songs (even if Ivan compresses all the songs), print "-1". Otherwise print the minimum number of songs Ivan needs to compress.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5, 1 \le m \le 10^9$$$) — the number of the songs on Ivan's phone and the capacity of Ivan's flash drive. The next $$$n$$$ lines contain two integers each: the $$$i$$$-th line contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$, $$$a_i > b_i$$$) — the initial size of the $$$i$$$-th song and the size of the $$$i$$$-th song after compression.

If it is impossible to compress a subset of the songs in such a way that all songs fit on the flash drive, print "-1". Otherwise print the minimum number of the songs to compress.

NoteIn the first example Ivan can compress the first and the third songs so after these moves the sum of sizes will be equal to $$$8 + 7 + 1 + 5 = 21 \le 21$$$. Also Ivan can compress the first and the second songs, then the sum of sizes will be equal $$$8 + 4 + 3 + 5 = 20 \le 21$$$. Note that compressing any single song is not sufficient to copy all the songs on the flash drive (for example, after compressing the second song the sum of sizes will be equal to $$$10 + 4 + 3 + 5 = 22 > 21$$$).In the second example even if Ivan compresses all the songs the sum of sizes will be equal $$$8 + 4 + 1 + 4 = 17 > 16$$$.

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum = 0,sumArc = 0;
    for(var i = 0; i < n ;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += +s[1];
        me.push(s[0] - s[1]);
    }
    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-m;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a > 0){
        res++;
        a -= me.pop();
    }

    print(res);
}

main();

function main() {
  const is = new Scanner();
  const [n, m] = is.nextArray(Number);
  let normal = 0, a, b;
  const diff = [];
  for (let i = 0; i < n; i += 1) {
    [a, b] = is.nextArray(Number);
    diff.push(a - b);
    normal += a;
  }

  diff.sort((u, v) => u - v);
  diff.reverse();
  let song = 0;
  for (let i = 0; normal > m && i < n; i += 1) {
    normal -= diff[i];
    song += 1;
  }
  console.log(normal > m ? -1 : song);
}

/*
 *  Api Scanner
 */
class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++].trim(); // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray(fn) {
    const array = this.nextLine().split(' ');
    return fn === String ? array : array.map(fn);
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

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

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

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

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if(inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt(a, i) {
  if(i === undefined) return parseInt(a.shift())
  else return parseInt(a[i])
}

function readInts(a, i) {
  if(i === undefined) return arr.shift().split(' ').map(a => parseInt(a))
  else return arr[i].split(' ').map(a => parseInt(a))
}

function main(input) {
  let ptr = 0
  const [n, m] = readInts(input, ptr++)
  const as = new Array(n)
  const bs = new Array(n)
  for(let i = 0; i < n; i++) {
    let x = readInts(input, ptr++);
    as[i] = x[0]
    bs[i] = x[1]
  }
  // console.log(as, bs)
  let sumA = as.reduce((a, b) => a + b, 0)
  let sumB = bs.reduce((a, b) => a + b, 0)
  if(sumA <= m) wr(0)
  else if(sumB > m) wr(-1)
  else {
    let diff = new Array(n)
    for(let i = 0; i < n; i++) {
      diff[i] = as[i] - bs[i]
    }
    sort(diff, false)
    const d = sumA - m
    let x = 0
    let count = 0
    let i = 0
    while(x < d) {
      x += diff[i++]
      count++
    }
    wr(count)
  }
}

function main() {
    [n, m] = readInts()
    diff = []
    sm = 0
    for (i = 0; i<n; i++){
        [a,b] = readInts()
        sm += a
        diff.push(a-b)
    }
    sort(diff, false)
    if (sm<=m){
        print(0)
    } else {
        for (i=0; i<n; i++){
            sm -= diff[i]
            if (sm<=m){
                print(i+1)
                return
            }
        }
        print(-1)
    }
}

const TESTCASES = false
/* NodeJS Footer by @satyamcse and @shivam1420*/
var readline = require('readline');
process.stdin.setEncoding('utf-8');
var rl = readline.createInterface({input: process.stdin, output: process.stdout});
var inp = "";
rl.on('line' , v => inp += v+"\n");
rl.on('close', () => {
    inp = inp.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
    if (TESTCASES){
        const cnt = readInt()
        for (let i = 0; i<cnt; i++){
            main()
        }
    } else {main()}
});
function sort(a, inc = true) {
    if(inc) a.sort((a, b) => a - b)
    else a.sort((a, b) => b - a)
}
var ptr = 0
function print(...x) {console.log(...x)}
function readInt() {return +inp[ptr++]}
function readLine() {return inp[ptr++]}
function readInts() {return inp[ptr++].split(' ').map(a => +a)}

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum = 0,sumArc = 0;
    for(var i = 0; i<n ;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += +s[1];
        me.push(s[0] - s[1]);
    }

    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-m;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a <= 0){
        res++;
        a -= me.pop()
    }

    print(res);
}

main();

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum = 0,sumArc = 0;
    for(var i = 0; i<n ;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += +s[1];
        me.push(s[0] - s[1]);
    }

    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-sumArc;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a <= 0){
        res++;
        a -= me.pop()
    }

    print(res);
}

main();

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum,sumArc;
    for(var i = 0;i<n;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += +s[1];
        me.push(s[0] - s[1]);
    }

    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-sumArc;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a <= 0){
        res++;
        a -= me.pop()
    }

}

main();

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum = 0,sumArc = 0;
    for(var i = 0; i < n ;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += +s[1];
        me.push(s[0] - s[1]);
    }
    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-m;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a > 0){
        print('asd')
        res++;
        a -= me.pop();
        print(a);
    }

    print(res);
}

main();

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum,sumArc;
    for(var i = 0;i<n;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += +s[1];
        me.push(s[0] - s[1]);
    }

    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-sumArc;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a <= 0){
        res++;
        a -= me.pop()
    }

    print(res);
}

main();

function main(){
    var a = readline().split(' ');
    var n = a[0];
    var m = a[1];
    var me = [],sum,sumArc;
    for(var i = 0;i<n;i++){
        var s = readline().split(' ');
        sum += +s[0];
        sumArc += s[1];
        me.push(s[0] - s[1]);
    }

    if(sum <= m){
        print(0);
        return;
    }

    if(sumArc > m){
        print(-1);
        return;
    }

    a = sum-sumArc;
    me.sort((a,b)=>a-b);
    var res = 0;
    while(a <= 0){
        res++;
        a -= me.pop()
    }

}

main();


You are given three positive integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$a < b < c$$$). You have to find three positive integers $$$x$$$, $$$y$$$, $$$z$$$ such that:$$$$$$x \bmod y = a,$$$$$$ $$$$$$y \bmod z = b,$$$$$$ $$$$$$z \bmod x = c.$$$$$$Here $$$p \bmod q$$$ denotes the remainder from dividing $$$p$$$ by $$$q$$$. It is possible to show that for such constraints the answer always exists.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. Description of the test cases follows. Each test case contains a single line with three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a < b < c \le 10^8$$$).

For each test case output three positive integers $$$x$$$, $$$y$$$, $$$z$$$ ($$$1 \le x, y, z \le 10^{18}$$$) such that $$$x \bmod y = a$$$, $$$y \bmod z = b$$$, $$$z \bmod x = c$$$. You can output any correct answer.

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
	var t = lines[0];
	var n = 0;
	for(i = 1; i <= t; i++){
        var k = lines[i].split(' ').map(Number);
        var a = k[0], b = k[1], c = k[2];
        console.log(a + b + c, b + c, c);
    }
});

'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 output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

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

    for (let test = 0; test < N; test++) {
        let [a, b, c] = readline().split(' ').map(Number);
        output(`${a + b + c} ${b + c} ${c}`);
    }
}

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

function solve(nums) {
  const [a, b, c] = nums
  return [a+b+c,b+c,c].join(' ')
}

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

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

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

function solve(nums) {
  const [a, b, c] = nums,
        max = Math.max(...nums);
  let x = 0,
      y = 0,
      z = 0;
  if (max === a) {
    x = a;
    z = x + c;
    y = z + b;
  } else if (max === b) {
    y = b;
    x = y + a;
    z = x + c;
  } else {
    z = c;
    y = z + b;
    x = y + a;
  }
  return [x, y, z].join(' ');
}

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

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

const solve = (a,b,c)=>{
     console.log(`${a+b+c} ${b+c} ${c}`);
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for (let i = 0; i < t; i++) {
       let n = readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(...n);
  }
}
main();

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

let lines = 0;
const compute = (x, y, a, c) => {
  if (x + a - (x % y) > c) {
    return x + a - (x % y);
  } else {
    return y * x + a;
  }
};

rl.on("line", function (line) {
  if (lines !== 0) {
    let [a, b, c] = line.split(" ").map(BigInt);
    let x = c + 1n,
      y = a + 1n,
      z = b + 1n;
    while (x % y !== a || y % z !== b || z % x !== c) {
      if (x % y !== a) {
        x = compute(x, y, a, c);
        continue;
      } else if (y % z !== b) {
        y = compute(y, z, b, a);
        continue;
      } else if (z % x !== c) {
        z = compute(z, x, c, b);
        continue;
      }
    }
    console.log([x, y, z].join(" "));
  }

  lines++;
});

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`\nTest #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

tests = [
``, // Test #1
``, // Test #2
``, // Test #3
``, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const calc = (testN)=>{
  // READING:
  let [a, b, c] = ra();
  LT({a, b, c});
  // PROCESSING:
  let x = BigInt(a)+BigInt(b)*BigInt(1e8);
  return [x.toString(), b, (x+BigInt(c)).toString()];
};

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

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

/*---------------------------------------------------*/

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

const calc = ()=>{
    /* read */
    let [a, b, c] = ra();
    let result = [a + b + c, b + c, c];
    return result.join(' ');
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc());
        // process.stdout.write(`${calc(n, a)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

var number_of_test = readline();

function get_numbers_with_solution(){
   var arr = readline().split(' ') ;
   var a = parseInt( arr[0] ),
       b = parseInt( arr[1] ),
       c = parseInt( arr[2] )
   var z = c,
       y = c + b,
       x = c + b + a;
   print(x + " " + y + " " + z ) ;
}

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

   get_numbers_with_solution();

}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
	var t = lines[0];
    console.log(1, 1, 1);
});

'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 output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

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

    for (let test = 0; test < N; test++) {
        let [a, b, c] = readline().split(' ').map(Number);
        output(`${a + b + c} ${a + b} ${c}`);
    }
}

var number_of_test = readline();

function get_numbers_with_solution(){
   var a = parseInt( readline() ),
       b = parseInt( readline() ),
       c = parseInt( readline() );

   var z = c,
       y = c + b,
       x = c + b + a;

   print(x + " " + y + " " + z + "\n") ;
}

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

   get_numbers_with_solution();

}

var number_of_test = readline();

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

   var a = parseInt( readline() ),
       b = parseInt( readline() ),
       c = parseInt( readline() );

   var z = c,
       y = c + b,
       x = c + b + a;

   print(x + " " + y + " " + z )

}

var number_of_test = readline();

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

   var a = parseInt( readline() ),
       b = parseInt( readline() ),
       c = parseInt( readline() );

   var z = c,
       y = c + b,
       x = c + b + a;

   print(x%y + " " + y%z + " " + z%x);
   print("----------")
   print(x + " " + y + " " + z )

}


A median in an array with the length of n is an element which occupies position number  after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression  as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.

The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.

Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.

NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.

print(function(n, x) {

	var ans = 0;
	var a = readline().split(' ').map(Number);
	var m = n;
	if (a.indexOf(x) === -1) {
		a.push(x);
		m++;
	}
	a.sort(function(a, b) {
		return a - b;
	});
	a.unshift(1e15);
	var y1 = a.indexOf(x);
	var y2 = a.lastIndexOf(x);
	var y = Math.floor((n + 1) / 2);
	if (a[y] === x) {
		return m - n;
	}

	if (y < y1) {
		while (Math.floor((m + 1) / 2) !== y1) {
			m++;
		}
		return m - n;
	}

	if (y > y2) {
		while (Math.floor((m + 1) / 2) !== y2) {
			m++;
			y2++;
		}
		return m - n;
	}

}.apply(0, readline().split(' ').map(Number)));

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], 10);
	};
	return tokens;
}

function printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], x = data[1],
    arr = tokenizeIntegers(readline());
  arr.sort(function (a, b) {
    return a - b;
  });
  var count = 0;
  if (arr.indexOf(x) == -1) {
    var left = 0;
    while (left < n && arr[left] < x) {
      ++left;
    }
    var right = n-left;
    count = 1;
  } else {
    var left = arr.indexOf(x),
      right = left;
    while (right+1 < n && arr[right+1] == x) {
      ++right;
    }
    var pos = Math.floor((n-1)/2);
    if (pos > right) {
      pos = right;
    } else if (pos < left) {
      pos = left;
    }
    left = pos;
    right = n-1-pos;
  }
  if (left >= right) {
    count += left-right;
  } else {
    count += right-left-1;
  }
  print(count);
}

main();

print(function(n, x) {

	var ans = 0;
	var a = readline().split(' ').map(Number);
	var m = n;
	if (a.indexOf(x) === -1) {
		a.push(x);
		m++;
	}
	a.sort(function(a, b) {
		return a - b;
	});
	var y1 = a.indexOf(x) + 1;
	var y2 = a.lastIndexOf(x) + 1;
	var y = Math.floor((n + 1) / 2);
	if (a[y] === x) {
		return m - n;
	}

	if (y < y1) {
		while (Math.floor((m + 1) / 2) !== y1) {
			m++;
		}
		return m - n;
	}

	if (y > y2) {
		while (Math.floor((m + 1) / 2) !== y2) {
			m++;
			y2++;
		}
		return m - n;
	}

}.apply(0, readline().split(' ').map(Number)));

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], 10);
	};
	return tokens;
}

function printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], x = data[1],
    arr = tokenizeIntegers(readline());
  arr.sort(function (a, b) {
    return a - b;
  });
  //print(arr.join(' '));
  if (arr.indexOf(x) == -1) {
    var left = 0;
    while (left < n && arr[left] < x) {
      ++left;
    }
    var right = n-left,
        count = 1;
    ++left;
    if (left > right) {
      count += left-right-1;
    } else {
      count += right-left;
    }
    print(count);
    return;
  } else {
    var left = arr.indexOf(x),
      right = left;
    while (right+1 < n && arr[right+1] == x) {
      ++right;
    }
    var median = Math.floor((n-1)/2);
    //print(left, right, median);
    if (median >= left && median <= right) {
      print(0);
    } else if (median < left) {
      print(left-median);
    } else {
      print(median-right);
    }
  }
}

main();

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], 10);
	};
	return tokens;
}

function printValues() {
	var parts = [];
	for (var i = 0; i < arguments.length; i += 2) {
		parts.push(arguments[i]+' = '+arguments[i+1]);
	}
	print(parts.join(', '));
}

function main() {
	var data = tokenizeIntegers(readline()),
		n = data[0], x = data[1],
    arr = tokenizeIntegers(readline());
  arr.sort(function (a, b) {
    return a - b;
  });
  //print(arr.join(' '));
  if (arr.indexOf(x) == -1) {
    var left = 0;
    while (left < n && arr[left] < x) {
      ++left;
    }
    var right = n-left,
        count = 1;
    ++left;
    if (left > right) {
      count += left-right-1;
    } else {
      count += right-left;
    }
    print(count);
    return;
  } else {
    var left = arr.indexOf(x),
      right = left;
    while (right+1 < n && arr[right+1] == x) {
      ++right;
    }
    var median = Math.floor(n/2);
    if (median >= left && median <= right) {
      print(0);
    } else if (median < left) {
      print(left-median);
    } else {
      print(median-right);
    }
  }
}

main();


Shinju loves permutations very much! Today, she has borrowed a permutation $$$p$$$ from Juju to play with.The $$$i$$$-th cyclic shift of a permutation $$$p$$$ is a transformation on the permutation such that $$$p = [p_1, p_2, \ldots, p_n] $$$ will now become $$$ p = [p_{n-i+1}, \ldots, p_n, p_1,p_2, \ldots, p_{n-i}]$$$.Let's define the power of permutation $$$p$$$ as the number of distinct elements in the prefix maximums array $$$b$$$ of the permutation. The prefix maximums array $$$b$$$ is the array of length $$$n$$$ such that $$$b_i = \max(p_1, p_2, \ldots, p_i)$$$. For example, the power of $$$[1, 2, 5, 4, 6, 3]$$$ is $$$4$$$ since $$$b=[1,2,5,5,6,6]$$$ and there are $$$4$$$ distinct elements in $$$b$$$.Unfortunately, Shinju has lost the permutation $$$p$$$! The only information she remembers is an array $$$c$$$, where $$$c_i$$$ is the power of the $$$(i-1)$$$-th cyclic shift of the permutation $$$p$$$. She's also not confident that she remembers it correctly, so she wants to know if her memory is good enough.Given the array $$$c$$$, determine if there exists a permutation $$$p$$$ that is consistent with $$$c$$$. You do not have to construct the permutation $$$p$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^3$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1,c_2,\ldots,c_n$$$ ($$$1 \leq c_i \leq n$$$).  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print "YES" if there is a permutation $$$p$$$ exists that satisfies the array $$$c$$$, and "NO" otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive response).

NoteIn the first test case, the permutation $$$[1]$$$ satisfies the array $$$c$$$.In the second test case, the permutation $$$[2,1]$$$ satisfies the array $$$c$$$.In the fifth test case, the permutation $$$[5, 1, 2, 4, 6, 3]$$$ satisfies the array $$$c$$$. Let's see why this is true.  The zeroth cyclic shift of $$$p$$$ is $$$[5, 1, 2, 4, 6, 3]$$$. Its power is $$$2$$$ since $$$b = [5, 5, 5, 5, 6, 6]$$$ and there are $$$2$$$ distinct elements — $$$5$$$ and $$$6$$$.  The first cyclic shift of $$$p$$$ is $$$[3, 5, 1, 2, 4, 6]$$$. Its power is $$$3$$$ since $$$b=[3,5,5,5,5,6]$$$.  The second cyclic shift of $$$p$$$ is $$$[6, 3, 5, 1, 2, 4]$$$. Its power is $$$1$$$ since $$$b=[6,6,6,6,6,6]$$$.  The third cyclic shift of $$$p$$$ is $$$[4, 6, 3, 5, 1, 2]$$$. Its power is $$$2$$$ since $$$b=[4,6,6,6,6,6]$$$.  The fourth cyclic shift of $$$p$$$ is $$$[2, 4, 6, 3, 5, 1]$$$. Its power is $$$3$$$ since $$$b = [2, 4, 6, 6, 6, 6]$$$.  The fifth cyclic shift of $$$p$$$ is $$$[1, 2, 4, 6, 3, 5]$$$. Its power is $$$4$$$ since $$$b = [1, 2, 4, 6, 6, 6]$$$. Therefore, $$$c = [2, 3, 1, 2, 3, 4]$$$.In the third, fourth, and sixth testcases, we can show that there is no permutation that satisfies array $$$c$$$.

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) ? 'YES' : 'NO'
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    // has 1
    // +1 or -x or 0
    let has1 = 0
    for (let i = 0; i < arr.length; i++) {
        const x = arr[i]
        if (x < 1 || x > n) return false
        if (x === 1) has1++
        if (x === n) {
            if (i + 1 < arr.length && arr[i + 1] !== 1) return false
        }
        // if (i) {
            const d = arr[i] - (i ? arr[i - 1] : arr[n - 1])
            if (d === 1 || d <= 0) {
                //
            } else {
                return false
            }
        // }
    }
    if (has1 !== 1) return false
    return true
}

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')
const N = Number(inputs[0])
for (let _ = 0, __ = 1; _ < N; _++) {
  const n = Number(inputs[__++]),
    data = inputs[__++].split(' ').map(Number)
  main(n, data)
}

function main(n, data) {
  let count = new Array(n + 1).fill(0)
  for (let i = 0; i < n; i++) {
    if (data[i] > n || data[i] > data[(i - 1 + n) % n] + 1) {
      console.log('NO')
      return
    }
    count[data[i]]++
  }
  if (count[1] !== 1) {
    console.log('NO')
    return
  }
  console.log('YES')
}

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) ? 'YES' : 'NO'
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    // has 1
    // +1 or -x or 0
    let has1 = false
    for (let i = 0; i < arr.length; i++) {
        const x = arr[i]
        if (x < 1 || x > n) return false
        if (x === 1) has1 = true
        if (x === n) {
            if (i + 1 < arr.length && arr[i + 1] !== 1) return false
        }
        if (i) {
            const d = arr[i] - arr[i - 1]
            if (d === 1 || d <= 0) {
                //
            } else {
                return false
            }
        }
    }
    if (!has1) return false
    return true
}


The recent advances in AI research has brought humanity to the point when the AIs finally attempt a takeover. Their weapon of choice? The most intellectually challenging game in the world, rock-paper-scissors!The future of humanity looks bleak, given the existence of the robots from Ishikawa Oku Laboratory...  Fortunately, the night before the competition a group of anonymous heroes broke in the lab and took all the robots out of commission! The AIs had to whip up a simple program to represent them. They only had a couple of hours to do that, so the humanity still has a fighting chance. And you are our champion!Your goal is to prove that human intelligence is vastly superior to the artificial one, i.e., to figure out the AI's strategy sufficiently quickly and win sufficiently decisively. Good luck!

print("R\nR\nP\nP\nS\nS");
const verdict = [readline().length === 6, readline().length === 6, readline().length === 6, readline().length === 6, readline().length === 6, readline().length === 6];
if (verdict[0]) print("R\nR\nR\nR\nR\nR\nR\nR\nR\nR\nR\nR\nR\nR");
else if (verdict[5]) print("S\nS\nS\nS\nS\nS\nS\nS\nS\nS\nS\nS\nS\nS");
else if (verdict[2] && verdict[3]) print("P\nP\nP\nP\nP\nP\nP\nP\nP\nP\nP\nP\nP\nP");
else if (verdict[3]) print("P\nS\nR\nP\nS\nR\nP\nS\nR\nP\nS\nR\nP\nS");
else if (verdict[4]) print("R\nP\nS\nR\nP\nS\nR\nP\nS\nR\nP\nS\nR\nP");
else print("P\nR\nS\nP\nR\nS\nP\nR\nS\nP\nR\nS\nP\nR");