You are given two arrays: an array $$$a$$$ consisting of $$$n$$$ zeros and an array $$$b$$$ consisting of $$$n$$$ integers.You can apply the following operation to the array $$$a$$$ an arbitrary number of times: choose some subsegment of $$$a$$$ of length $$$k$$$ and add the arithmetic progression $$$1, 2, \ldots, k$$$ to this subsegment — i. e. add $$$1$$$ to the first element of the subsegment, $$$2$$$ to the second element, and so on. The chosen subsegment should be inside the borders of the array $$$a$$$ (i.e., if the left border of the chosen subsegment is $$$l$$$, then the condition $$$1 \le l \le l + k - 1 \le n$$$ should be satisfied). Note that the progression added is always $$$1, 2, \ldots, k$$$ but not the $$$k, k - 1, \ldots, 1$$$ or anything else (i.e., the leftmost element of the subsegment always increases by $$$1$$$, the second element always increases by $$$2$$$ and so on).Your task is to find the minimum possible number of operations required to satisfy the condition $$$a_i \ge b_i$$$ for each $$$i$$$ from $$$1$$$ to $$$n$$$. Note that the condition $$$a_i \ge b_i$$$ should be satisfied for all elements at once.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$) — the number of elements in both arrays and the length of the subsegment, respectively. The second line of the input contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 10^{12}$$$), where $$$b_i$$$ is the $$$i$$$-th element of the array $$$b$$$.

Print one integer — the minimum possible number of operations required to satisfy the condition $$$a_i \ge b_i$$$ for each $$$i$$$ from $$$1$$$ to $$$n$$$.

NoteConsider the first example. In this test, we don't really have any choice, so we need to add at least five progressions to make the first element equals $$$5$$$. The array $$$a$$$ becomes $$$[5, 10, 15]$$$.Consider the second example. In this test, let's add one progression on the segment $$$[1; 3]$$$ and two progressions on the segment $$$[4; 6]$$$. Then, the array $$$a$$$ becomes $$$[1, 2, 3, 2, 4, 6]$$$.

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

// inspired by https://www.luogu.com.cn/blog/kkxhh/solution-p1438
function solve(n, k, arr) {
    const tree = []
    createTree(tree, 0, 0, n - 1, 0n)
    let ans = 0n
    for (let i = arr.length - 1; i >= 0; i--) {
        const now = queryTree(tree, 0, i, i, 0n, 0n)
        if (now >= arr[i]) continue

        const rk = Math.min(i + 1, k)
        // const t = Math.ceil((arr[i] - now) / rk)
        const t = ceil((arr[i] - now), BigInt(rk))
        const left = i - rk + 1
        // [left, right] + [1, k]
        // for each, 1 - left + `i`
        insertTree(tree, 0, left, i, [BigInt(1 - left) * t, t])
        ans += t
    }
// console.log(tree)
    return ans
}
function ceil(a, b) {
    const r = a % b
    return r ? a / b + 1n : a / b
}
function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: [0n, 0n] }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function insertTree(tree, idx, l, r, val) { // same l, r
    const { left, right, lazy } = tree[idx]
    if (l <= left && r >= right) {
        // tree[idx].val += lazy
        // tree[idx].lazy = tree[idx].lazy || [0n, 0n]
        tree[idx].lazy[0] += val[0]
        tree[idx].lazy[1] += val[1]
        return
    }

    // if (lazy && left !== right) {
    //     // tree[2 * idx + 1].val += lazy
    //     // tree[2 * idx + 2].val += lazy
    //     tree[2 * idx + 1].lazy = tree[2 * idx + 1].lazy || [0n, 0n]
    //     tree[2 * idx + 1].lazy[0] += lazy[0]
    //     tree[2 * idx + 1].lazy[1] += lazy[1]
    //     tree[2 * idx + 2].lazy = tree[2 * idx + 2].lazy || [0n, 0n]
    //     tree[2 * idx + 2].lazy[0] += lazy[0]
    //     tree[2 * idx + 2].lazy[1] += lazy[1]
    //     tree[idx].lazy = null
    // }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        insertTree(tree, 2 * idx + 1, l, r, val)
    }
    if (r > mid) {
        insertTree(tree, 2 * idx + 2, l, r, val)
    }
    // const merge = add
    // tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r, t1, t2) {
    const { left, right, val, lazy } = tree[idx]
    if (left === right) {
        return (lazy[0] + t1) + BigInt(left) * (lazy[1] + t2)
    }
//         if (lazy && left === right) {
//             tree[idx].val += (lazy[0] + t1) + BigInt(left) * (lazy[1] + t2)
// // console.log('relax', left, right, tree[idx].val)
//             // tree[idx].lazy = null
//         }
//     if (l <= left && r >= right) return tree[idx].val

    const mid = Math.floor((left + right) / 2)
    // if (lazy) {
    //     // tree[2 * idx + 1].val += lazy
    //     // tree[2 * idx + 2].val += lazy
    //     tree[2 * idx + 1].lazy = tree[2 * idx + 1].lazy || [0n, 0n]
    //     tree[2 * idx + 1].lazy[0] += lazy[0]
    //     tree[2 * idx + 1].lazy[1] += lazy[1]
    //     tree[2 * idx + 2].lazy = tree[2 * idx + 2].lazy || [0n, 0n]
    //     tree[2 * idx + 2].lazy[0] += lazy[0]
    //     tree[2 * idx + 2].lazy[1] += lazy[1]
    //     tree[idx].lazy = null
    // }

    let a = 0n
    let b = 0n
    if (l <= mid) {
        a = queryTree(tree, 2 * idx + 1, l, r, t1 + lazy[0], t2 + lazy[1])
    }
    if (r > mid) {
        b = queryTree(tree, 2 * idx + 2, l, r, t1 + lazy[0], t2 + lazy[1])
    }
    const merge = add
    return merge(a, b)
}
function add(a, b) {
    return a + b
}

'use strict';
 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
  rl.on('line', line => {
      lines.push(line);
  });
  rl.on('close', main)
}
let rli = 0;
function readline() {
    return lines[rli++];
}
const l = process.env.DEBUG ? console.log : ()=>{};

module.exports = E;

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

const calc = (n, k, b)=>{
  let ans = BigInt(0);
  let sum = 0;
  let cnt = 0;
  let closed = new Array(n).fill(0);
  for (let i=n-1; i>=0; i--){
    sum -= (cnt);
    cnt -= closed[i]
    b[i] -= sum;
    if (b[i]<=0)
      continue;
    let el = Math.min(i+1, k)
    let need = Math.ceil(b[i] / el)
    sum += need * el;
    cnt += need;
    ans += BigInt(need);
    if (i-el>=0)
      closed[i-el] += need;
  }
  return ans.toString()
};

function main() {
    let T = 1||+readline()
    while (T--){
      let [n, k] = ra();
      let b = ra();
      l('ans')
      print(calc(n, k, b));
    }
}

E.calc = calc;

'use strict';
 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
  rl.on('line', line => {
      lines.push(line);
  });
  rl.on('close', main)
}
let rli = 0;
function readline() {
    return lines[rli++];
}
const l = process.env.DEBUG ? console.log : ()=>{};

module.exports = E;

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

const calc = (n, k, b)=>{
  let ans = BigInt(0);
  let sum = 0;
  let cnt = 0;
  let closed = new Array(n).fill(0);
  for (let i=n-1; i>=0; i--){
    sum -= (cnt);
    cnt -= closed[i]
    b[i] -= sum;
    if (b[i]<=0)
      continue;
    let el = Math.min(i+1, k)
    let need = Math.floor((b[i]+el-1) / el)
    sum += need * el;
    cnt += need;
    ans += BigInt(need);
    if (i-el>=0)
      closed[i-el] += need;
  }
  return ans.toString()
};

function main() {
    let T = 1||+readline()
    while (T--){
      let [n, k] = ra();
      let b = ra();
      l('ans')
      print(calc(n, k, b));
    }
}

E.calc = calc;

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

const MAN = 10 ** 15
const add = (a, b) => {
  if (typeof a === 'bigint' || typeof a === 'bigint' || a + b >= MAN) return BigInt(a) + BigInt(b)
  return a + b
}
const mul = (a, b) => {
  if (typeof a === 'bigint' || typeof a === 'bigint' || a * b >= MAN) return BigInt(a) * BigInt(b)
  return a * b
}
const sub = (a, b) => {
  if (typeof a === 'number' && typeof b === 'number') return a - b
  let res = BigInt(a) - BigInt(b)
  if (res >= MAN) return res
  return Number(res)
}

function solve(n, k, data) {
  const nums = new Array(n).fill(0)
  let res = 0,
    sum = 0,
    base = 0
  for (let i = n - 1; i >= 0; i--) {
    if (i + 1 < k) k--
    sum = sub(sum, base)
    base = add(base, nums[i])

    let cur = Math.max(0, Math.ceil(sub(data[i], sum) / k))

    res = add(res, cur)
    base = add(base, cur)

    if (i >= k) nums[i - k] = -cur
    sum = add(sum, mul(cur, k))
  }
  return res
}

void (function main() {
  const [n, k] = inputs[0].split(' ').map(Number)
  const data = inputs[1].split(' ').map(Number)

  console.log(solve(n, k, data).toString())
})()

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

