You are given two sequences $$$a_1, a_2, \dots, a_n$$$ and $$$b_1, b_2, \dots, b_n$$$. Each element of both sequences is either $$$0$$$, $$$1$$$ or $$$2$$$. The number of elements $$$0$$$, $$$1$$$, $$$2$$$ in the sequence $$$a$$$ is $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ respectively, and the number of elements $$$0$$$, $$$1$$$, $$$2$$$ in the sequence $$$b$$$ is $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ respectively.You can rearrange the elements in both sequences $$$a$$$ and $$$b$$$ however you like. After that, let's define a sequence $$$c$$$ as follows:$$$c_i = \begin{cases} a_i b_i & \mbox{if }a_i > b_i \\ 0 & \mbox{if }a_i = b_i \\ -a_i b_i & \mbox{if }a_i < b_i \end{cases}$$$You'd like to make $$$\sum_{i=1}^n c_i$$$ (the sum of all elements of the sequence $$$c$$$) as large as possible. What is the maximum possible sum?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains three integers $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ ($$$0 \le x_1, y_1, z_1 \le 10^8$$$) — the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$a$$$. The second line of each test case also contains three integers $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ ($$$0 \le x_2, y_2, z_2 \le 10^8$$$; $$$x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0$$$) — the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$b$$$.

For each test case, print the maximum possible sum of the sequence $$$c$$$.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    const [a, b, c] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const [d, e, f] = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    let ans = Math.min(c, e);

    const extra = Math.max(f - (a + c - ans), 0);

    ans -= extra;

    console.log(ans * 2);
  }
}

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.split(/\n/);
    main();
});

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

function main() {
  const t = Number(readLine())
  for (let _ = 0; _ < t; _++) {
    const [x1, y1, z1] = readLine().split(/\s/).map(Number)
    const [x2, y2, z2] = readLine().split(/\s/).map(Number)
    const positive = Math.min(z1, y2)
    const negative = Math.max(z2 - x1 - z1 + positive, 0)
    console.log((positive - negative) * 2)
  }
}

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b);
  if (b < a) return [];
  let arr = Array(b - a + 1)
  for (let i = a; i <= b; i++) arr[i] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.for = function (a, b, fn) {
  let res
  for (let i = a; i <= b; i++) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.forR = function (a, b, fn) {
  let res
  for (let i = a; i >= b; i--) {
    if ((res = fn(this[i], i, this)) != null) return res;
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return a;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  a = a || 0;
  b = b || (this.length - 1);
  let prev = a;
  for (let i = a; i <= b; i++) {
    if (i == b || fn(this[i], this[i + 1])) {
      arr.push(this.slice(prev, i + 1));
      prev = i + 1;
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
function inv(b, m) {
  for (var a = m, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + m) % m;
}

// let MOD = 1e9 + 7
// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
function main() {
  let inp = input.split(/\s+/).map(v => +v), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math, bi = BigInt;
  let t = $()
  while (t--) {
    let [a0, a1, a2, b0, b1, b2] = $(6);
    let plus = min(a2, b1);
    let minus = min(a1, (b0 + b1 + b2 - plus - b2))
    log(plus * 2 - min(a1 - minus) * 2)
  }
}

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

    probB();
});

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

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

function probA(){
    let t = parseInt(readline());
    while(t > 0){
        t--;
        let [n,k] = readline().split(' ');
        n = pi(n);
        k = pi(k);

        if(n < k)
            console.log(k-n);
        else{
            if((n+k) % 2 === 0){
                console.log(0);
            }else{
                console.log(n-k);
            }
        }
    }
}

function probB(){
    let t = pi(readline());

    while(t > 0){
        t--;
        let a = readline().split(' ');
        let b = readline().split(' ');

        a[0] = pi(a[0]);
        a[1] = pi(a[1]);
        a[2] = pi(a[2]);

        b[0] = pi(b[0]);
        b[1] = pi(b[1]);
        b[2] = pi(b[2]);

        let maxSum = 0;
        if(b[2] - (a[0] + a[2]) > 0){
            b[2] = b[2] - (a[0]+a[2]);
            a[0] = 0;
            a[2] = 0;
        }else if(b[2] - a[0] > 0){
            a[2] = a[2] - (b[2] - a[0]);
            b[2] = 0;
            a[0] = 0;
        }else{
            a[0] -= b[2];
            b[2] = 0;
        }

        if(a[2] > b[1])
            console.log((b[1] - b[2]) * 2)
        else
            console.log((a[2]-b[2]) * 2);

    }
}

var t = parseInt(readline());

while(t--){
    a = readline().split(' ');
    x1 = parseInt(a[0]);
    y1 = parseInt(a[1]);
    z1 = parseInt(a[2]);

    a = readline().split(' ');
    x2 = parseInt(a[0]);
    y2 = parseInt(a[1]);
    z2 = parseInt(a[2]);

    result = 0;
    min = Math.min(z1, y2);
    result += min * 2;
    z1 -= min;
    y2 -= min;

    min = Math.min(z2, x1);
    z2 -= min;
    x1 -= min;

    min = Math.min(z2, z1);
    z1 -= min;
    z2 -= min;

    result -= z2 * 2;

    print(result);
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    const [a, b, c] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const [d, e, f] = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    let diff = 0;
    if (f - a > 0) {
      diff = Math.min(f - a, b) * 2;
    }
    let ans = Math.min(c, e) * 2;

    if (ans) {
      ans -= diff;
    }

    console.log(ans);
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    const [a, b, c] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const [d, e, f] = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    let diff = 0;
    if (b + c > d + e) {
      diff = b + c - (d + e);
    }
    let ans = Math.min(c, e) * 2;

    if (ans) {
      ans -= diff * 2;
    }

    console.log(ans);
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    const [a, b, c] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    const [d, e, f] = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    console.log(Math.min(c, e) * 2);
  }
}

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

    probB();
});

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

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

function probA(){
    let t = parseInt(readline());
    while(t > 0){
        t--;
        let [n,k] = readline().split(' ');
        n = pi(n);
        k = pi(k);

        if(n < k)
            console.log(k-n);
        else{
            if((n+k) % 2 === 0){
                console.log(0);
            }else{
                console.log(n-k);
            }
        }
    }
}

function probB(){
    let t = pi(readline());

    while(t > 0){
        t--;
        let a = readline().split(' ');
        let b = readline().split(' ');

        a[0] = pi(a[0]);
        a[1] = pi(a[1]);
        a[2] = pi(a[2]);

        b[0] = pi(b[0]);
        b[1] = pi(b[1]);
        b[2] = pi(b[2]);

        let maxSum = 0;
        if(b[2] - (a[0] + a[2]) > 0){
            b[2] = b[2] - (a[0]+a[2]);
            a[0] = 0;
            a[1] = 0;
        }else if(b[2] - a[0] > 0){
            a[2] = a[2] - (b[2] - a[0]);
            b[2] = 0;
            a[0] = 0;
        }else{
            a[0] -= b[2];
            b[2] = 0;
        }

        if(a[2] > b[1])
            console.log((b[1] - b[2]) * 2)
        else
            console.log((a[2]-b[2]) * 2);

    }
}


Given $$$n$$$, find any array $$$a_1, a_2, \ldots, a_n$$$ of integers such that all of the following conditions hold: $$$1 \le a_i \le 10^9$$$ for every $$$i$$$ from $$$1$$$ to $$$n$$$.$$$a_1 < a_2 < \ldots <a_n$$$For every $$$i$$$ from $$$2$$$ to $$$n$$$, $$$a_i$$$ isn't divisible by $$$a_{i-1}$$$It can be shown that such an array always exists under the constraints of the problem.

The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case print $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ — the array you found. If there are multiple arrays satisfying all the conditions, print any of them.

NoteIn the first test case, array $$$[1]$$$ satisfies all the conditions.In the second test case, array $$$[2, 3]$$$ satisfies all the conditions, as $$$2<3$$$ and $$$3$$$ is not divisible by $$$2$$$.In the third test case, array $$$[111, 1111, 11111, 111111, 1111111, 11111111, 111111111]$$$ satisfies all the conditions, as it's increasing and $$$a_i$$$ isn't divisible by $$$a_{i-1}$$$ for any $$$i$$$ from $$$2$$$ to $$$7$$$.

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

"use strict";

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

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

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

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