function solve(n, k, arr) {
    const tree = []
    createTree(tree, 0, 0, n - 1, 0)
    let ans = 0
    for (let i = arr.length - 1; i >= 0; i--) {
        const now = queryTree(tree, 0, i, i)
        if (now >= arr[i]) continue

        const rk = Math.min(i + 1, k)
        const t = Math.ceil((arr[i] - now) / rk)
        insertTree(tree, 0, i - rk + 1, i, [i - rk, t])
        ans += t
    }
// console.log(tree)
    return ans
}
function createTree(tree, p, left, right, val) {
    tree[p] = { left, right, val, lazy: [] }
    if (left === right) return

    const mid = Math.floor((left + right) / 2)
    createTree(tree, 2 * p + 1, left, mid, val)
    createTree(tree, 2 * p + 2, mid + 1, right, val)
}
function insertTree(tree, idx, l, r, val) { // same l, r
    const { left, right, lazy } = tree[idx]
    if (l <= left && r >= right) {
        // tree[idx].val += lazy
        tree[idx].lazy.push(val)
        return
    }

    if (lazy.length && left !== right) {
        // tree[2 * idx + 1].val += lazy
        // tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy.push(...lazy)
        tree[2 * idx + 2].lazy.push(...lazy)
        tree[idx].lazy = []
    }

    const mid = Math.floor((left + right) / 2)
    if (l <= mid) {
        insertTree(tree, 2 * idx + 1, l, r, val)
    }
    if (r > mid) {
        insertTree(tree, 2 * idx + 2, l, r, val)
    }
    const merge = add
    tree[idx].val = merge(tree[2 * idx + 1].val, tree[2 * idx + 2].val)
}
function queryTree(tree, idx, l, r) {
    const { left, right, val, lazy } = tree[idx]
        if (lazy.length && left === right) {
            lazy.forEach(([x, t]) => {
                tree[idx].val += (left - x) * t
            })
// console.log('relax', left, right, tree[idx].val)
            tree[idx].lazy = []
        }
    if (l <= left && r >= right) return tree[idx].val

    const mid = Math.floor((left + right) / 2)
    if (lazy.length) {
        // tree[2 * idx + 1].val += lazy
        // tree[2 * idx + 2].val += lazy
        tree[2 * idx + 1].lazy.push(...lazy)
        tree[2 * idx + 2].lazy.push(...lazy)
        tree[idx].lazy = []
    }

    let a = 0
    let b = 0
    if (l <= mid) {
        a = queryTree(tree, 2 * idx + 1, l, r)
    }
    if (r > mid) {
        b = queryTree(tree, 2 * idx + 2, l, r)
    }
    const merge = add
    return merge(a, b)
}
function add(a, b) {
    return a + b
}

'use strict';
 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
  rl.on('line', line => {
      lines.push(line);
  });
  rl.on('close', main)
}
let rli = 0;
function readline() {
    return lines[rli++];
}
const l = process.env.DEBUG ? console.log : ()=>{};

module.exports = E;

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

const calc = (n, k, b)=>{
  let ans = (0);
  let sum = 0;
  let cnt = 0;
  let closed = new Array(n).fill(0);
  for (let i=n-1; i>=0; i--){
    sum -= (cnt);
    cnt -= closed[i]
    b[i] -= sum;
    if (b[i]<=0)
      continue;
    let el = Math.min(i+1, k)
    let need = Math.floor((b[i]+el-1) / el)
    sum += need * el;
    cnt += need;
    ans += (need);
    if (i-el>=0)
      closed[i-el] += need;
  }
  return ans.toString()
};

function main() {
    let T = 1||+readline()
    while (T--){
      let [n, k] = ra();
      let b = ra();
      l('ans')
      print(calc(n, k, b));
    }
}

E.calc = calc;

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

const MAN = 10 ** 15
const add = (a, b) => {
  if (typeof a === 'bigint' || typeof a === 'bigint' || a + b >= MAN) return BigInt(a) + BigInt(b)
  return a + b
}
const mul = (a, b) => {
  if (typeof a === 'bigint' || typeof a === 'bigint' || a * b >= MAN) return BigInt(a) * BigInt(b)
  return a * b
}
const sub = (a, b) => {
  if (typeof a === 'number' && typeof b === 'number') return a - b
  let res = BigInt(a) - BigInt(b)
  if (res >= MAN) return res
  return Number(res)
}

function solve(n, k, data) {
  const nums = new Array(n).fill(0)
  let res = 0,
    sum = 0,
    base = 0
  for (let i = n - 1; i >= 0; i--) {
    if (i + 1 < k) k--
    sum = sub(sum, base)
    base = add(base, nums[i])

    let cur = Math.max(0, Math.ceil(sub(data[i], sum) / k))

    res = add(res, cur)
    base = add(base, cur)

    if (i >= k) nums[i - k] = -cur
    sum = add(sum, mul(cur, k))
  }
  return res
}

void (function main() {
  const [n, k] = inputs[0].split(' ').map(Number)
  const data = inputs[1].split(' ').map(Number)

  console.log(solve(n, k, data))
})()

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

function solve(n, k, data) {
  const nums = new Array(n).fill(0)
  let res = 0,
    sum = 0,
    base = 0
  for (let i = n - 1; i >= 0; i--) {
    if (i + 1 < k) k--
    sum -= base
    base += nums[i]

    let cur = Math.max(0, Math.ceil((data[i] - sum) / k))

    res += cur
    base += cur
    if (i >= k) nums[i - k] = -cur

    sum += cur * k
  }
  return res
}

void (function main() {
  const [n, k] = inputs[0].split(' ').map(Number)
  const data = inputs[1].split(' ').map(Number)

  console.log(solve(n, k, data))
})()


This is the easy version of the problem. The only difference between the versions is the constraints on $$$n$$$, $$$k$$$, $$$a_i$$$, and the sum of $$$n$$$ over all test cases. You can make hacks only if both versions of the problem are solved.Note the unusual memory limit.You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$ of length $$$n$$$, and an integer $$$k$$$.The cost of an array of integers $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$ is $$$$$$\max\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right) - \min\limits_{1 \le i \le n}\left(\left \lfloor \frac{a_i}{p_i} \right \rfloor \right).$$$$$$Here, $$$\lfloor \frac{x}{y} \rfloor$$$ denotes the integer part of the division of $$$x$$$ by $$$y$$$. Find the minimum cost of an array $$$p$$$ such that $$$1 \le p_i \le k$$$ for all $$$1 \le i \le n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 3000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_1 \le a_2 \le \ldots \le a_n \le 3000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3000$$$.

For each test case, print a single integer — the minimum possible cost of an array $$$p$$$ satisfying the condition above.

NoteIn the first test case, the optimal array is $$$p = [1, 1, 1, 2, 2]$$$. The resulting array of values of $$$\lfloor \frac{a_i}{p_i} \rfloor$$$ is $$$[4, 5, 6, 4, 5]$$$. The cost of $$$p$$$ is $$$\max\limits_{1 \le i \le n}(\lfloor \frac{a_i}{p_i} \rfloor) - \min\limits_{1 \le i \le n}(\lfloor \frac{a_i}{p_i} \rfloor) = 6 - 4 = 2$$$. We can show that there is no array (satisfying the condition from the statement) with a smaller cost.In the second test case, one of the optimal arrays is $$$p = [12, 12, 12, 12, 12]$$$, which results in all $$$\lfloor \frac{a_i}{p_i} \rfloor$$$ being $$$0$$$.In the third test case, the only possible array is $$$p = [1, 1, 1]$$$.

'use strict';

function solve(n, m, a) {
  const N = Math.min(...a);
  const max = new Array(N + 10).fill(-1);
  max[N] = N;
  let min = 1;
  for (let num of a) {
    const tmp = Math.floor(num / m);
    min = Math.max(min, tmp);
    let p = num;
    for (let i = Math.max(2, Math.floor(num / N)); i <= N; i++) {
      const cur = Math.floor(num / i);
      if (cur === p) {
        break;
      }
      if (cur <= N) {
        max[cur + 1] = Math.max(max[cur + 1], p);
      }
      p = cur;
    }
  }
  let res = Infinity;
  let p = -1;
  for (let i = 1; i <= N; i++) {
    p = Math.max(p, max[i]);
    res = Math.min(res, Math.max(min, p) - i);
  }
  return res === Infinity ? Math.max(min - N, 0) : Math.max(res, 0);
}

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

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

'use strict';

function solve(n, m, a) {
  a.sort((a, b) => a - b);
  const set = new Set();
  for (let i = 1; i <= m; i++) {
    set.add(Math.floor(a[0] / i));
  }
  const check = t => {
    let res = [t, t, t, t];
    for (let i = 0; i < n; i++) {
      const k = Math.floor(a[i] / t);
      let min = t,
          max = t;
      if (k >= m) {
        max = min = Math.floor(a[i] / m);
      } else {
        const num = Math.floor(a[i] / k);
        if (num > t) {
          max = num;
          min = Math.floor(a[i] / (k + 1));
        } else if (num < t) {
          min = num;
          if (k > 1) max = Math.floor(a[i] / (k - 1));else max = min;
        }
      }
      res[0] = Math.min(res[0], min);
      res[1] = Math.max(res[1], min);
      res[2] = Math.min(res[2], max);
      res[3] = Math.max(res[3], max);
    }
    return Math.min(res[1] - res[0], res[3] - res[2]);
  };
  let res = Infinity;
  for (let num of set) {
    res = Math.min(res, check(num));
  }
  return res;
}

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

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