function main() {

const x=+readline();
let g=[];
for(let i=0;i<x;i++){
    let y=+readline();
    let d=[];
    for(let i=2;i<y+2;i++){
        d.push(i);
    }

    g.push(d);

}

for(let i=0;i<g.length;i++){
    console.log(g[i].join(" "));

}
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;
function readline(){
    return input[currentline++];
}
var t = readline()
for(var i=1;i<=t;i++) {
	var h = readline();
	function r(u) {
		if(u==1) return 1;
		else {
			var ans = []
			for(var j=2;ans.length<h;j++) {
				ans.push(j)
			}
			return ans.join(' ');
		}
	}
	console.log(r(h))
}

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

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

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

"use strict";

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

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

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

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

function main() {

const x=+readline();
let g=[];
for(let i=0;i<x;i++){
    let y=+readline();
    let d=[];
    for(let i=2;i<y+2;i++){
        d.push(i);
    }

    g.push(d);

}

for(let i=0;i<g.length;i++){
    console.log(g[i]);

}

}

// your code goes here
const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;
function readline(){
    return input[currentline++];
}
var t = readline()
for(var i=1;i<=t;i++) {
	var h = readline();
	function r(u) {
		if(u==1) return 1;
		else {
			var ans = []
			for(var j=2;ans.length<h;j++) {
				ans.push(j)
			}
			return ans;
		}
	}
	console.log(r(h))
}


You are given an array of $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$. You can make the following operation: choose an integer $$$x \geq 2$$$ and replace each number of the array by the remainder when dividing that number by $$$x$$$, that is, for all $$$1 \leq i \leq n$$$ set $$$a_i$$$ to $$$a_i \bmod x$$$.Determine if it is possible to make all the elements of the array equal by applying the operation zero or more times.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array. The sum of $$$n$$$ for all test cases is at most $$$2 \cdot 10^5$$$.

For each test case, print a line with YES if you can make all elements of the list equal by applying the operation. Otherwise, print NO. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as a positive answer).

NoteIn the first test case, one can apply the operation with $$$x = 3$$$ to obtain the array $$$[2, 2, 0, 2]$$$, and then apply the operation with $$$x = 2$$$ to obtain $$$[0, 0, 0, 0]$$$.In the second test case, all numbers are already equal.In the fourth test case, applying the operation with $$$x = 4$$$ results in the array $$$[1, 1, 1, 1]$$$.

const solve = (n,arr)=>{
     arr = arr.sort((a,b)=>a-b);
     let one = false;
     let consec = false;
     for(let i=0;i<n;i++){
          if(arr[i]===1) one = true;
          if((i<n-1)&&(arr[i]+1===arr[i+1])) consec = true;
     }
     return (one && consec)? "NO":"YES"
}
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 = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       console.log(solve(n,arr));
  }
}
main();

const solve = (n,arr)=>{
     arr = arr.sort((a,b)=>a-b);
     if(arr[0]>=2) return "YES";
     else if(arr[0]===0){
          for(let i=1;i<n;i++)
               if(arr[i]===1) return "NO";
               else if(arr[i]>=2) break;
     }
     else{
     for(let i=1;i<n;i++){
          if(arr[i]===2) return "NO";
          else if((arr[i]-arr[i-1])===1) return "NO";
     }
     }
     return "YES";
}
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 = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       console.log(solve(n,arr));
  }
}
main();

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')
const N = Number(inputs[0])
inputs.shift()
main(N, inputs)
function main(N, inputs) {
  next: for (let _ = 0; _ < N; _++) {
    const n = Number(inputs[_ * 2]),
      nums = inputs[_ * 2 + 1].split(' ').map(Number)
    let has0 = nums.some(num => num === 0),
      has1 = nums.some(num => num === 1)
    if (has0 && has1) {
      console.log('NO')
    } else if (!has1) {
      console.log('YES')
    } else {
      nums.sort((a, b) => b - a)
      for (let i = 1; i < n; i++) {
        if (nums[i] === nums[i - 1] - 1) {
          console.log('NO')
          continue next
        }
      }

      console.log('YES')
    }
  }
}

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

const EPS = 1e-6;

function main() {
    let T = +readline();
    while (T--){
      let [n] = readline().split(' ').map(a=>+a);
      let arr = readline().split(' ').map(a=>+a);
      let can_turn_all_to_0 = true
      let can_turn_all_to_1 = true
      let has_1 = false
      let all_same = true;
      for (let a of arr){
        if (arr[0]!=a)
          all_same = false;
        if (a==1)
          can_turn_all_to_0 = false;
        if (a==1)
          has_1 = true;
        if (a==2 || a==0)
          can_turn_all_to_1 = false;
      }
      if (!has_1 || all_same){
        print('yes');
      } else {
        arr.sort((a, b)=>a-b);
        let fail;
        for (let i=0; i<n-1; i++)
        {
          if (arr[i]+1==arr[i+1])
          {
            fail = true;
            break;
          }
        }
        print(!fail ? 'yes' : 'no')
      }
    }
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var a = lines[i].split(' ').map(Number).sort(function(a, b){return a - b});
            var flag1 = 0, flag2 = 0;
            for(j = 0; j < n; j++){
                if(a[j] == 1){
                    flag1 = 1;
                }
                if(j < n - 1 && a[j + 1] - a[j] == 1){
                    flag2 = 1;
                }
            }
            console.log(flag1 && flag2 ? 'NO' : 'YES');
        }
    }
});

const solve = (n,arr)=>{
     arr = arr.sort((a,b)=>a-b);
     if(arr[0]>=2) return "YES";
     else if(arr[0]===0){
          for(let i=1;i<n;i++)
               if(arr[i]===1) return "NO";
               else if(arr[i]>=2) break;
     }
     let arr1 = [arr[0]];
     for(let i=1;i<n;i++){
          if(arr[i]===2) return "NO";
          else if((arr[i]-arr[i-1])===1) return "NO";
     }
     return "YES";
}
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 = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       console.log(solve(n,arr));
  }
}
main();

const solve = (n,arr)=>{
     arr = arr.sort((a,b)=>a-b);
     if(arr[0]===0){
          let flag = 1;
          for(let i=1;i<n-1;i++){
               if((arr[i]===1)&&(arr[i+1]>=2)) return "NO";
               else if(arr[i]>=2) break;
          }
     }
     else if(arr[0]===1){
          for(let i=1;i<n;i++){
               if(arr[i]===2) return "NO";
               else if(arr[i]>2){
                    for(let j=i+1;j<n;i++){
                         if(arr[j]%arr[i]!==1) return "NO";
                    }
               }
          }
     }
     return "YES";
}
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 = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       console.log(solve(n,arr));
  }
}
main();

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')
const N = Number(inputs[0])
inputs.shift()
main(N, inputs)
function main(N, inputs) {
  next: for (let _ = 0; _ < N; _++) {
    const n = Number(inputs[_ * 2]),
      nums = inputs[_ * 2 + 1].split(' ').map(Number)
    let has0 = nums.some(num => num === 0),
      has1 = nums.some(num => num === 1)
    if (has0 && has1) {
      console.log('NO')
    } else if (!has1) {
      console.log('YES')
    } else {
      nums.sort((a, b) => b - a)
      for (let i = 1; i < n; i++) {
        console.log(i, nums[i], nums[i - 1])
        if (nums[i] === nums[i - 1] - 1) {
          console.log('NO')
          continue next
        }
      }

      console.log('YES')
    }
  }
}

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')
const N = Number(inputs[0])
inputs.shift()
main(N, inputs)
function main(N, inputs) {
  next: for (let _ = 0; _ < N; _++) {
    const n = Number(inputs[_ * 2]),
      nums = inputs[_ * 2 + 1].split(' ').map(Number)
    let has0 = nums.some(num => num === 0),
      has1 = nums.some(num => num === 1)
    if (has0 && has1) {
      console.log('NO')
    } else if (!has1) {
      console.log('YES')
    } else {
      nums.sort((a, b) => b - a)
      console.log(nums, n)
      for (let i = 1; i < n; i++) {
        console.log(i, nums[i], nums[i - 1])
        if (nums[i] === nums[i - 1] - 1) {
          console.log('NO')
          continue next
        }
      }

      console.log('YES')
    }
  }
}

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

const EPS = 1e-6;

function main() {
    let T = +readline();
    while (T--){
      let [n] = readline().split(' ').map(a=>+a);
      let arr = readline().split(' ').map(a=>+a);
      let can_turn_all_to_0 = true
      let can_turn_all_to_1 = true
      let all_same = true;
      for (let a of arr){
        if (arr[0]!=a)
          all_same = false;
        if (a==1)
          can_turn_all_to_0 = false;
        if (a==2 || a==0)
          can_turn_all_to_1 = false;
      }
      print(all_same || can_turn_all_to_0 || can_turn_all_to_1 ? 'yes' : 'no')
    }
}


Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes.  They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.

The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.

After each round, print the current score of the bears.

"use strict";
// Object.defineProperty(exports, "__esModule", { value: true });
// var lol_io_1 = require("lol-io");
function readNumbers() {
    return readline().split(' ').map(function (s) { return parseInt(s); });
}
function readMatrix(n) {
    var matrix = [];
    for (var i = 0; i < n; i++) {
        var row = readNumbers();
        matrix.push(row);
    }
    return matrix;
}
function readQueries(q) {
    var queries = [];
    for (var i = 0; i < q; i++) {
        var _a = readNumbers(), r = _a[0], c = _a[1];
        queries.push([r, c]);
    }
    return queries;
}
function arrayFilled(n, value) {
    var a = [];
    for (var i = 0; i < n; i++)
        a.push(value);
    return a;
}
function computeMaxForRows() {
    var maxSeqInRow = arrayFilled(n, 0);
    for (var i = 0; i < matrix.length; i++) {
        var row = matrix[i];
        var currMax = 0;
        for (var j = 0; j < row.length; j++) {
            if (row[j]) {
                currMax++;
                maxSeqInRow[i] = Math.max(maxSeqInRow[i], currMax);
            }
            else {
                currMax = 0;
            }
        }
    }
    return maxSeqInRow;
}
function computeMaxForRow(i) {
    maxSeqInRow[i] = 0;
    var row = matrix[i];
    var currMax = 0;
    for (var j = 0; j < row.length; j++) {
        if (row[j]) {
            currMax++;
            maxSeqInRow[i] = Math.max(maxSeqInRow[i], currMax);
        }
        else {
            currMax = 0;
        }
    }
}
var _a = readNumbers(), n = _a[0], m = _a[1], q = _a[2];
var matrix = readMatrix(n);
var queries = readQueries(q);
var maxSeqInRow = computeMaxForRows();
function solve() {
    for (var _i = 0, queries_1 = queries; _i < queries_1.length; _i++) {
        var _a = queries_1[_i], i = _a[0], j = _a[1];
        matrix[i - 1][j - 1] ^= 1;
        computeMaxForRow(i - 1);
        print(Math.max.apply(Math, maxSeqInRow).toString());
    }
}
solve();


There are $$$n$$$ students standing in a circle in some order. The index of the $$$i$$$-th student is $$$p_i$$$. It is guaranteed that all indices of students are distinct integers from $$$1$$$ to $$$n$$$ (i. e. they form a permutation).Students want to start a round dance. A clockwise round dance can be started if the student $$$2$$$ comes right after the student $$$1$$$ in clockwise order (there are no students between them), the student $$$3$$$ comes right after the student $$$2$$$ in clockwise order, and so on, and the student $$$n$$$ comes right after the student $$$n - 1$$$ in clockwise order. A counterclockwise round dance is almost the same thing — the only difference is that the student $$$i$$$ should be right after the student $$$i - 1$$$ in counterclockwise order (this condition should be met for every $$$i$$$ from $$$2$$$ to $$$n$$$). For example, if the indices of students listed in clockwise order are $$$[2, 3, 4, 5, 1]$$$, then they can start a clockwise round dance. If the students have indices $$$[3, 2, 1, 4]$$$ in clockwise order, then they can start a counterclockwise round dance.Your task is to determine whether it is possible to start a round dance. Note that the students cannot change their positions before starting the dance; they cannot swap or leave the circle, and no other student can enter the circle. You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 200$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 200$$$) — the number of students. The second line of the query contains a permutation of indices $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ is the index of the $$$i$$$-th student (in clockwise order). It is guaranteed that all $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$ (i. e. they form a permutation).

For each query, print the answer on it. If a round dance can be started with the given order of students, print "YES". Otherwise print "NO".

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

function query(arr){
    let n = arr.length;
    let arr2 = arr.concat(arr);
    let f = arr2.indexOf(1);
    for (let i=0; i<n; i++)
    {
        if (arr2[f+i]!=i+1)
            return false;
    }
    return true;
}

function main() {
    var q = +readline();
    while (q--)
    {
        var n = +readline();
        let arr = readline().split(' ').map(n=>+n);
        if (query(arr) || query(arr.reverse()))
            print('YES')
        else
            print('NO');
    }
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {

        function can1 (data) {
            return data.reduce((agr, value, index, array) => {
                if (!agr) return false;
                if (index === array.length - 1) return agr;
                return value === array[index + 1] - 1 || array[index + 1] === 1;
            }, true);
        }

        function can0 (data) {
            return data.reduceRight((agr, value, index, array) => {
                if (!agr) return false;
                if (index === 0) return agr;
                return value === array[index - 1] - 1 || array[index - 1] === 1;
            }, true);
        }

        return can1(data) || can0(data);
    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let data = lines[testCount * 2].split(" ").map(Number);
        //console.log(data);
        let result = foo(data);
        answer += (result ? "YES" : "NO") +"\n";
        testCount++;
    }
    console.log(answer);
})

let i = '';
process.stdin.on('data', (c) => {
  i += c;
});
process.stdin.on('end', () => {
  const { EOL } = require('os');
  const lines = i.split(EOL);
  let count = 2;
  // console.log(lines);
  while (count < lines.length) {
    let input = lines[count].split(' ');
    input = input.map(str => parseInt(str, 10));
    canDance(input);
    count += 2;
  }
});

function canDance(arr) {
  let index = arr.indexOf(1);
  if (index === -1) {
    console.log('NO');
    return;
  }

  // clockwise
  const startIndex = index;
  let curr = 1;
  index++;
  while (index !== startIndex) {
    if (index === arr.length) index = 0;
    if (arr[index] === curr + 1) {
      curr++;
      index++;
    } else {
      break;
    }
  }

  if (index === startIndex) {
    console.log('YES');
    return;
  }

  curr = 1;
  index = startIndex - 1;
  while (index !== startIndex) {
    if (index === -1) index = arr.length - 1;
    if (arr[index] === curr + 1) {
      curr++;
      index--;
    } else {
      break;
    }
  }
  if (index === startIndex) {
    console.log('YES');
  } else {
    console.log('NO');
  }
}

'use strict'

const roundelay = (n, p) => {
    let i = 1;
    while (i < n && (p[i] === p[i-1] + 1 || p[i-1] === n && p[i] === 1)) i++;
    if (i === n) return 'YES';
    i = 1;
    while (i < n && (p[i] === p[i-1] - 1 || p[i-1] === 1 && p[i] === n)) i++;
    if (i === n) return 'YES';
    return 'NO';
}

const q = parseInt(readline());
for (let i = 0; i < q; i++) {
    write(roundelay(parseInt(readline()), readline().split(' ').map(Number)) + '\n');
}

rVal = () => +readline();
rArr = () => readline().split(' ').map(item => +item);

var q = rVal();

for(var i = 0; i < q; i++) {
  var n = rVal();
  var arr = rArr();

  if(n === 1) {
    print('YES');
    continue;
  }

  for(var j = 0; j < n; j++) {
    if(arr[j] === 1) {
      index = j;
      break;
    }
  }

  var j = 0;

  for(j = 0, k = index; j < n - 1; j++) {
    var k2 = k + 1;
    if(k2 === n) {
      k2 = 0;
    }
    if(arr[k2] - arr[k] === 1) {
      k = k2;
    } else {
      break;
    }
  }

  if(j === n - 1) {
    print('YES');
    continue;
  }

  for(var j = 0, k = index; j < n - 1; j++) {
    var k2 = k - 1;
    if(k2 < 0) {
      k2 = n - 1;
    }
    if(arr[k2] - arr[k] === 1) {
      k = k2;
    } else {
      break;
    }
  }

  if(j === n - 1) {
    print('YES');
    continue;
  }

  print('NO');
}

'use strict'

var t=Number(readline());

while(t--)
{
    var n=parseInt(readline());
    var data=readline().split(' ').map(Number);

    var start_idx=-1;
    for(var i=0;i<n;i++){
        if(data[i]==1) start_idx=i;
    }

    var flag= true;
    var clockW=start_idx;

    for(var i=1;i<n;i++){
        var tmp=data[clockW];
        clockW++;
        if(clockW>=n) clockW=0;
        if((data[clockW]-tmp)!=1){
            flag=false;
            break;
        }
    }

    if(!flag){
        flag=true;
        clockW=start_idx;

        for(var i=1;i<n;i++){
            var tmp=data[clockW];
            clockW--;
            if(clockW<0) clockW=n-1;

            if( (data[clockW]-tmp)!=1 ){
                flag=false;
                break;
            }
        }
    }

    print((flag)?"YES":"NO");
}

'use strict'

const roundelay = (n, p) => {
    let i = 1;
    while (i < n && (p[i] === p[i-1] + 1 || p[i-1] === n && p[i] === 1)) i++;
    if (i === n) return 'OK';
    i = 1;
    while (i < n && (p[i] === p[i-1] - 1 || p[i-1] === 1 && p[i] === n)) i++;
    if (i === n) return 'OK';
    return 'NO';
}

const q = parseInt(readline());
for (let i = 0; i < q; i++) {
    roundelay(parseInt(readline()), readline().split(' ').map(Number));
}

'use strict'

const roundelay = (n, p) => {
    let i = 1;
    while (i < n && (p[i] === p[i-1] + 1 || p[i-1] === n && p[i] === 1)) i++;
    if (i === n) return 'OK';
    i = 1;
    while (i < n && (p[i] === p[i-1] - 1 || p[i-1] === 1 && p[i] === n)) i++;
    if (i === n) return 'OK';
    return 'NO';
}