You are given an array $$$a$$$ of $$$n$$$ integers, where $$$n$$$ is odd. You can make the following operation with it:  Choose one of the elements of the array (for example $$$a_i$$$) and increase it by $$$1$$$ (that is, replace it with $$$a_i + 1$$$). You want to make the median of the array the largest possible using at most $$$k$$$ operations.The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $$$[1, 5, 2, 3, 5]$$$ is $$$3$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n$$$ is odd, $$$1 \le k \le 10^9$$$) — the number of elements in the array and the largest number of operations you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print a single integer — the maximum possible median after the operations.

NoteIn the first example, you can increase the second element twice. Than array will be $$$[1, 5, 5]$$$ and it's median is $$$5$$$.In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is $$$3$$$.In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be $$$[5, 1, 2, 5, 3, 5, 5]$$$ and the median will be $$$5$$$.

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, k, nArr;
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    k = parseInt(resOne[1]);
  }
  if (lineCount === 1) {
    nArr = line.trim().split(' ').map((item) => parseInt(item));
    console.log(maximumMedian(n, k, nArr));
    rl.close();
  }
  lineCount ++;
});

function maximumMedian(n, k, nArr) {
  if (n === 1) {
    return nArr[0] += k;
  }
  let sort = nArr.sort((a, b) => {
    if ( a < b) {
      return -1;
    }
    if ( a > b) {
      return 1;
    }
    return 0;
  });
  let rightArr = sort.splice(((n - 1)/2));
  let len = rightArr.length;
  let result = rightArr[0];
  let minIndex = rightArr.lastIndexOf(result);
  let tempIndex = minIndex;
  if ( k <= minIndex) {
    return result;
  }

  let count = k;
  while (count) {
    if (tempIndex + 1 === len) {
      // 全加满了，数组中数据完全相同
      // count 剩余的次数
      let lastCount = Math.floor(count / len);
      result += lastCount;
      break;
    } else {
      let resultNext = rightArr[tempIndex + 1];
      let gap = resultNext - result;
      if (gap > 0) {
        // 不一定能加完，看count还剩多少
        let curCount = gap * (tempIndex + 1)
        if (count < curCount) {
          // 剩余次数不够每个+gap 算出能加多少次
          result += Math.floor(count / (tempIndex + 1));
          break;
        }
        result += gap;
        count -= curCount;
      }
      if (count < 0) {
        // count 会<0
        break;
      }
      // 数组的下一个
      tempIndex += 1;
    }
  }
  return result;
}

var nm = readline().split(' ').map(item => +item);
var arr = readline().split(' ').map(item => +item).sort((a, b) => a - b);
var m = ~~(arr.length / 2);
var k = m + 1;

while(nm[1] > 0) {
  if(k === arr.length) {
    d = k - m;
    arr[m] += ~~(nm[1] / d);
    break;
  }

  if(arr[m] < arr[k]) {
    var val = arr[k] - arr[m];
    var d = k - m;
    var c = val * d;
    if(c < nm[1]) {
      arr[m] += val;
      nm[1] -= c;
    } else {
      arr[m] += ~~(nm[1] / d);
      break;
    }
  } else {
    k++;
  }
}

print(arr[m]);

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {"use strict";
    // TODO
    var input = rdArN();
    var n = input[0];
    var k = input[1];
    var A = rdArN();

    A.sortLt();
    var mid = Math.floor(n/2);
    A = A.slice(mid);

    var len = n - mid;
    var step = 1;
    var lastHeight = A[0];
    //pr(A);
    //pr(len, step, lastHeight)
    while (true) {
        if (step >= len) {
            break;
        }
        var nextHeight = A[step];
        var needToAdd = step*(nextHeight - lastHeight)
        //pr(needToAdd);
        if (needToAdd <= k) {
            k -= needToAdd;
            lastHeight = nextHeight;
            ++step;
        } else {
            break;
        }
    }
    lastHeight += Math.floor(k/step);
    wr(lastHeight);
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
getPrimeFactors=function(n){var primes=getPrimes(Math.floor(Math.sqrt(n))),last=primes.push(n)-1,factors=[],i,p;for(i=0,p=primes[0];primes[last]>1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});

main();
return OUTPUT;
})();

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, k, nArr;
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    k = parseInt(resOne[1]);
  }
  if (lineCount === 1) {
    nArr = line.trim().split(' ').map((item) => parseInt(item));
    console.log(maximumMedian(n, k, nArr));
    rl.close();
  }
  lineCount ++
})

function maximumMedian(n, k, nArr) {
  if (n === 1) {
    return nArr[0] += k;
  }
  let sort = nArr.sort((a, b) => {
    if ( a < b) {
      return -1
    }
    if ( a > b) {
      return 1
    }
    return 0
  });
  let rightArr = sort.splice(((n - 1)/2));
  let len = rightArr.length;
  let result = rightArr[0];
  let minIndex = rightArr.lastIndexOf(result);
  let tempIndex = minIndex
  if ( k <= minIndex) {
    return result;
  }
  let loseCount = 0;
  let lastCount = 0
  for (let i = 0 ; i < k + loseCount; i +=(tempIndex + 1)) {
    if (tempIndex === (len - 1)) {
      if (i + tempIndex + 1 <= k + loseCount) {
        lastCount = Math.floor((k + loseCount - i) / len);
        break;
      }
    } else {
      let resultNext = rightArr[tempIndex + 1];
      if (result < resultNext + 1) {
        result += 1;
      } else {
        loseCount += tempIndex;
        tempIndex += 1;
      }
    }
  }
  if (lastCount) {
    result += lastCount
  }

  return result;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0;
let n;
let k;
let nArr;
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    k = parseInt(resOne[1]);
  }
  if (lineCount === 1) {
    nArr = line.trim().split(' ').map((item) => parseInt(item));
    console.log(maximumMedian(n, k, nArr));
    rl.close();
  }
  lineCount ++
})

function maximumMedian(n, k, nArr) {
  if (n === 1) {
    return nArr[0] += k;
  }
  const sortFun = (a, b) => {
    if ( a < b) {
      return -1
    }
    if ( a > b) {
      return 1
    }
    return 0
  }

  let sort = nArr.sort(sortFun);
  let medianAndRightArr = sort.splice(((n - 1)/2));

  let len = medianAndRightArr.length;
  let result = medianAndRightArr[0];

  let minIndex = medianAndRightArr.lastIndexOf(result);
  let tempIndex = minIndex

  if ( k <= minIndex) {
    return result;
  }

  let loseCount = 0;
  for (let i = 0 ; i < k + loseCount; i +=(tempIndex + 1)) {
    if (tempIndex === (len - 1)) {
      if (i + tempIndex + 1 < k) {
        // 最后一个，扫过一遍，值都相等了
        result += 1;
      }
    } else {
      let resultNext = medianAndRightArr[tempIndex + 1];
      if (result < resultNext + 1) {
        // 当前值比下一个值小，则在当前值上一直增加
        result += 1;
      } else {
        tempIndex += 1;
        // 丢了一段
        loseCount += tempIndex;
      }
    }
  }
  return result;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, k, nArr;
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    k = parseInt(resOne[1]);
  }
  if (lineCount === 1) {
    nArr = line.trim().split(' ').map((item) => parseInt(item));
    console.log(maximumMedian(n, k, nArr));
    rl.close();
  }
  lineCount ++
})

function maximumMedian(n, k, nArr) {
  if (n === 1) {
    return nArr[0] += k;
  }
  let sort = nArr.sort((a, b) => {
    if ( a < b) {
      return -1
    }
    if ( a > b) {
      return 1
    }
    return 0
  });
  let rightArr = sort.splice(((n - 1)/2));
  let len = rightArr.length;
  let result = rightArr[0];
  let minIndex = rightArr.lastIndexOf(result);
  let tempIndex = minIndex
  if ( k <= minIndex) {
    return result;
  }
  let loseCount = 0;
  let lastCount = 0
  for (let i = 0 ; i < k + loseCount; i +=(tempIndex + 1)) {
    if (tempIndex === (len - 1)) {
      if (i + tempIndex + 1 <= k + loseCount) {
        lastCount = Math.ceil((k + loseCount - i) / len);
        break;
      }
    } else {
      let resultNext = rightArr[tempIndex + 1];
      if (result < resultNext + 1) {
        result += 1;
      } else {
        loseCount += tempIndex;
        tempIndex += 1;
      }
    }
  }
  if (lastCount) {
    result += lastCount
  }

  return result;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, k, nArr;
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    k = parseInt(resOne[1]);
  }
  if (lineCount === 1) {
    nArr = line.trim().split(' ').map((item) => parseInt(item));
    console.log(maximumMedian(n, k, nArr));
    rl.close();
  }
  lineCount ++;
});

function maximumMedian(n, k, nArr) {
  if (n === 1) {
    return nArr[0] += k;
  }
  let sort = nArr.sort((a, b) => {
    if ( a < b) {
      return -1;
    }
    if ( a > b) {
      return 1;
    }
    return 0;
  });
  let rightArr = sort.splice(((n - 1)/2));
  let len = rightArr.length;
  let result = rightArr[0];
  let minIndex = rightArr.lastIndexOf(result);
  let tempIndex = minIndex;
  if ( k <= minIndex) {
    return result;
  }

  let count = k;
  while (count) {
    if (tempIndex + 1 === len) {
      // 全加满了，数组中数据完全相同
      // count 剩余的次数
      let lastCount = Math.floor(count / len);
      result += lastCount;
      count = 0;
      break;
    } else {
      let resultNext = rightArr[tempIndex + 1];
      let gap = resultNext - result;
      if (gap > 0) {
        result += gap;
        count -= gap * (tempIndex + 1);
      }
      tempIndex += 1;
    }
  }
  return result;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0;
let n;
let k;
let nArr;
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    k = parseInt(resOne[1]);
  }
  if (lineCount === 1) {
    nArr = line.trim().split(' ').map((item) => parseInt(item));
    console.log(maximumMedian(n, k, nArr));
    rl.close();
  }
  lineCount ++
})

function maximumMedian(n, k, nArr) {
  if (n === 1) {
    return nArr[0] += k;
  }
  const sortFun = (a, b) => {
    if ( a < b) {
      return -1
    }
    if ( a > b) {
      return 1
    }
    return 0
  }

  let sort = nArr.sort(sortFun);
  let medianAndRightArr = sort.splice(((n - 1)/2));

  let len = medianAndRightArr.length;
  let result = medianAndRightArr[0];

  let minIndex = medianAndRightArr.lastIndexOf(result);
  let tempIndex = minIndex

  if ( k <= minIndex) {
    return result;
  }

  let loseCount = 0;
  for (let i = 0 ; i < k + loseCount; i +=(tempIndex + 1)) {
    if (tempIndex === (len - 1)) {
      if (i + tempIndex + 1 < k) {
        // 最后一个，扫过一遍，值都相等了
        result += 1;
      }
    } else {
      let resultNext = medianAndRightArr[tempIndex + 1];
      if (result < resultNext + 1) {
        // 当前值比下一个值小，则在当前值上一直增加
        result += 1;
      } else {
        // 丢了一次加一
        loseCount += 1;
        tempIndex += 1;
      }
    }
  }
  return result;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0
let n
let k
let nArr
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ')
    n = parseInt(resOne[0])
    k = parseInt(resOne[1])
  }
  if (lineCount === 1) {
    nArr = line.trim().split(' ').map((item) => parseInt(item))
    console.log(maximumMedian(n, k, nArr))
    rl.close()
  }
  lineCount ++
})

function maximumMedian(n, k, nArr) {
  const sortFun = (a, b) => {
    if ( a < b) {
      return -1
    }
    if ( a > b) {
      return 1
    }
    return 0
  }

  let count = 0

  let sort = nArr.sort(sortFun)
  let medianAndRightArr = sort.splice(((n - 1)/2))

  function addOne(arr) {
    let sortRes = arr.sort(sortFun)
    if (count === k) {
      return sortRes[0]
    }
    count++
    if (sortRes[0] <= sortRes[1]) {
      sortRes[0] += 1
    } else {
      sortRes[1] += 1
    }
    return addOne(sortRes)
  }
  return addOne(medianAndRightArr)
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0;
let n;
let k;
let nArr;
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    k = parseInt(resOne[1]);
  }
  if (lineCount === 1) {
    nArr = line.trim().split(' ').map((item) => parseInt(item));
    console.log(maximumMedian(n, k, nArr));
    rl.close();
  }
  lineCount ++
})

function maximumMedian(n, k, nArr) {
  if (n === 1) {
    return nArr[0] += k;
  }
  const sortFun = (a, b) => {
    if ( a < b) {
      return -1
    }
    if ( a > b) {
      return 1
    }
    return 0
  }

  let sort = nArr.sort(sortFun);
  let medianAndRightArr = sort.splice(((n - 1)/2));

  let len = medianAndRightArr.length;
  let result = medianAndRightArr[0];

  let minIndex = medianAndRightArr.lastIndexOf(result);
  let tempIndex = minIndex

  if ( k <= minIndex) {
    return result;
  }

  for (let i = 0 ; i < k; i +=(tempIndex + 1)) {
    if (tempIndex === (len - 1)) {
      if (i + tempIndex + 1 <= k) {
        // 最后一个，扫过一遍，值都相等了
        result += 1;
      }
    } else {
      let resultNext = medianAndRightArr[tempIndex + 1];
      if (result < resultNext + 1) {
        result += 1;
      } else {
        tempIndex += 1;
      }
    }
  }

  return result;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0;
let n;
let k;
let nArr;
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    k = parseInt(resOne[1]);
  }
  if (lineCount === 1) {
    nArr = line.trim().split(' ').map((item) => parseInt(item));
    console.log(maximumMedian(n, k, nArr));
    rl.close();
  }
  lineCount ++
})

function maximumMedian(n, k, nArr) {
  if (n === 1) {
    return nArr[0] += k;
  }
  const sortFun = (a, b) => {
    if ( a < b) {
      return -1
    }
    if ( a > b) {
      return 1
    }
    return 0
  }

  let sort = nArr.sort(sortFun);
  let medianAndRightArr = sort.splice(((n - 1)/2));

  let len = medianAndRightArr.length;
  let result = medianAndRightArr[0];

  let minIndex = medianAndRightArr.lastIndexOf(result);
  let tempIndex = minIndex

  if ( k <= minIndex) {
    return result;
  }

  let loseCount = 0;
  for (let i = 0 ; i < k + loseCount; i +=(tempIndex + 1)) {
    if (tempIndex === (len - 1)) {
      if (i + tempIndex + 1 < k + loseCount) {
        // 最后一个，扫过一遍，值都相等了
        result += 1;
      }
    } else {
      let resultNext = medianAndRightArr[tempIndex + 1];
      if (result < resultNext + 1) {
        // 当前值比下一个值小，则在当前值上一直增加
        result += 1;
      } else {
        // 丢了一段
        // TODO
        loseCount += tempIndex;
        tempIndex += 1;
      }
    }
  }
  return result;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0;
let n;
let k;
let nArr;
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    k = parseInt(resOne[1]);
  }
  if (lineCount === 1) {
    nArr = line.trim().split(' ').map((item) => parseInt(item));
    console.log(maximumMedian(n, k, nArr));
    rl.close();
  }
  lineCount ++
})

function maximumMedian(n, k, nArr) {
  if (n === 1) {
    return nArr[0] += k;
  }
  const sortFun = (a, b) => {
    if ( a < b) {
      return -1
    }
    if ( a > b) {
      return 1
    }
    return 0
  }

  let sort = nArr.sort(sortFun);
  let medianAndRightArr = sort.splice(((n - 1)/2));

  let len = medianAndRightArr.length;
  let result = medianAndRightArr[0];

  let minIndex = medianAndRightArr.lastIndexOf(result);
  let tempIndex = minIndex

  if ( k <= minIndex) {
    return result;
  }

  let loseCount = 0;
  for (let i = 0 ; i < k + loseCount; i +=(tempIndex + 1)) {
    if (tempIndex === (len - 1)) {
      if (i + tempIndex + 1 < k) {
        // 最后一个，扫过一遍，值都相等了
        result += 1;
      }
    } else {
      let resultNext = medianAndRightArr[tempIndex + 1];
      if (result < resultNext + 1) {
        // 当前值比下一个值小，则在当前值上一直增加
        result += 1;
      } else {
        // 丢了一段
        loseCount += tempIndex;
        tempIndex += 1;
      }
    }
  }
  return result;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0;
let n;
let k;
let nArr;
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    k = parseInt(resOne[1]);
  }
  if (lineCount === 1) {
    nArr = line.trim().split(' ').map((item) => parseInt(item));
    console.log(maximumMedian(n, k, nArr));
    rl.close();
  }
  lineCount ++
})

function maximumMedian(n, k, nArr) {
  if (n === 1) {
    return nArr[0] += k;
  }
  const sortFun = (a, b) => {
    if ( a < b) {
      return -1
    }
    if ( a > b) {
      return 1
    }
    return 0
  }

  let sort = nArr.sort(sortFun);
  let medianAndRightArr = sort.splice(((n - 1)/2));

  let len = medianAndRightArr.length;
  let result = medianAndRightArr[0];

  let minIndex = medianAndRightArr.lastIndexOf(result);
  let tempIndex = minIndex

  if ( k <= minIndex) {
    return result;
  }

  for (let i = 0 ; i < k; i +=(tempIndex + 1)) {
    if (tempIndex === (len - 1)) {
      if (i + tempIndex + 1 < k) {
        // 最后一个，扫过一遍，值都相等了
        result += 1;
      }
    } else {
      let resultNext = medianAndRightArr[tempIndex + 1];
      if (result < resultNext + 1) {
        result += 1;
      } else {
        tempIndex += 1;
      }
    }
  }

  return result;
}

const readline = require('readline');
const process = require('process');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let lineCount = 0, n, k, nArr;
rl.on('line', function(line){
  if (lineCount === 0) {
    let resOne = line.trim().split(' ');
    n = parseInt(resOne[0]);
    k = parseInt(resOne[1]);
  }
  if (lineCount === 1) {
    nArr = line.trim().split(' ').map((item) => parseInt(item));
    console.log(maximumMedian(n, k, nArr));
    rl.close();
  }
  lineCount ++;
});