const q = parseInt(readline());
for (let i = 0; i < q; i++) {
    write(roundelay(parseInt(readline()), readline().split(' ').map(Number)) + '\n');
}


Let $$$s$$$ be a string of lowercase Latin letters. Its price is the sum of the indices of letters (an integer between 1 and 26) that are included in it. For example, the price of the string abca is $$$1+2+3+1=7$$$.The string $$$w$$$ and the integer $$$p$$$ are given. Remove the minimal number of letters from $$$w$$$ so that its price becomes less than or equal to $$$p$$$ and print the resulting string. Note that the resulting string may be empty. You can delete arbitrary letters, they do not have to go in a row. If the price of a given string $$$w$$$ is less than or equal to $$$p$$$, then nothing needs to be deleted and $$$w$$$ must be output.Note that when you delete a letter from $$$w$$$, the order of the remaining letters is preserved. For example, if you delete the letter e from the string test, you get tst.

The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The following are descriptions of $$$t$$$ test cases. Each case consists of two lines. The first of them is the string $$$w$$$, it is non-empty and consists of lowercase Latin letters. Its length does not exceed $$$2\cdot10^5$$$. The second line contains an integer $$$p$$$ ($$$1 \le p \le 5\,200\,000$$$). It is guaranteed that the sum of string lengths $$$w$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Output exactly $$$t$$$ rows, the $$$i$$$-th of them should contain the answer to the $$$i$$$-th set of input data. Print the longest string that is obtained from $$$w$$$ by deleting letters such that its price is less or equal to $$$p$$$. If there are several answers, then output any of them. Note that the empty string  — is one of the possible answers. In this case, just output an empty string.

5

abca

2

abca

6

codeforces

1

codeforces

10

codeforces

100

const main = () => {

	var t = readInt();
	var allans = [];
	for (var zz = 0; zz < t; zz++) {
		var s = readString();
		var n = s.length;
		var p = readInt();

		var idxs = [];
		for (var i = 0; i < 27; i++)
			idxs.push([]);
		for (var i = 0; i < n; i++)
			idxs[s.charCodeAt(i) - 96].push(i);

		var total = 0;
		var takeIdx = [0];
		for (var i = 0; i < n; i++)
			takeIdx.push(0);
		for (var i = 1; i < 27; i++) {
			while (total + i <= p && idxs[i].length > 0) {
				total += i;
				takeIdx[idxs[i][idxs[i].length - 1]] = 1;
				idxs[i].pop();
			}
		}
		var ansarr = [];
		for (var i = 0; i < n; i++)
			if (takeIdx[i] === 1)
				ansarr.push(s[i]);
		var ans = ansarr.join('');
		allans.push(ans);
	}
	multiLineArrayPrint(allans);

	return;
}

const readInt = () => parseInt(readline());
const readString = () => readline();
const readIntArr = () => readline().split(" ").map(zzzz => parseInt(zzzz));
const parseLong = (string) => { // javascript's largest long is < (1<<62)
	var n = string.length;
	var res = 0;
	for (var i = 0; i < n; i++) {
		res *= 10;
		res += parseInt(string[i]);
	}
	return res;
}
const readLong = () => parseLong(readLong());
const readLongArr = () => readline().split(" ").map(zzzz => parseLong(zzzz));
const oneLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join(' '));
const multiLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join('\n'));
const multiLineArrayOfArraysPrint = (arr) => print(arr.map(yyyy => yyyy.map(zzzz => zzzz.toString()).join(' ')).join('\n'));
const makeArr = (defaultVal, dimensionsArr) => {
	var n = dimensionsArr.length;
	if (n === 1) return Array(dimensionsArr[0]).fill(defaultVal);
	else {
		var temp = [];
		for (var i = 0; i < dimensionsArr[0]; i++)
			temp.push(makeArr(defaultVal, dimensionsArr.slice(1)));
		return temp;
	}
}

for (_ = 0; _ < 1; _++) {
	main();
}

// newline for testing
 //newline for testing
// codeforces js cannot use "let" keyword. use "var" instead
// codeforces js cannot destructure arrays

T = readline()

abc = 'abcdefghijklmnopqrstuvwxyz'.split('')
obj = {}
for(i=0; i< abc.length; i++){
      obj[abc[i]] = i +1
}

while(T--){
      str = readline().split('').map(el => obj[el])
      p = readline()

      sum = str.reduce(function(acc, cur){
            return acc + cur
      }, 0)

      clone = str.slice()
      clone.sort((a, b) =>  a - b)

      while(sum > p){
            sum = sum - clone[clone.length-1]
            clone.pop()
      }

      objAns = {}
      for(i = 0; i < clone.length; i++){
            if(objAns[clone[i]] === undefined)
                  objAns[clone[i]] = 1
            else
                  objAns[clone[i]]++
      }

      strAns = []

      for(i = 0; i< str.length; i++){
            if(objAns[str[i]]){
                  objAns[str[i]]--
                  strAns.push(str[i])
            }
      }

      resultObj = {}

      Object.keys(obj).forEach(key => {
            value = obj[key]
            resultObj[value] = key
      })

      res = strAns.map(el => resultObj[el])

      print(res.join(''))
}

"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++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let arr = readline().trim().split("");
    let n = arr.length;
    let k = parseInt(readline());
    let obj = {
      a: 1,
      b: 2,
      c: 3,
      d: 4,
      e: 5,
      f: 6,
      g: 7,
      h: 8,
      i: 9,
      j: 10,
      k: 11,
      l: 12,
      m: 13,
      n: 14,
      o: 15,
      p: 16,
      q: 17,
      r: 18,
      s: 19,
      t: 20,
      u: 21,
      v: 22,
      w: 23,
      x: 24,
      y: 25,
      z: 26,
    };
    let narr = [];
    for (let i = 0; i < n; i++) {
      let o = { val: obj[arr[i]], ind: i };
      narr.push(o);
    }
    narr.sort((a, b) => a.val - b.val);
    let sum = 0;
    for (let i = 0; i < n; i++) sum += narr[i].val;
    let c = {},
      i = n - 1;
    while (sum > k && i >= 0) {
      sum -= narr[i].val;
      c[narr[i].ind] = 1;
      i--;
    }
    let res = "";
    for (let i = 0; i < n; i++) {
      if (c[i]) continue;
      else res += arr[i];
    }
    console.log(res);
  }
};
solve();

'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 alph = [...Array(26)].map((_, i) => String.fromCharCode(i + 97));
    let price = {};
    alph.forEach((letter, i) => price[letter] = i + 1);
    let N = readline();

    for (let test = 0; test < N; test++) {
        let str = readline();
        let target = Number(readline());

        if (str === '' || target === 0) {
            output('');
            continue;
        }

        let totalCost = 0;
        let costs = str.split('').map((letter, index) => {
            totalCost += price[letter];
            return {
                originalIndex: index,
                letter: letter,
                cost: price[letter]
            };
        });
        costs.sort((a, b) => a.cost - b.cost);

        while (totalCost > target) {
            let next = costs.pop();
            totalCost -= next.cost;
        }

        costs.sort((a, b) => a.originalIndex - b.originalIndex);

        let result = costs.map(c => c.letter).join('');

        output(result);
    }
}

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

function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
function abs(x) {
  return x < 0 ? x*(-1) : x;
}
// console.log(input)
var T = readline();
// var inf = 1000000000000;
for(var tc=1;tc<=T;tc++) {
  // var nul = readline();
  var n = readline()//.split(' ').map((x) => parseInt(x));
  // var a = readline().split(' ').map((x) => parseInt(x));
  var p = readline();
  var c = []
  var f = alph();
  var mp = new Map();
  for(var i=0;i<f.length;i++) mp.set(f[i], i+1)
  for(var i=0;i<n.length;i++) {
    c.push([i, mp.get(n[i])])
  }
  c.sort(function(a, b) { return a[1] - b[1] });
  // if(tc == 1) console.log(c)
  var ans = "";
  var g = 0;
  for(var i=0;i<c.length;i++) {
    var val = c[i][1];
    if(g + val > p) {
      // if(tc == 1) console.log("p", i)
      break;
    }
    g += val;
    // ans += n[c[i][0]]
  }
  var ca = c.slice(0, i)
  ca.sort(function(a,b) { return a[0] - b[0] })
  for(var i=0;i<ca.length;i++) ans += n[ca[i][0]]
  console.log(ans)
}

'use strict';

function solve(n, s) {
  const m = s.length;
  const a = new Array(m);
  for (let i = 0; i < m; i++) a[i] = s.charCodeAt(i) - 96;
  let sum = a.reduce((a, b) => a + b, 0);
  if (sum <= n) return s;
  const map = Array.from({
    length: 27
  }, () => []);
  let res = new Array(m).fill(1);
  for (let [i, num] of a.entries()) map[num].push(i);
  let i = 26;
  while (sum > n) {
    while (i >= 0 && map[i].length === 0) {
      i--;
    }
    if (map[i].length === 0) return '';
    const j = map[i].pop();
    res[j] = 0;
    sum -= i;
  }
  let ans = '';
  for (let i = 0; i < m; i++) {
    if (res[i]) ans += s[i];
  }
  return ans;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const s = await read();
      const n = Number(await read());
      res[i] = solve(n, s);
    }
    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);
});