function maximumMedian(n, k, nArr) {
  if (n === 1) {
    return nArr[0] += k;
  }
  let sort = nArr.sort((a, b) => {
    if ( a < b) {
      return -1;
    }
    if ( a > b) {
      return 1;
    }
    return 0;
  });
  let rightArr = sort.splice(((n - 1)/2));
  let len = rightArr.length;
  let result = rightArr[0];
  let minIndex = rightArr.lastIndexOf(result);
  let tempIndex = minIndex;
  if ( k <= minIndex) {
    return result;
  }

  let count = k;
  while (count) {
    if (tempIndex + 1 === len) {
      // 全加满了，数组中数据完全相同
      // count 剩余的次数
      let lastCount = Math.floor(count / len);
      result += lastCount;
      break;
    } else {
      let resultNext = rightArr[tempIndex + 1];
      let gap = resultNext - result;
      if (gap > 0) {
        result += gap;
        count -= gap * (tempIndex + 1);
      }
      if (count < 0) {
        // count 会<0
        break;
      }
      // 数组的下一个
      tempIndex += 1;
    }
  }
  return result;
}

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {"use strict";
    // TODO
    var input = rdArN();
    var n = input[0];
    var k = input[1];
    var A = rdArN();

    A.sortLt();
    var mid = Math.floor(n/2);
    A = A.slice(mid);

    var len = n - mid;
    var step = 1;
    var lastHeight = A[0];
    //pr(A);
    //pr(len, step, lastHeight)
    while (true) {
        if (step >= len) {
            break;
        }
        var nextHeight = A[step];
        var needToAdd = step*(nextHeight - lastHeight)
        //pr(needToAdd);
        if (needToAdd <= k) {
            k -= needToAdd;
            lastHeight = nextHeight;
            ++step;
        } else {
            break;
        }
    }
    lastHeight += Math.floor(k/len);
    wr(lastHeight);
};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const
rdS=readline,
rdN=()=>+rdS(),
rdArS=()=>rdS().split(' '),
rdArN=()=>rdArS().map(v=>+v),
wr=write,
pr=print,
prAr=(a)=>pr(...a),
prOb=(o)=>pr(JSON.stringify(o,null,4)),
crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);},
getPrimes=function(n){var sieve=crAr(n+1,true),primes=[],i,j;for(i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;},
getPrimeFactors=function(n){var primes=getPrimes(Math.floor(Math.sqrt(n))),last=primes.push(n)-1,factors=[],i,p;for(i=0,p=primes[0];primes[last]>1;){if(primes[last]%p===0){primes[last]/=p;factors.push(p);}else{p=primes[++i];}}return factors;},
defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{value:v,writable:true,enumerable:false,configurable:true});
defineProperty(Array.prototype,'sortLt',function(){return this.sort((a,b)=>a-b);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort((a,b)=>b-a);});

main();
return OUTPUT;
})();


International Women's Day is coming soon! Polycarp is preparing for the holiday.There are $$$n$$$ candy boxes in the shop for sale. The $$$i$$$-th box contains $$$d_i$$$ candies.Polycarp wants to prepare the maximum number of gifts for $$$k$$$ girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by $$$k$$$. In other words, two boxes $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) can be combined as a gift if $$$d_i + d_j$$$ is divisible by $$$k$$$.How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 100$$$) — the number the boxes and the number the girls. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$), where $$$d_i$$$ is the number of candies in the $$$i$$$-th box.

Print one integer — the maximum number of the boxes Polycarp can give as gifts.

NoteIn the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(2, 3)$$$;  $$$(5, 6)$$$;  $$$(1, 4)$$$. So the answer is $$$6$$$.In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(6, 8)$$$;  $$$(2, 3)$$$;  $$$(1, 4)$$$;  $$$(5, 7)$$$. So the answer is $$$8$$$.In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(1, 2)$$$;  $$$(6, 7)$$$. So the answer is $$$4$$$.

var inp = readline().split(' ').map(el => parseInt(el));
n = inp[0];
k = inp[1];

var freq = new Array(k).fill(0);
readline().split(' ').map(el => {
	var rem = parseInt(el) % k;
	freq[rem] += 1;
});

var ans = 0;

if(k === 1){
	ans = Math.floor(n / 2) * 2;
}
else{
	ans += Math.floor(freq[0] / 2);
	if(k % 2 == 0){
		ans += Math.floor(freq[k / 2] / 2);
	}
	else{
		ans += Math.min(freq[Math.floor(k / 2)], freq[k - Math.floor(k / 2)]);
	}
	for(var i = 1; i < Math.floor(k / 2); i++){
		ans += Math.min(freq[i], freq[k - i]);
	}
	ans *= 2;
}
print(ans);

var inp = readline().split(' ').map(el => parseInt(el));
n = inp[0];
k = inp[1];

var freq = new Array(k).fill(0);
readline().split(' ').map(el => {
	var rem = parseInt(el) % k;
	freq[rem] += 1;
});

var ans = 0;
ans += Math.floor(freq[0] / 2);
if(k % 2 == 0){
	ans += Math.floor(freq[k / 2] / 2);
}
else{
	ans += Math.min(freq[Math.floor(k / 2)], freq[k - Math.floor(k / 2)]);
}
for(var i = 1; i < Math.floor(k / 2); i++){
	ans += Math.min(freq[i], freq[k - i]);
}
ans *= 2;

print(ans);


One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors.There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least ai rating units as a present.The X site is administered by very creative and thrifty people. On the one hand, they want to give distinct ratings and on the other hand, the total sum of the ratings in the present must be as small as possible.Help site X cope with the challenging task of rating distribution. Find the optimal distribution.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of users on the site. The next line contains integer sequence a1, a2, ..., an (1 ≤ ai ≤ 109).

Print a sequence of integers b1, b2, ..., bn. Number bi means that user i gets bi of rating as a present. The printed sequence must meet the problem conditions.  If there are multiple optimal solutions, print any of them.

var n = parseInt( readline() );
var b = readline().split(' ').map(function(v, i){
	return {
		v: parseInt(v),
		i: i
	};
});

b.sort(function(a,b){return a.v===b.v?0:( a.v>b.v?1:-1 );});

var ret = [];
var h = 0;
for(var i=0;i<n;i++){
	var bi = b[i];
	if(bi.v <= h){
		ret[ bi.i ] = ++h;
	}else{
		ret[ bi.i ] = h = bi.v;
	}

}
print(ret.join(' '));

;(function() {

	var n = +readline(),
		b = [],
		a = readline().split(' ').map(function (e, i) { b[i] = i; return +e; });

	b.sort(function(x,y){ return a[x] - a[y]; });

	for (i = 1 ; i < n ; ++i)
		if (a[b[i]] <= a[b[i-1]])
			a[b[i]] = a[b[i-1]] + 1;

	print(a.join(' '));

}).call(this);

readline();
var numbers = readline().split(" ").map(x => ({ w: parseInt(x) }));
var sorted = numbers.slice().sort((x, y) => x.w - y.w);
var c = 0;
sorted.forEach(x => {
	if(c<x.w) c=x.w;
	x.r=c;
	c++;
});
print(numbers.map(x => x.r).join(" "));

(function() {
    var n = parseInt(readline());
    var a = readline().split(' ');
    var i, id = [];
    for(i = 0 ; i < n ; ++i ){
        a[i] = parseInt(a[i]);
        id[i] = i;
    }
    id.sort(function(x,y){
        return a[x]-a[y];
    })
    for(i = 1 ; i < n ; ++i){
        if ( a[id[i]] <= a[id[i-1]] ){
            a[id[i]] = a[id[i-1]] + 1;
        }
    }
    print(a.join(' '));
})();

function F(a, b, n){
	var arr = [];
	arr[0] = a;
	arr[1] = b;
	for( var i=2; i<n; i++){
		arr[i] = arr[i-1]+arr[i-2];
	}
	return arr[n-1];
}

function S(c, n){
	var ret = [];
	while(n--){
		ret.push(c);
	}
	return ret.join('');
}
var line = readline().split(' ').map(function(v){
	return parseInt(v);
});
var k=line[0],
x=line[1],
n=line[2],
m=line[3];
if(x==0){
	print(S('A', n));
	print(S('A'), m);
}else if(x==1){
	print(S('A', n));
	print(S('C', m));
}else if(n%2===m%2){
	if(n%2){
		if(F( (n+1)/2, (m-1)/2, k)==x){
			print( S('AC', (n-1)/2)+'C' );
			print( 'C'+S('AC', (m-1)/2) );
		}else{
			print( 'Happy new year!' );
		}
	}else{
		if(F( n/2, m/2, k)==x){
			print( S('AC', n/2) );
			print( S('AC', m/2) );
		}else{
			print( 'Happy new year!' );
		}
	}

}else{
	print('Happy new year!')
}

;(function () {

	var n = +readline(),
		t = {},
		a = readline().split(' ').map(function (e) {
			e = parseInt(e);
			if (t.hasOwnProperty(e)) t[e]++;
			else t[e] = 1;
			return e;
		});

	for (var i = 0; i < n; i++) a[i] += --t[a[i]];

	print(a.join(' '));

}).call(this);

;(function () {

	readline();

	print(readline().split(' ').map(Number).map(function (e, i, a) {
		while ((t = a.lastIndexOf(e)) !== -1 && t !== i) e++;
		return e;
	}).join(' '));

}).call(this);