//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();
	var alpha = "abcdefghijklmnopqrstuvwxyz";
	var costmap = {};
	for(var i = 0; i < alpha.length; i++){
		costmap[alpha[i]] = i + 1;
	}
	while(hasNext()){
		var S = nextCharArray();
		var N = S.length;
		var P = nextInt();
		var cost = 0;
		var map = {};
		for(var i = 0; i < N; i++){
			cost += costmap[S[i]];
			if(map[S[i]] == null){
				map[S[i]] = [];
			}
			map[S[i]].push(i);
		}
		for(var i = alpha.length - 1; i >= 0; i--){
			if(cost <= P){
				break;
			}
			if(map[alpha[i]] == null){
				continue;
			}
			var nx = map[alpha[i]];
			for(var j = 0; j < nx.length; j++){
				S[nx[j]] = "";
				cost -= costmap[alpha[i]];
				if(cost <= P){
					break;
				}
			}
		}
		myout(myconv(S, 0));
	}
}

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

function solve(str, p) {
    const arr = []
    for (let i = 0; i < str.length; i++) {
        const x = str.charCodeAt(i) - 'a'.charCodeAt(0) + 1
        arr.push([x, i])
    }
    arr.sort((a, b) => a[0] - b[0])
    //
    let now = 0
    const skip = {}
    for (let i = 0; i < arr.length; i++) {
        const [x, j] = arr[i]
        if (now + x > p) {
            // delete
            skip[j] = 1
        } else {
            now += x
        }
    }
    const ans = []
    for (let i = 0; i < str.length; i++) {
        if (!skip[i]) ans.push(str[i])
    }
    return ans.join('')
}

"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++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let arr = readline().trim().split("");
    let n = arr.length;
    let k = parseInt(readline());
    let obj = {
      a: 1,
      b: 2,
      c: 3,
      d: 4,
      e: 5,
      f: 6,
      g: 7,
      h: 8,
      i: 9,
      j: 10,
      k: 11,
      l: 12,
      m: 13,
      n: 14,
      o: 15,
      p: 16,
      q: 17,
      r: 18,
      s: 19,
      t: 20,
      u: 21,
      v: 22,
      w: 23,
      x: 24,
      y: 25,
      z: 26,
    };
    let narr = [];
    for (let i = 0; i < n; i++) {
      let o = { val: obj[arr[i]], ind: i };
      narr.push(o);
    }
    narr.sort((a, b) => a.val - b.val);
    let sum = 0;
    for (let i = 0; i < n; i++) sum += narr[i].val;
    let c = {},
      i = n - 1;
    if (sum === k) {
      console.log("");
      continue;
    }
    while (sum > k && i >= 0) {
      sum -= narr[i].val;
      c[narr[i].ind] = 1;
      i--;
    }
    let res = "";
    for (let i = 0; i < n; i++) {
      if (c[i]) continue;
      else res += arr[i];
    }
    console.log(res);
  }
};
solve();


One very important person has a piece of paper in the form of a rectangle a × b.Also, he has n seals. Each seal leaves an impression on the paper in the form of a rectangle of the size xi × yi. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees).A very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?

The first line contains three integer numbers n, a and b (1 ≤ n, a, b ≤ 100). Each of the next n lines contain two numbers xi, yi (1 ≤ xi, yi ≤ 100).

Print the largest total area that can be occupied by two seals. If you can not select two seals, print 0.

NoteIn the first example you can rotate the second seal by 90 degrees. Then put impression of it right under the impression of the first seal. This will occupy all the piece of paper.In the second example you can't choose the last seal because it doesn't fit. By choosing the first and the third seals you occupy the largest area.In the third example there is no such pair of seals that they both can fit on a piece of paper.

ln=readline().split(" ").map(x=>x*1);
n=ln[0];
a=ln[1];
b=ln[2];
seals = [];
for(i=0; i<n; i++){
    seals.push(readline().split(" ").map(x=>x*1));
}

function canFit(x1,y1,x2,y2){
    if(x1>a||x2>a||y1>b||y2>b) return false;
    ox = x1+x2>a?false:true;
    oy = y1+y2>b?false:true;
    return ox||oy;
}

ans = 0;
for(i=0; i<n-1; i++){
    for(j=i+1; j<n; j++){
        ix = seals[i][0];
        iy = seals[i][1];
        jx = seals[j][0];
        jy = seals[j][1];
        a1 = ix*iy;
        a2 = jx*jy;
        if(canFit(ix,iy, jx,jy)||canFit(iy,ix, jx,jy)||canFit(ix,iy, jy,jx)||canFit(iy,ix, jy,jx)){
            ans = ans<a1+a2?a1+a2:ans;
        }
    }
}
print(ans);

ln=readline().split(" ").map(x=>x*1);
n=ln[0];
a=ln[1];
b=ln[2];
seals = [];
for(i=0; i<n; i++){
    seals.push(readline().split(" ").map(x=>x*1));
}

function canFit(x1,y1,x2,y2){
    if(x1>a||x2>a||y1>b||y2>b) return false;
    ox = x1+x2>a?true:false;
    oy = y1+y2>b?true:false;
    return ox||oy;
}

ans = 0;
for(i=0; i<n-1; i++){
    for(j=i+1; j<n; j++){
        ix = seals[i][0];
        iy = seals[i][1];
        jx = seals[j][0];
        jy = seals[j][1];
        a1 = ix*iy;
        a2 = jx*jy;
        if(canFit(ix,iy, jx,jy)||canFit(iy,ix, jx,jy)||canFit(ix,iy, jy,jx)||canFit(iy,ix, jy,jx)){
            ans = ans<a1+a2?a1+a2:ans;
        }
    }
}
print(ans);

var rline = readline().split(" ");var xy = [rline[1],rline[2]];

var temp = [];for(var o=0;o<rline[0];o++)temp.push(readline().split(" "))
var ayinput = [];

for(var i = 0;i<temp.length;i++){
 ayinput.push((+xy[0]-(+temp[i][0]))*xy[1] + " " + (+xy[1]-(+temp[i][1]))*xy[0]);
}