(function() {
    var n = parseInt(readline());
    var a = readline().split(' ');
    var i, id = [];
    for(i = 0 ; i < n ; ++i ){
        a[i] = parseInt(a[i]);
        id[i] = i;
    }
    id.sort(function(x,y){
        return a[x]-a[y];
    })
    for(i = 1 ; i < n ; ++i){
        if ( a[id[i]] == a[id[i-1]] ){
            ++a[id[i]];
        }
    }
    print(a.join(' '));
})();


Vlad, like everyone else, loves to sleep very much.Every day Vlad has to do $$$n$$$ things, each at a certain time. For each of these things, he has an alarm clock set, the $$$i$$$-th of them is triggered on $$$h_i$$$ hours $$$m_i$$$ minutes every day ($$$0 \le h_i < 24, 0 \le m_i < 60$$$). Vlad uses the $$$24$$$-hour time format, so after $$$h=12, m=59$$$ comes $$$h=13, m=0$$$ and after $$$h=23, m=59$$$ comes $$$h=0, m=0$$$.This time Vlad went to bed at $$$H$$$ hours $$$M$$$ minutes ($$$0 \le H < 24, 0 \le M < 60$$$) and asks you to answer: how much he will be able to sleep until the next alarm clock.If any alarm clock rings at the time when he went to bed, then he will sleep for a period of time of length $$$0$$$.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the test. The first line of the case contains three integers $$$n$$$, $$$H$$$ and $$$M$$$ ($$$1 \le n \le 10, 0 \le H < 24, 0 \le M < 60$$$) — the number of alarms and the time Vlad went to bed. The following $$$n$$$ lines contain two numbers each $$$h_i$$$ and $$$m_i$$$ ($$$0 \le h_i < 24, 0 \le m_i < 60$$$) — the time of the $$$i$$$ alarm. It is acceptable that two or more alarms will trigger at the same time. Numbers describing time do not contain leading zeros.

Output $$$t$$$ lines, each containing the answer to the corresponding test case. As an answer, output two numbers  — the number of hours and minutes that Vlad will sleep, respectively. If any alarm clock rings at the time when he went to bed, the answer will be 0 0.

var t = parseInt(readline())
for(j = 0; j < t; j++){
var d = 2000;
var c = 2000;

var arr = readline()
arr = arr.split(' ')
var arr_min = []
var n = parseInt(arr[0])
var h = parseInt(arr[1])
var m = parseInt(arr[2])
var start = h * 60 + m

  for(var i = 0; i < n; i++){
    var sleep = readline();
    sleep = sleep.split(' ')
    var H = parseInt(sleep[0])
    var M = parseInt(sleep[1])
    var min = (H * 60) + M
    if(min >= start){
      d = Math.min(d, min)
    }
      c = Math.min(c,min)
  }

  if(d !== 2000){
    d = d - start
  print(parseInt(d / 60), d % 60 )
  }else{
    c = (1440 - start)  + c
    print(parseInt(c / 60), c % 60 )
  }
}

var t = readline();
for(var i=0;i<t;i++){
    var nhm = readline().split(' ').map(x=>parseInt(x));
    var n=nhm[0],h=nhm[1],m=nhm[2];
    var x=h*60+m;
    var ans=1000000;
    for(var j=0;j<n;j++){
        var h1m1 = readline().split(' ').map(x=>parseInt(x));
        var h1=h1m1[0],m1=h1m1[1];
        if(x<=h1*60+m1){
           ans=Math.min(ans,h1*60+m1-x);
        }
        else{
            ans=Math.min(ans,24*60 + (h1*60+m1) - x)
        }
    }
    print(Math.floor(ans/60) , ans- 60*Math.floor(ans/60));
}

var tests = parseInt(readline());
    var n, h, m;
    var alarms;
    for (var t=0; t < tests; t++) {
        var nhm = readline().split(' ').map(x=>parseInt(x));
        n = nhm[0];
        h = nhm[1];
        m = nhm[2];
        alarms = [];
        for (var i = 0; i < n; i++) {
            var a = readline().split(' ').map(x=>parseInt(x));
            alarms.push(a[0] * 60 + a[1]);
        }
        var sleep = h * 60 + m;
        var min = 24*60;
        for (var i = 0; i < n; i++) {
            var diff = alarms[i] - sleep;
            if ( diff < 0 ) {
                diff += 24*60;
            }
            if (diff < min) {
                min = diff;
            }
        }
        var hour = Math.floor(min/60);
        var minute = min - hour*60;
        print(hour + ' ' + minute);
    }

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function calc(H, M, alarms) {
    // console.log(H)
    // console.log(M)
    // console.log(alarms)
    next_alarm(H, M, alarms)

}

function next_alarm(H, M, alarms) {
    let k = alarms.length
    let min = Number.MAX_SAFE_INTEGER
    for(let i = 0; i < k; i++) {
        let hour = alarms[i].h
        let minute = alarms[i].m
        var _diff = 0

        if (hour == H && minute == M) {
            console.log("0 0")
            return
        }

        if ((hour == H && minute > M) || (hour > H)) { // alarm later than in day
            _diff = Math.abs(new Date('2011/10/09 ' + hour + ':' + minute) -
            new Date('2011/10/09 ' + H+':'+M));
        } else {
            _diff = Math.abs(new Date('2011/10/10 ' + hour + ':' + minute) -
            new Date('2011/10/09 ' + H+':'+M));
        }

        if (_diff/1000 < min) {
            min = _diff/1000
        }

        // alarms[i].diff = _diff/1000
    }

    // console.log(alarms)

    let hour = (min/3600)|0
    let minute = (min%3600)/60

    console.log(hour + " " + minute)

}

function main() {
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
        const n_h_m = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
        const n = n_h_m[0]
        const H = n_h_m[1]
        const M = n_h_m[2]

        let alarms = []

        for(let i = 0; i < n; i ++) {
            const hm = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
            alarms.push({"h": hm[0], "m": hm[1]})
        }

        calc(H, M, alarms)

    }

    // ws.end();
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '', currentLine = 0;
process.stdin.on('data', inputStdin => { inputString += inputStdin; });
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => string.trim());
    main();
});
function readLine() {
    return inputString[currentLine++];
}
function main(){
  const t = +readLine();

  for(let j = 0;j<t;j++){
    const a = readLine().split(' ').map(p=> +p)
    const N = a[0];
    const H = a[1];
    const M = a[2];

    const Tot = H*60 + M;

    let ans = 24000;

    for(let i = 0;i<N;i++){
      let x = readLine().split(' ').map(p => +p);

      let h = x[0];
      let m = x[1];

      let time = h*60 + m;

      if(time<Tot){
        ans = Math.min(ans,24*60-Tot+time);
      }else{
        ans = Math.min(ans, time-Tot);
      }

    }

    console.log(Math.floor(ans/60),ans%60)
  }
}

function solve() {
  const [n, H, M] = cl().split(' ').map((item) => Number(item));
  let now = H * 60 + M;

  let res = Infinity;
  for (let i = 0; i < n; i++) {
    const [h, m] = cl().split(' ').map((item) => Number(item));
    let diff = h * 60 + m - now;
    if (diff < 0) diff += 1440;
    res = Math.min(res, diff);
  }

  co(`${res / 60 | 0} ${res % 60}`);
}

function Solution() {
  let n = Number(cl());
  while (n--) solve();
}

let i = 0;
const lines = []

function cl() { return lines[i++] }
function co(str) { console.log(str)}
const readline = require('readline')
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
rl.on('line', (input) => lines.push(input));
rl.on('close', Solution);

function solve() {
  const [n, H, M] = cl().split(' ').map((item) => Number(item));
  let now = H * 60 + M;

  const times = [];
  for (let i = 0; i < n; i++) {
    const [h, m] = cl().split(' ').map((item) => Number(item));
    times[i] = h * 60 + m;
  }

  times.sort((x, y) => x - y);

  if (now > times[n - 1]) now -= 60 * 24;

  for (let i = 0; i < n; i++) {
    if (times[i] > now) {
      times[i] -= now;
      return co(`${times[i] / 60 | 0} ${times[i] % 60}`);
    }
    if (times[i] === now) return co('0 0');
  }
}

function Solution() {
  let n = Number(cl());
  while (n--) solve();
}

let i = 0;
const lines = []

function cl() { return lines[i++] }
function co(str) { console.log(str)}
const { time } = require('console');
const readline = require('readline')
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
rl.on('line', (input) => lines.push(input));
rl.on('close', Solution);

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '', currentLine = 0;
process.stdin.on('data', inputStdin => { inputString += inputStdin; });
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => string.trim());
    main();
});
function readLine() {
    return inputString[currentLine++];
}

function main() {
    const t = +readLine();
    for(let i = 0; i < t; i++){
        const a = readLine().split(' ').map(p => +p);
        const n = a[0];
        const H = a[1];
        const M = a[2];
        let arr = [], aux;
        for(let j = 0; j < n; j++){
            aux = readLine().split(' ').map(p => +p);
            arr.push(aux);
        }
        let result = myFunc(H, M, arr);
        console.log(...result);
    }
}