var lastspace = 9005;var round = 0;var z = 0;var e = 9999;
for(var r = 0;r<ayinput.length;r++){
 var firstitem = ayinput[r].split(" ");for(var m = r+1;m<ayinput.length;m++){

var seconditem = ayinput[m].split(" ");
var fps0 = (+firstitem[z])+(+seconditem[0]);var fps1 = (+firstitem[z])+(+seconditem[1]);

if(fps0>=xy[0]*xy[1]){if((fps0<=lastspace)&&(seconditem[1]<=e) ){
    e = seconditem[1];lastspace= fps0;round =((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}

if(fps1>=xy[0]*xy[1]){if((fps1<=lastspace)&&(seconditem[0]<=e)){
    e = seconditem[0];lastspace=fps1;round = ((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}

}if(z===0){z+=1;r-=1}
}
 print(round);

    var rline = readline().split(" ");var xy = [rline[1],rline[2]];

    var temp = [];for(var o=0;o<rline[0];o++)temp.push(readline().split(" "))
    var ayinput = [];

    for(var i = 0;i<temp.length;i++){
    ayinput.push((+xy[0]-(+temp[i][0]))*xy[1] + " " + (+xy[1]-(+temp[i][1]))*xy[0]);
    }

    var lastspace = 9999999;var round = 0;var z = 0;var e = 9999999;
    for(var r = 0;r<ayinput.length;r++){
    var firstitem = ayinput[r].split(" ");for(var m = r+1;m<ayinput.length;m++){

    var seconditem = ayinput[m].split(" ");
    var fps0 = (+firstitem[z])+(+seconditem[0]);var fps1 = (+firstitem[z])+(+seconditem[1]);

    if((fps0>=xy[0]*xy[1])&&(fps0<=lastspace)){

       var s = true ;if((fps0==lastspace)&&(seconditem[1]>e)){s=false}
        if(s==true){
        e = seconditem[1];lastspace= fps0;round =((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}

    if((fps1>=xy[0]*xy[1])&&(fps1<=lastspace)){
         s = true ;if((fps1==lastspace)&&(seconditem[0]>e)){s=false}
         if(s==true){
        e = seconditem[0];lastspace=fps1;round = ((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}

    }if(z===0){z+=1;r-=1}
    }
    print(round);

var rline = readline().split(" ");var xy = [+rline[1],+rline[2]];
var round = [0];
var ayinput = [];for(var o=0;o<rline[0];o++)ayinput.push(readline().split(" "))

for(var i =0;i<ayinput.length;i++){
for(var r=i+1;r<ayinput.length;r++){kk(ayinput[i],ayinput[r])}
}

function kk(a,b){

var s1 = [xy[0] - (+a[0]) , xy[1]];var s2 = [xy[1] - (+a[1]) , xy[0]];
var s3 = [xy[0] - (+a[1]) , xy[1]];var s4 = [xy[1] - (+a[0]) , xy[0]];
var toot = [s1,s2,s3,s4];for(var x = 0;x<toot.length;x++){

if(toot[x][0]>0){

  if ((toot[x][0] >= b[0]) && (toot[x][1]>=b[0])){
    round.push((+(ayinput[i][0]*ayinput[i][1]))  +  (+(ayinput[r][0]*ayinput[r][1])))
    if(round[round.length - 1]>xy[0]*xy[1])round[round.length - 1] = 0;
          }

  if ((toot[x][1] >= b[0]) && (toot[x][0]>=b[1])){
    round.push((+(ayinput[i][0]*ayinput[i][1]))  +  (+(ayinput[r][0]*ayinput[r][1])))
    if(round[round.length - 1]>xy[0]*xy[1])round[round.length - 1] = 0;
  }
  }

}
}

print(Math.max(...round))

var rline = readline().split(" ");var xy = [+rline[1],+rline[2]];
var round = [0];
var ayinput = [];for(var o=0;o<rline[0];o++)ayinput.push(readline().split(" "))

for(var i =0;i<ayinput.length;i++){
for(var r=i+1;r<ayinput.length;r++){kk(ayinput[i],ayinput[r])}
}

function kk(a,b){

var s1 = [xy[0] - (+a[0]) , xy[1]];var s2 = [xy[1] - (+a[1]) , xy[0]];
var s3 = [xy[0] - (+a[1]) , xy[1]];var s4 = [xy[1] - (+a[0]) , xy[0]];
var toot = [s1,s2,s3,s4];for(var x = 0;x<toot.length;x++){

if(toot[x][0]>0){

  if ((toot[x][0] >= b[0]) && (toot[x][1]>=b[1])){
    round.push((+(ayinput[i][0]*ayinput[i][1]))  +  (+(ayinput[r][0]*ayinput[r][1])))
    if(round[round.length - 1]>xy[0]*xy[1])round[round.length - 1] = 0;
          }

  if ((toot[x][1] >= b[0]) && (toot[x][0]>=b[1])){
    round.push((+(ayinput[i][0]*ayinput[i][1]))  +  (+(ayinput[r][0]*ayinput[r][1])))
    if(round[round.length - 1]>xy[0]*xy[1])round[round.length - 1] = 0;
  }
  }

}
}

print(Math.max(...round))

    var rline = readline().split(" ");var xy = [rline[1],rline[2]];

    var temp = [];for(var o=0;o<rline[0];o++)temp.push(readline().split(" "))
    var ayinput = [];

    for(var i = 0;i<temp.length;i++){
    ayinput.push((+xy[0]-(+temp[i][0]))*xy[1] + " " + (+xy[1]-(+temp[i][1]))*xy[0]);
    }

    var lastspace = 9999999;var round = 0;var z = 0;var e = 9999999;
    for(var r = 0;r<ayinput.length;r++){
    var firstitem = ayinput[r].split(" ");for(var m = r+1;m<ayinput.length;m++){

    var seconditem = ayinput[m].split(" ");
    var fps0 = (+firstitem[z])+(+seconditem[0]);var fps1 = (+firstitem[z])+(+seconditem[1]);

    if(fps0>=xy[0]*xy[1]){if((fps0<=lastspace)&&(seconditem[1]<=e) ){

        e = seconditem[1];lastspace= fps0;round =((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}

    if(fps1>=xy[0]*xy[1]){if((fps1<=lastspace)&&(seconditem[0]<=e)){

        e = seconditem[0];lastspace=fps1;round = ((temp[r][0]*temp[r][1])+(temp[m][0]*temp[m][1]));}}

    }if(z===0){z+=1;r-=1}
    }
    print(round);


Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that.  Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then:  at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$);  at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$);  the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.

For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.

NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.

//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
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;}}

//↑見なくていいよ！ここまで--------------------------------------------------
function Main(){
	var t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray();
		var count = 0;
		list.sort(function(a,b){
			return a - b;
		});
		for(var j = 0; j < N; j++){
			if(list[j] <= j + 1){
				count = j + 1;
			}
		}
		output[i] = count + 1;
	}
	myout(myconv(output,9));
}

'use strict';

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

let inputString = [];
let currentLine = 0;

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

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

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

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

const withTiming = callback => {
    const start = new Date();
    callback();
    console.log(`Took ${new Date() - start} ms`);
}

function main() {
    const n = Math.floor(readline());
    const inputs = [];

    for (let i = 0; i < n; i++) {
        const m = parseInt(readline());
        const grannies = readline().split(' ').map(granny => parseInt(granny));
        let possibleGrannies = m + 1, i = 0;
        grannies.sort((a, b) => b - a);

        while (grannies[i] >= possibleGrannies) {
            i++;
            possibleGrannies--;
        }

        console.log(possibleGrannies);
    }
}

//1 1 4 5 4 9

const processData = (lines) => {
  const n = +lines[0]
  for (let i=0; i<n; i++) {
    const arr = lines[i*2+2].split(' ').map(x => +x)
    arr.sort((a, b) => a-b)
    let acc = 1
    let buffer = 0
    for (let i=0; i<arr.length; i++) {

      if (arr[i] <= acc + buffer) {
        acc += buffer + 1
        buffer = 0
      } else {
        buffer++
      }
    }
    console.log(acc)
  }
}

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

function ladies (n, arr) {
    arr.sort((a, b) => a > b ? 1 : -1);
    let present = 1;
    let itr = 0;
    let j = n - 1;

    while (j >= 0 && itr < n) {
        let now = ((j - itr) + 1);
        if (arr[j] <= (now + present - 1)) {
            present += now;
            itr = j + 1;
            j = n - 1;
        }
        else {
            if ((itr === j) || (itr === n-1) || (itr > j)) return present;
            j -= 1;
        }
    }
    return present;
}

function processData(input) {
    let inpArr = input.split("\n");
    let n = parseInt(inpArr[0]);

    for (let i = 1; i < inpArr.length - 1; i += 2) {
        console.log(ladies(parseInt(inpArr[i]), inpArr[i+1].split(' ').map(val => parseInt(val))));
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

'use strict';

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

let inputString = [];
let currentLine = 0;

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

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

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

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

const withTiming = callback => {
    const start = new Date();
    callback();
    console.log(`Took ${new Date() - start} ms`);
}

function main() {
    const n = Math.floor(readline());
    const inputs = [];

    for (let i = 0; i < n; i++) {
        const m = parseInt(readline());
        const grannies = readline().split(' ').map(granny => parseInt(granny));
        let currentGrannies = 1, k = 0;
        grannies.sort();

        while(k < grannies.length) {
            if (grannies[k] <= currentGrannies) {
                currentGrannies++;
                k++;
            } else {
                let j = grannies[k];

                if (grannies[j] <= j + 1) {
                    currentGrannies = j + 2;
                    k = j + 1;
                } else {
                    k = grannies.length;
                }
            }
        }
        console.log(currentGrannies);
    }
}

//1 1 4 5 5 9

'use strict';

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

let inputString = [];
let currentLine = 0;

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

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

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

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

const withTiming = callback => {
    const start = new Date();
    callback();
    console.log(`Took ${new Date() - start} ms`);
}

function main() {
    const n = Math.floor(readline());
    const inputs = [];

    for (let i = 0; i < n; i++) {
        const m = parseInt(readline());
        const grannies = readline().split(' ').map(granny => parseInt(granny));
        let k = 0, result = grannies.length + 1;
        grannies.sort();

        while(k < grannies.length) {
            if (grannies[k] <= k + 1) {
                k++;
            } else {
                let j = grannies[k];

                if (grannies[j] <= j + 1) {
                    k = j + 1;
                } else {
                    result = k + 1;
                    k = grannies.length;
                }
            }
        }

        console.log(result);
    }
}

//1 1 4 5 4 9


Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols sitting on the i-th wire.  Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the i-th wire). Consequently all the birds on the i-th wire to the left of the dead bird get scared and jump up on the wire number i - 1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number i + 1, if there exists no such wire they fly away. Shaass has shot m birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots.

The first line of the input contains an integer n, (1 ≤ n ≤ 100). The next line contains a list of space-separated integers a1, a2, ..., an, (0 ≤ ai ≤ 100).  The third line contains an integer m, (0 ≤ m ≤ 100). Each of the next m lines contains two integers xi and yi. The integers mean that for the i-th time Shaass shoot the yi-th (from left) bird on the xi-th wire, (1 ≤ xi ≤ n, 1 ≤ yi). It's guaranteed there will be at least yi birds on the xi-th wire at that moment.

On the i-th line of the output print the number of birds on the i-th wire.

var n = +readline();
var a = ('0 ' + readline() + ' 0').split(' ').map(Number);
var m = +readline();
while( m-- ){
	+function(x, y){
		a[x-1] += y-1;
		a[x+1] += a[x]-y;
		a[x] = 0;
	}.apply(0, readline().split(' ').map(Number));
}
a.shift();
a.pop();
print(a.join('\n'));

ip = readline().split(" ");
n = parseInt(ip[0]);
A = readline().split(" ");
ip = readline().split(" ");
m = parseInt(ip[0]);
var B = new Array();
for (var i = 0; i < m; i++){
	B[i] = readline().split(" ");
	if (B[i][0]-1 > 0) A[B[i][0]-2] = parseInt(A[B[i][0]-2]) + parseInt(B[i][1]-1);
	if (B[i][0]-1 < n-1) A[B[i][0]] =  parseInt(A[B[i][0]])  + parseInt(A[B[i][0]-1]) - parseInt(B[i][1]);
	A[B[i][0]-1] = 0;
}
for (var i = 0; i < n; i++){
	write(A[i] + "\n");
}

var numberOfLines = readline()
  var lines = readline().split(' ').map(Number)
  var numberOfShoots = readline()

  for (var i = 0; i < numberOfShoots; i++) {
    var shootPositions = readline().split(' ').map(Number)
    var lineIndex = shootPositions[0] - 1
    var index = shootPositions[1]

    var currentNumberOfBirds = lines[lineIndex]

    if (lineIndex - 1 >= 0) lines[lineIndex - 1] += (index - 1)
    if (lineIndex + 1 < lines.length) lines[lineIndex + 1] += currentNumberOfBirds - index
    lines[lineIndex] = 0
  }

  for (var i = 0; i < lines.length; i++) {
    print(lines[i])
  }

;(function () {

	var n = +readline();
	var a = readline().split(' ').map(Number);
	var m = +readline();
	var x = [];
	for (var i = 0; i < m; i++) x.push( readline().split(' ').map(Number) );

	for (var i = 0; i < m; i++) {
		if (x[i][0] != 1) a[x[i][0] - 2] += x[i][1] - 1;
		if (x[i][0] != n) a[x[i][0]] += a[x[i][0] - 1] - x[i][1];
		a[x[i][0] - 1] = 0; // poor bird
	}

	print( a.join('\n') );

}).call(this);

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

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

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

function main() {
	var wireNum = parseInt(readline());
	var wires = tokenizeIntegers(readline());
	wires.unshift(null);

	var jumpNum = parseInt(readline());
	for (var i = 0; i < jumpNum; i += 1) {
		var integers = tokenizeIntegers(readline());
		var r = integers[0], c = integers[1];
		if (r > 1) {
			wires[r-1] += c-1;
		}
		if (r < wireNum) {
			wires[r+1] += wires[r]-c;
		}
		wires[r] = 0;
	}

	print(wires.slice(1).join('\n'));
}

main();

var n = readline(),
	a = readline().split(" ").map(Number),
	m = readline(), x = [];
for (var i = 0; i < m; i++) {
	x[i] = readline().split(" ").map(Number);
	var v = x[i][0] - 1;
	a[v + 1] += a[v] - x[i][1];
	a[v] = 0;
	a[v - 1] += x[i][1] - 1;
}
for (var i = 0; i < n; i++) {
	print(a[i]);
}

var wires = parseInt(readline());
var arr = readline().split(" ").map(Number);
var shoots = parseInt(readline());

for (var i = 0; i < shoots; i++) {
    var current = readline().split(" ").map(Number);
    var k = current[0];
    var n = current[1];

    if (k !== 1) {
        arr[k - 2] += n - 1; // arr[k - 2] is nothing but arr[(k - 1) - 1]
    }

    if (k !== arr.length) {
        arr[k] += arr[k - 1] - n; // arr[k] is nothing but arr[(k - 1) + 1]
    }

    arr[k - 1] = 0;
}

print(arr.join(" "));

const readline = require('readline');

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

let lineCounter = 1;
let birdsPerLine = [];
let shotsArr = [];
let numOfShots;

rl.on('line', (input) => {
    if (lineCounter === 1) {
        lineCounter++;
        return;
    }
    if (lineCounter === 2) {
        let line = input.split(' ');
        line.forEach(ele => {
            birdsPerLine.push(parseInt(ele));
        })
    } else if (lineCounter === 3) {
        numOfShots = parseInt(input);
        if (numOfShots === 0) {
            rl.close();
            solve(birdsPerLine, shotsArr);
            birdsPerLine.forEach(ele => {
                console.log(ele);
            })
        }
    } else if (lineCounter <= 3 + numOfShots) {
        let line = input.split(' ');
        shotsArr.push([parseInt(line[0]), parseInt(line[1])]);
        if (lineCounter === 3 + numOfShots) {
            rl.close();
            solve(birdsPerLine, shotsArr);
            birdsPerLine.forEach(ele => {
                console.log(ele);
            })
        }
    }
    lineCounter++;
});

const solve = (birdsPerLine, shotsArr) => {
    shotsArr.forEach(shot => {
        let line = shot[0];
        let shootedBird = shot[1];
        let currentBirds = birdsPerLine[line - 1];
        let leftBird = shootedBird - 1;
        let rightBirds = currentBirds - shootedBird;
        birdsPerLine[line - 1] = 0;
        if (birdsPerLine[line - 2] || birdsPerLine[line - 2] === 0) birdsPerLine[line - 2] += leftBird;
        if (birdsPerLine[line] || birdsPerLine[line] === 0) birdsPerLine[line] += rightBirds;
    });

}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

function print(s) {
  process.stdout.write(`${s}`);
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  // input
  const n = +readline();
  const a = readline().split(' ').map(x => parseInt(x));
  const m = +readline();
  for (let i = 0; i < m; i++) {
    const [x, y] = readline().split(' ').map(x => parseInt(x));
    if (x !== 1) {
      a[x-1-1] += y - 1;
    }
    if (x !== n) {
      a[x+1-1] += a[x-1] - y;
    }
    a[x-1] = 0;
  }
 // output
  a.forEach(x => print(`${x}\n`));
}

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

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

  if (c === 1) {
    c++;
    wires = d.split(' ').map(Number);
    return;
  }

  if (c == 2) {
    c++;
    return;
  }

  const [x, y] = d.split(' ').map(Number);
  let curr = x - 1;
  let up = curr - 1;
  let down = curr + 1;

  let birds = wires[curr];
  let upBirds = y - 1;
  let downBirds = birds - y;
  wires[curr] = 0;

  if (wires[up] !== undefined) {
    wires[up] = wires[up] + upBirds;
  }

  if (wires[down] !== undefined) {
    wires[down] = wires[down] + downBirds;
  }
  c++;
});

rl.on('close', () => {
  for (let i = 0; i < wires.length; i++) {
    console.log(wires[i]);
  }
});

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

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

  if (c === 1) {
    c++;
    wires = [0, ...d.split(' ').map(Number), 0];
    return;
  }

  if (c == 2) {
    c++;
    return;
  }

  const [x, y] = d.split(' ').map(Number);

  wires[x - 1] +=  y - 1;
  wires[x + 1] += wires[x] - y;
  wires[x] = 0;

  c++;
});

rl.on('close', () => {
  for (let i = 1; i < wires.length - 1; i++) {
    console.log(wires[i]);
  }
});

'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 readint() {
    let line = readline().split(' ').map(function(num) {
        return parseInt(num);
    });
    return line;
}

function readfloat() {
    let line = readline().split(' ').map(function(num) {
        return parseFloat(num);
    });
    return line;
}

function print(x) {
    console.log(x);
}

function write(x) {
    process.stdout.write(x);
}
function main() {
    let n = parseInt(readline());
    let a = readint();
    let m = parseInt(readline());
    let xy = [];
    for (let i = 0; i < m; i++) {
        let xly = readint();
        xy.push(xly);
    }
    for (let i = 0; i < m; i++) {

        let x = xy[i][0];
        let y = xy[i][1];
        x--;
        y--;
        if(x != 0) {
            a[x - 1] += y;
        }
        if(x != n - 1) {
            a[x + 1] += a[x] - y - 1;
        }
        a[x] = 0;
    }
    for (let i = 0; i < a.length; i++) {
        write(a[i] + "\n");
    }
}

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
const mapFunc = (arr) => {
  return arr.map((b) => parseInt(b));
}
let input = [];
readline.on('line', line => {
  input.push(line);
});
process.stdin.on('end', () => {
const n = parseInt(input[0], 10);
let a = input[1].split(' ');
a = a.map((b) => parseInt(b));
const m = parseInt(input[2], 10);
for (let i=3; i < m+3; i++) {
  let xy = input[i].split(' ');
  xy = mapFunc(xy);
  xy[0] -= 1;
  const wentUp = xy[1] - 1;
  const wentDown = parseInt(a[xy[0]], 10) - wentUp - 1;
  if (xy[0] > 0) {
    a[xy[0] - 1] = a[xy[0] - 1] + wentUp;
  }
  if (xy[0] < n-1) {
    a[xy[0] + 1] = a[xy[0] + 1] + wentDown;
  }
  a[xy[0]] = 0;
}
for (const e of a) {
  console.log(e);
}
});

var wires = parseInt(readline());
var arr = readline().split(" ").map(Number);
var shoots = parseInt(readline());

for (var i = 0; i < shoots; i++) {
    var current = readline().split(" ").map(Number);
    var k = current[0];
    var n = current[1];

    if (arr[(k -1) -1]) {
        arr[(k -1) -1] += n - 1;
    }

    if (arr[(k - 1) + 1]) {
        arr[(k - 1) + 1] += arr[k - 1] - n;
    }

    arr[k - 1] = 0;
}

print(arr.join(" "));

const readline = require('readline');

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

let lineCounter = 1;
let birdsPerLine = [];
let shotsArr = [];
let numOfShots;

rl.on('line', (input) => {
    if (lineCounter === 1) {
        lineCounter++;
        return;
    }
    if (lineCounter === 2) {
        let line = input.split(' ');
        line.forEach(ele => {
            birdsPerLine.push(parseInt(ele));
        })
    } else if (lineCounter === 3) {
        numOfShots = parseInt(input);
    } else if (lineCounter <= 3 + numOfShots) {
        let line = input.split(' ');
        shotsArr.push([parseInt(line[0]), parseInt(line[1])]);
        if (lineCounter === 3 + numOfShots) {
            rl.close();
            solve(birdsPerLine, shotsArr);
            birdsPerLine.forEach(ele => {
                console.log(ele);
            })
        }
    }
    lineCounter++;
});

const solve = (birdsPerLine, shotsArr) => {
    shotsArr.forEach(shot => {
        let line = shot[0];
        let shootedBird = shot[1];
        let currentBirds = birdsPerLine[line - 1];
        let leftBird = shootedBird - 1;
        let rightBirds = currentBirds - shootedBird;
        birdsPerLine[line - 1] = 0;
        if (birdsPerLine[line - 2] || birdsPerLine[line - 2] === 0) birdsPerLine[line - 2] += leftBird;
        if (birdsPerLine[line] || birdsPerLine[line] === 0) birdsPerLine[line] += rightBirds;
    });

}


Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 > c_1$$$, then to some other city $$$c_3 > c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k > c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey:  $$$c = [1, 2, 4]$$$;  $$$c = [3, 5, 6, 8]$$$;  $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of cities in Berland. The second line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ ($$$1 \le b_i \le 4 \cdot 10^5$$$), where $$$b_i$$$ is the beauty value of the $$$i$$$-th city.

Print one integer — the maximum beauty of a journey Tanya can choose.

NoteThe optimal journey plan in the first example is $$$c = [2, 4, 5]$$$.The optimal journey plan in the second example is $$$c = [1]$$$.The optimal journey plan in the third example is $$$c = [3, 6]$$$.

const processData = (lines) => {
  const b = lines[1].split(' ')
    .map((x, index) => x-index)
    .reduce((r, x, index) => {r[x] = (r[x] || 0) + (x + index); return r }, {})
  console.log(Math.max.apply(null, Object.values(b)))
}

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


Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!

The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, ) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively. Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.

Print the maximum total friendship factir that can be reached.

NoteIn the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.In the second sample test we can take all the friends.

var input = readline().split(" ").map(Number), n = input[0], d = input[1], arr = [];
for(var i = 0; i < n; i++){
    arr.push(readline().split(" ").map(Number));
}
var ans = 0;

arr.sort(function(a,b){return a[0]-b[0]});

var a = 0;
for(var i = 0; i < n; i++){
    arr[i][1] += a;
    a = arr[i][1];
}
delete a;

for(var i = 0; i < n; i++){
    var l = i;
    var r = n-1;

    while(r-l > 2){
        var m = Math.floor((r+l)/2);

        if(arr[m][0] < arr[i][0] + d){
            l = m;
        }
        else{
            r = m;
        }
    }

    while(l < r){
        if(arr[l][0] < arr[i][0] + d){
            l++;
        }
        else{
            r = l;
        }
    }

    if(arr[l][0] >= arr[i][0] + d){
        l--;
    }

    var numb;

    if(i == 0){
        numb = arr[l][1];
    }
    else{
        numb = arr[l][1] - arr[i-1][1]
    }

    var ans = Math.max(ans, numb);
}

write(ans);

var inp = readline().split(' ');
var n = parseInt(inp[0], 10);
var d = parseInt(inp[1], 10);
var friends = [];

for (var i = 0; i < n; i++) {
	inp = readline().split(' ');
	friends.push({
		m: parseInt(inp[0], 10),
		s: parseInt(inp[1], 10)
	});
}

friends = friends.sort(function (a, b) {
	return a.m - b.m;
});

var result = count(friends, d);

write(result);

function count(friends, d) {
	var maxF = 0;
	var m = 0;
	var s = 0;
	var f = friends[s].s;

	while (s < friends.length - 1) {
		s++;
		f += friends[s].s;
		if (friends[s].m - friends[m].m >= d) {
			maxF = Math.max(maxF, f - friends[s].s);
			while (friends[s].m - friends[m].m >= d) {
				f -= friends[m].s;
				m++;
			}
		}
	}
	maxF = Math.max(maxF, f);
	return maxF;
}

function main() {
    var line = readline().split(' ').map(Number);
    var n = line[0];
    var d = line[1];
    var friends = [];
    for(var i=0;i<n;i++){
        line = readline().split(' ').map(Number);
        friends.push(line);
    }
    friends.sort((a,b)=>a[0]-b[0]);
    var startIndex = 0;
    var max = 0;
    var sum = 0;
    for(var i=0;i<n;i++){
        while(friends[i][0] - friends[startIndex][0] >= d){
            sum -= friends[startIndex][1];
            startIndex++;

        }
        sum += friends[i][1];
        if(sum > max){
            max = sum;
        }
    }
    print(max)
}

main()

var parsedLine = readline().split(" ");
var n = parseInt(parsedLine[0]);
var d = parseInt(parsedLine[1]);

var friends = [];
for (var i = 0; i < n; i++) {
  parsedLine = readline().split(" ");
  friends.push({
    m: parseInt(parsedLine[0]),
    s: parseInt(parsedLine[1])
  });
}
friends.sort(function(f1, f2) { return f1.m - f2.m; });

var sums = [0];
friends.forEach(function(f, i) { sums.push(f.s + sums[i]); });

var max = 0;
friends.forEach(function(f, i, arr) {
  var j = binarySearch(i, arr.length, function(k) {
    return arr[k].m >= arr[i].m + d;
  });
  var sum = sums[j] - sums[i];
  max = sum > max ? sum : max;
});

print(max);

function binarySearch(start, end, callback) {
  while(end > start + 1) {
    var mid = start + parseInt((end-start)/2);
    if (callback(mid)) {
      end = mid;
    } else {
      start = mid;
    }
  }
  return end;
}

var input = readline().split(" ").map(Number), n = input[0], d = input[1], arr = [];
for(var i = 0; i < n; i++){
    arr.push(readline().split(" ").map(Number));
}
var ans = 0;

arr.sort(function(a,b){return a[0]-b[0]});

var a = 0;
for(var i = 0; i < n; i++){
    arr[i][1] += a;
    a = arr[i][1];
}
delete a;

for(var i = 0; i < n; i++){
    var l = i;
    var r = n-1;

    while(r-l > 2){
        var m = Math.floor((r+l)/2);

        if(arr[m][0] < arr[m][0] + d){
            l = m;
        }
        else{
            r = m;
        }
    }

    while(l < r){
        if(arr[l][0] < arr[i][0] + d){
            l++;
        }
        else{
            r = l;
        }
    }

    if(arr[l][0] >= arr[i][0] + d){
        l--;
    }

    var numb;

    if(i == 0){
        numb = arr[l][1];
    }
    else{
        numb = arr[l][1] - arr[i-1][1]
    }

    var ans = Math.max(ans, numb);
}

write(ans);

var inp = readline().split(' ');
var n = parseInt(inp[0], 10);
var d = parseInt(inp[1], 10);
var friends = [];

for (var i = 0; i < n; i++) {
	inp = readline().split(' ');
	friends.push({
		m: parseInt(inp[0], 10),
		s: parseInt(inp[1], 10)
	});
}

friends = friends.sort(function (a, b) {
	return a.m > b.m;
});

var result = count(friends, d);

write(result);

function count(friends, d) {
	var maxF = 0;
	var m = 0;
	var s = 0;
	var f = friends[s].s;

	while (s < friends.length - 1) {
		s++;
		f += friends[s].s;
		if (friends[s].m - friends[m].m >= d) {
			maxF = Math.max(maxF, f - friends[s].s);
			while (friends[s].m - friends[m].m >= d) {
				f -= friends[m].s;
				m++;
			}
		}
	}
	maxF = Math.max(maxF, f);
	return maxF;
}