function myFunc(H, M, arr){

    let c = (60*H + M);
    let min = Infinity;
    let min_val = Infinity;
    let aux, item;

    for(let i = 0; i < arr.length; i++){
        item = arr[i];
        aux = (60*item[0] + item[1]);
        if(aux < min_val){
            min_val = aux;
        }
        if(aux >= c && aux < min){
            min = aux;
        }
    }

    if(min == Infinity){
        min_val = 1440 - c + min_val;
       return [parseInt(min_val/60), min_val%60];
    }
    min = min - c;
    return [parseInt(min/60), min%60];

}

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

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];
solve = () => {
    const t = parseInt(readline());
    for (let i = 0; i < t; i++) {
        var min = 24 * 60;
        var minI;
        var a = readline().split(" ").map(Number);
        var MinS = a[1] * 60 + a[2];
        for (let j = 0; j < a[0]; j++) {
            var b = readline().split(" ").map(Number);
            var minB = b[0] * 60 + b[1];
            if (minB < MinS) {
                minI = minB - MinS + 24 * 60;
            } else {
                minI = minB - MinS;
            }
            if (minI < min) {
                min = minI
            }
        }
        console.log((parseInt(min / 60)) + ' ' + (min % 60));
    }

}

// cls; cat .\input.txt | node .\script.js
// codium --diff file1.js file2.js
'use strict';
let data = ''; // raw
let inputs = ''; // iterator
function read() { return inputs.next().value.trim(); };

async function solve() {
    const day = 24 * 60
    let [n, H, M] = (await read()).split(' ').map(Number)
    let current_day_time = H * 60 + M

    let n_list = []
    for (let i = 0; i < n; i++) {
        const [h, m] = (await read()).split(' ').map(Number)
        n_list.push(h * 60 + m)
    }

    let overlap = day % current_day_time

    let intervals = n_list
        .map(e => {
            const interval = e - current_day_time
            if (interval < 0) {
                let v = day - current_day_time + e
                return v
            }
            if (interval > 0) {
                return interval
            }
            if (interval == 0) {
                return 0
            }
        })

    let result = Math.min(...intervals)
    return `${Math.floor(result / 60)} ${result % 60}`
}

async function main() {
    let tasks_amount = parseInt(await read())
    for (let i = 0; i < tasks_amount; i++) {
        let result = await solve()
        console.log(result)
    }
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => data += input);
process.stdin.on('end', async () => {
    let splitted = data.split('\r\n')
    inputs = await splitted.values();
    await main();
});

'use strict';

function solve(n, h, m, a) {
  a.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);
  for (let [x, y] of a) {
    if (x === h && y >= m) {
      return `0 ${y - m}`;
    }
    if (x > h) {
      const t = x * 60 + y - (h * 60 + m);
      return `${Math.floor(t / 60)} ${t % 60}`;
    }
  }
  const [x, y] = a[0];
  const t = 1440 + x * 60 + y - (h * 60 + m);
  return `${Math.floor(t / 60)} ${t % 60}`;
}

async function main(r) {
  const rns = async () => {
    return (await r()).split(' ').filter(s => s !== '').map(Number);
  };
  try {
    let t = Number(await r());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const [n, m, k] = await rns();
      const a = [];
      let tmp = n;
      while (tmp--) {
        a.push(await rns());
      }
      res[i] = solve(n, m, k, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

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

'use strict';

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++) {
        const [n, H, M] = readline().split(' ').map(Number);
        let min = 24*60;
        for (let i = 0; i < n; i++) {
            const [h, m] = readline().split(' ').map(Number);
            let hDiff = h - H;
            let mDiff = m - M;
            if (mDiff < 0) {
                mDiff += 60;
                hDiff--;
            }
            if (hDiff < 0) {
                hDiff += 24;
            }
            const time = hDiff * 60 + mDiff;
            if (time < min) {
                min = time;
            }
        }
        const hrs = Math.floor(min / 60);
        const mins = min % 60;
        output(hrs + ' ' + mins);
    }
}

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

function solve(n, H, M, arr) {
    const sorted = arr.map(([h, m]) => h * 60 + m)
        .sort((a, b) => a - b)
    const now = H * 60 + M
    let y = sorted[0] + 24 * 60 - now
    for (let x of sorted) {
        if (x >= now) {
            y = x - now
            break
        }
    }
    return [Math.floor(y / 60), y % 60].join(' ')
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var H = nextInt();
		var M = nextInt();
		var set = new Set();
		for(var i = 0; i < N; i++){
			set.add(nextInt() * 60 + nextInt());
		}

		var now = H * 60 + M;
		var output = 0;
		while(true){
			if(set.has(now)){
				break;
			}
			now++;
			output++;
			now %= 1440;
		}
		var ah = Math.floor(output / 60);
		var am = output % 60;
		myout(ah + " " + am);
	}
}

var t = parseInt(readline())
for(j = 0; j < t; j++){
var d = 2000;
var c = 2000;

var arr = readline()
arr = arr.split(' ')
var arr_min = []
var n = parseInt(arr[0])
var h = parseInt(arr[1])
var m = parseInt(arr[2])
var start = h * 60 + m

  for(var i = 0; i < n; i++){
    var sleep = readline();
    sleep = sleep.split(' ')
    var H = parseInt(sleep[0])
    var M = parseInt(sleep[1])
    var min = (H * 60) + M
    if(min >= start){
      d = Math.min(d, min)
    }else{
      c = Math.min(d,min)
    }
  }

  if(d !== 2000){
    d = d - start
  print(parseInt(d / 60), d % 60 )
  }else{
    c = (1440 - start)  + c
    print(parseInt(c / 60), c % 60 )
  }
}

var t = parseInt(readline())

for(j = 0; j < t; j++){

var arr = readline()
arr = arr.split(' ')
var arr_min = []
var n = parseInt(arr[0])
var h = parseInt(arr[1])
var m = parseInt(arr[2])
var start = h * 60 + m

for(var i = 0; i < n; i++){
  var sleep = readline();
  sleep = sleep.split(' ')
  var H = parseInt(sleep[0])
  var M = parseInt(sleep[1])
  var min = (H * 60) + M
  arr_min.push(min)
}
arr_min.sort(function(a, b) {
  return a - b;
});

minn = 100000

for (var i = 0; i<n; i++){
    if (Math.abs(arr_min[i] - start) < minn){
        minn = arr_min[i]
    }
}

result =  minn - start

print(parseInt(result/60), parseInt(result%60))
}

var t = parseInt(readline())

for(j = 0; j < t; j++){

var arr = readline()
arr = arr.split(' ')
var arr_min = []
var n = parseInt(arr[0])
var h = parseInt(arr[1])
var m = parseInt(arr[2])
var start = h * 60 + m

for(var i = 0; i < n; i++){
  var sleep = readline();
  sleep = sleep.split(' ')
  var H = parseInt(sleep[0])
  var M = parseInt(sleep[1])
  var min = (H * 60) + M
  arr_min.push(min)
}
arr_min.sort(function(a, b) {
  return a - b;
});

if(start < arr_min[0]){
var s = Math.abs(start - arr_min[0])
print(parseInt(s / 60) ,parseInt(s % 60))

}
else if(start === arr_min[0]){
print(parseInt(0) ,parseInt(0))
}
else{
    var d = 1440 - start

    arr_min[0] = arr_min[0] + d
        start = 0 + arr_min[0]
        print(parseInt(start / 60) ,start % 60)
}

}

var t = parseInt(readline())

for(j = 0; j < t; j++){

var arr = readline()
arr = arr.split(' ')
var arr_min = []
var n = parseInt(arr[0])
var h = parseInt(arr[1])
var m = parseInt(arr[2])
var start = h * 60 + m

for(var i = 0; i < n; i++){
  var sleep = readline();
  sleep = sleep.split(' ')
  var H = parseInt(sleep[0])
  var M = parseInt(sleep[1])
  var min = (H * 60) + M
  arr_min.push(min)
}
arr_min.sort(function(a, b) {
  return a - b;
});

if(start < arr_min[0]){
var s = Math.abs(start - arr_min[0])
print(parseInt(s / 60) ,parseInt(s % 60))

}
else if(start === arr_min[0]){
print(parseInt(0) ,parseInt(0))
}
else{
    var d = 1440 - start
    arr_min[0] = arr_min[0] - d
        start = 0 + arr_min[0]
        print(parseInt(start / 60) ,start % 60)
}

}

var t = parseInt(readline())

for(j = 0; j < t; j++){

var arr = readline()
arr = arr.split(' ')
var arr_min = []
var n = parseInt(arr[0])
var h = parseInt(arr[1])
var m = parseInt(arr[2])
var start = h * 60 + m

for(var i = 0; i < n; i++){
  var sleep = readline();
  sleep = sleep.split(' ')
  var H = parseInt(sleep[0])
  var M = parseInt(sleep[1])
  var min = (H * 60) + M
  arr_min.push(min)
}
arr_min.sort(function(a, b) {
  return a - b;
});

if(start < arr_min[0]){
var s = Math.abs(start - arr_min[0])
print(parseInt(s / 60) ,parseInt(s % 60))
}else{
    var d = 1440 - start
    arr_min[0] = arr_min[0] - d
        start = 0 + arr_min[0]
        print(parseInt(start / 60) ,start % 60)
}

}

var t = parseInt(readline())

for(j = 0; j < t; j++){

var arr = readline()
arr = arr.split(' ')
var arr_min = []
var n = parseInt(arr[0])
var h = parseInt(arr[1])
var m = parseInt(arr[2])
var start = h * 60 + m

for(var i = 0; i < n; i++){
  var sleep = readline();
  sleep = sleep.split(' ')
  var H = parseInt(sleep[0])
  var M = parseInt(sleep[1])
  var min = (H * 60) + M
  arr_min.push(min)
}
arr_min.sort(function(a, b) {
  return a - b;
});

var s = Math.abs(start - arr_min[0])
print(parseInt(s / 60) ,parseInt(s % 60))
}

var t = parseInt(readline())

for(j = 0; j < t; j++){

var arr = readline()
arr = arr.split(' ')
var arr_min = []
var n = parseInt(arr[0])
var h = parseInt(arr[1])
var m = parseInt(arr[2])
var start = h * 60 + m

for(var i = 0; i < n; i++){
  var sleep = readline();
  sleep = sleep.split(' ')
  var H = parseInt(sleep[0])
  var M = parseInt(sleep[1])
  var min = (H * 60) + M
  arr_min.push(min)
}
arr_min.sort(function(a, b) {
  return a - b;
});

var s = Math.abs(start - arr_min[0])
print(parseInt(s / 60))
print(s % 60)
}

var t = readline();
for(var i=0;i<t;i++){
    var n = readline();
    var arr = readline().split(' ').map(x=>parseInt(x));
    var map={};
    var ans=0;
    for(var j=arr.length;j>=0;j--){
        if(map[arr[j]]){
            ans=j+1;
            break;
        }
        else{
            map[arr[j]]=1;
        }
    }
    print(ans);
}

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function calc(H, M, alarms) {
    // console.log(H)
    // console.log(M)
    // console.log(alarms)
    next_alarm(H, M, alarms)

}

function next_alarm(H, M, alarms) {
    let k = alarms.length
    let min = Number.MAX_SAFE_INTEGER
    for(let i = 0; i < k; i++) {
        let hour = alarms[i].h
        let minute = alarms[i].m
        var _diff = 0

        if (hour == H && minute == M) {
            console.log("0 0")
            return
        }

        if ((hour == H && minute >= M) || (hour > H)) { // alarm later than in day
            _diff = Math.abs(new Date('2011/10/09 ' + hour + ':' + minute) -
            new Date('2011/10/09 ' + H+':'+M));
        } else {
            _diff = Math.abs(new Date('2011/10/10 ' + hour + ':' + minute) -
            new Date('2011/10/09 ' + H+':'+M));
        }

        if (_diff/1000 < min) {
            min = _diff
        }

        alarms[i].diff = _diff/1000
    }

    // console.log(alarms)

    let hour = (min/1000/3600)|0
    let minute = ((min/1000)%3600)/60

    console.log(hour + " " + minute)

}

function main() {
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
        const n_h_m = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
        const n = n_h_m[0]
        const H = n_h_m[1]
        const M = n_h_m[2]

        let alarms = []

        for(let i = 0; i < n; i ++) {
            const hm = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
            alarms.push({"h": hm[0], "m": hm[1]})
        }

        calc(H, M, alarms)

    }

    // ws.end();
}

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function calc(H, M, alarms) {
    // console.log(H)
    // console.log(M)
    // console.log(alarms)
    next_alarm(H, M, alarms)

}

function next_alarm(H, M, alarms) {
    let k = alarms.length
    let min = Number.MAX_SAFE_INTEGER
    for(let i = 0; i < k; i++) {
        let hour = alarms[i].h
        let minute = alarms[i].m
        var _diff = 0

        if ((hour == H && minute >= M) || (hour > H)) { // alarm later than in day
            _diff = Math.abs(new Date('2011/10/09 ' + hour + ':' + minute) -
            new Date('2011/10/09 ' + H+':'+M));
        } else {
            _diff = Math.abs(new Date('2011/10/10 ' + hour + ':' + minute) -
            new Date('2011/10/09 ' + H+':'+M));
        }

        if (_diff/1000 < min) {
            min = _diff
        }

        alarms[i].diff = _diff/1000
    }

    // console.log(alarms)

    let hour = (min/1000/3600)|0
    let minute = ((min/1000)%3600)/60

    console.log(hour + " " + minute)

}

function main() {
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
        const n_h_m = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
        const n = n_h_m[0]
        const H = n_h_m[1]
        const M = n_h_m[2]

        let alarms = []

        for(let i = 0; i < n; i ++) {
            const hm = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
            alarms.push({"h": hm[0], "m": hm[1]})
        }

        calc(H, M, alarms)

    }

    // ws.end();
}

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function calc(H, M, alarms) {
    // console.log(H)
    // console.log(M)
    // console.log(alarms)
    next_alarm(H, M, alarms)

}

function next_alarm(H, M, alarms) {
    let k = alarms.length
    let min = Number.MAX_SAFE_INTEGER
    for(let i = 0; i < k; i++) {
        let hour = alarms[i].h
        let minute = alarms[i].m
        var _diff = 0

        if ((hour == H && minute >= M) || (hour > H)) { // alarm later than in day
            _diff = Math.abs(new Date('2011/10/09 ' + hour + ':' + minute) -
            new Date('2011/10/09 ' + H+':'+M));
        } else {
            _diff = Math.abs(new Date('2011/10/10 ' + hour + ':' + minute) -
            new Date('2011/10/09 ' + H+':'+M));
        }

        if (_diff/1000 < min) {
            min = _diff
        }

        alarms[i].diff = _diff/1000
    }

    console.log(alarms)

    let hour = (min/1000/3600)|0
    let minute = ((min/1000)%3600)/60

    console.log(hour + " " + minute)

}

function main() {
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
        const n_h_m = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
        const n = n_h_m[0]
        const H = n_h_m[1]
        const M = n_h_m[2]

        let alarms = []

        for(let i = 0; i < n; i ++) {
            const hm = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
            alarms.push({"h": hm[0], "m": hm[1]})
        }

        calc(H, M, alarms)

    }

    // ws.end();
}

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function calc(H, M, alarms) {
    // console.log(H)
    // console.log(M)
    // console.log(alarms)
    next_alarm(H, M, alarms)

}

function next_alarm(H, M, alarms) {
    let k = alarms.length
    let min = Number.MAX_SAFE_INTEGER
    for(let i = 0; i < k; i++) {
        let hour = alarms[i].h
        let minute = alarms[i].m
        var _diff = 0

        if ((hour == H && minute >= M) || (hour > H)) { // alarm later than in day
            _diff = Math.abs(new Date('2011/10/09 ' + hour + ':' + minute) -
            new Date('2011/10/09 ' + H+':'+M));
        } else {
            _diff = Math.abs(new Date('2011/10/10 ' + hour + ':' + minute) -
            new Date('2011/10/09 ' + H+':'+M));
        }

        if (_diff/1000 < min) {
            min = _diff
        }

        // alarms[i].diff = _diff/1000
    }

    // console.log(min)

    let hour = (min/1000/3600)|0
    let minute = ((min/1000)%3600)/60

    console.log(hour + " " + minute)

}

function main() {
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const test_cases = parseInt(readLine().trim(), 10);

    for (let gItr = 0; gItr < test_cases; gItr++) {
        const n_h_m = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
        const n = n_h_m[0]
        const H = n_h_m[1]
        const M = n_h_m[2]

        let alarms = []

        for(let i = 0; i < n; i ++) {
            const hm = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
            alarms.push({"h": hm[0], "m": hm[1]})
        }

        calc(H, M, alarms)

    }

    // ws.end();
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '', currentLine = 0;
process.stdin.on('data', inputStdin => { inputString += inputStdin; });
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => string.trim());
    main();
});
function readLine() {
    return inputString[currentLine++];
}
function main(){
  const t = +readLine();

  for(let j = 0;j<t;j++){
    const a = readLine().split(' ').map(p=> +p)
    const N = a[0];
    const H = a[1];
    const M = a[2];

    const Tot = H*60 + M;

    let ans = 24000;

    for(let i = 0;i<N;i++){
      let x = readLine().split(' ').map(p => +p);

      let h = x[0];
      let m = x[1];

      let time = h*60 + m;

      if(time<Tot){
        ans = Math.min(ans,2400-Tot+time);
      }else{
        ans = Math.min(ans, time-Tot);
      }

    }

    console.log(Math.floor(ans/60),ans%60)
  }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '', currentLine = 0;
process.stdin.on('data', inputStdin => { inputString += inputStdin; });
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => string.trim());
    main();
});
function readLine() {
    return inputString[currentLine++];
}

function main() {
    const t = +readLine();
    for(let i = 0; i < t; i++){
        const a = readLine().split(' ').map(p => +p);
        const n = a[0];
        const H = a[1];
        const M = a[2];
        let arr = [], aux;
        for(let j = 0; j < n; j++){
            aux = readLine().split(' ').map(p => +p);
            arr.push(aux);
        }
        let result = myFunc(H, M, arr);
        console.log(...result);
    }
}

function myFunc(H, M, arr){

    let c = (60*H + M);
    let min = Infinity;
    let min_val = Infinity;
    let aux, item;

    for(let i = 0; i < arr.length; i++){
        item = arr[i];
        aux = (60*item[0] + item[1]);
        if(aux < min_val){
            min_val = aux;
        }
        if(aux >= c && aux < min){
            min = aux;
        }
    }

    if(min == Infinity){
        min_val = 1440 - c + min_val;
       return [parseInt(min_val/60), min_val%60];
    }

    return [parseInt(min/60), min%60];

}