$$$ \def\myred#1{\color{red}{\underline{\bf{#1}}}} \def\myblue#1{\color{blue}{\overline{\bf{#1}}}} $$$ $$$\def\RED{\myred{Red}} \def\BLUE{\myblue{Blue}}$$$You are given a sequence of $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$. Initially, all the elements of the sequence are unpainted. You can paint each number $$$\RED$$$ or $$$\BLUE$$$ (but not both), or leave it unpainted. For a color $$$c$$$, $$$\text{Count}(c)$$$ is the number of elements in the sequence painted with that color and $$$\text{Sum}(c)$$$ is the sum of the elements in the sequence painted with that color.For example, if the given sequence is $$$[2, 8, 6, 3, 1]$$$ and it is painted this way: $$$[\myblue{2}, 8, \myred{6}, \myblue{3}, 1]$$$ (where $$$6$$$ is painted red, $$$2$$$ and $$$3$$$ are painted blue, $$$1$$$ and $$$8$$$ are unpainted) then $$$\text{Sum}(\RED)=6$$$, $$$\text{Sum}(\BLUE)=2+3=5$$$, $$$\text{Count}(\RED)=1$$$, and $$$\text{Count}(\BLUE)=2$$$.Determine if it is possible to paint the sequence so that $$$\text{Sum}(\RED) > \text{Sum}(\BLUE)$$$ and $$$\text{Count}(\RED) < \text{Count}(\BLUE)$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3\le n\le 2\cdot 10^5$$$) — the length of the given sequence.  The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0\le a_i\le 10^9$$$) — the given sequence. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print YES if it is possible to paint the given sequence satisfying the above requirements, and NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).

NoteIn the first test case, there is no possible way to paint the sequence. For example, if you paint the sequence this way: $$$[\myblue{1},\myblue{2},\myred{3}]$$$ (where $$$3$$$ is painted red, $$$1$$$ and $$$2$$$ are painted blue) then $$$\text{Count}(\RED)=1 < \text{Count}(\BLUE)=2$$$, but $$$\text{Sum}(\RED)=3 \ngtr \text{Sum}(\BLUE)=3$$$. So, this is not a possible way to paint the sequence.In the second test case, a possible way to paint the sequence is described in the statement. We can see that $$$\text{Sum}(\RED)=6 > \text{Sum}(\BLUE)=5$$$ and $$$\text{Count}(\RED)=1 < \text{Count}(\BLUE)=2$$$.In the third test case, there is no possible way to paint the sequence. For example, if you paint the sequence this way: $$$[\myred{3},\myred{5},\myblue{4}, \myblue{2}]$$$ (where $$$3$$$ and $$$5$$$ are painted red, $$$4$$$ and $$$2$$$ are painted blue) then $$$\text{Sum}(\RED) = 8 > \text{Sum}(\BLUE) = 6$$$ but $$$\text{Count}(\RED) = 2 \nless \text{Count}(\BLUE) = 2$$$. So, this is not a possible way to paint the sequence.In the fourth test case, it can be proven that there is no possible way to paint the sequence satisfying sum and count constraints.

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;

function readline() {
    return input[currentline++];
}
var tc = parseInt(readline());
while(tc--)
{
    var n = parseInt(readline());
    var arr = readline().split(' ').map(Number);
    var poss = false;
    arr.sort((a,b)=>b-a);
    var sumRed = 0, sumBlue = arr[n-1];
    for(var i=0; i<parseInt((n-1)/2); i++)
    {
        sumBlue += arr[n-i-2];
        sumRed  += arr[i];
        if(sumRed > sumBlue)
        {
            poss = true;
            break;
        }
    }
    if(poss) console.log("YES");
    else console.log("NO");
}

'use strict';
const { throws } = require('assert');

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

module.exports = E;

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

const EPS = 1e-6;
const MOD = 1e9+7;

const calc = (arr)=>{
  arr.sort((a, b)=>a-b);
  let blue_sum = arr[0]+arr[1];
  let blue_cnt = 2;
  let red_sum = arr[arr.length-1];
  let bi = 2;
  let ri = arr.length-2;
  while (bi<ri && blue_sum>=red_sum){
    blue_sum += arr[bi];
    red_sum += arr[ri];
    bi++;
    ri--;
  }
  return red_sum>blue_sum
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let arr = ra();
      print(calc(arr) ? 'YES' : 'NO');
    }
}

E.calc = calc;

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
function readLine() {
    return inputString[currentLine++];
};
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
    // cmd(not powershell): node cp.js < input.txt
});

function main() {
    let t = parseInt(readLine());
    while (t-- > 0) {
        solve();
    }
}
function solve() {
    readLine();
    let input = readLine().split(" ").map(i => parseInt(i)).sort((a,b)=>a-b);
    const rarr = [], barr = [];
    let l = 0; r = input.length - 1;
    let rsum = 0; bsum = 0;
    bsum += input[l];
    barr.push(input[l++]);
    while (l < r) {
        bsum += input[l];
        rsum += input[r];
        barr.push(input[l]);
        rarr.push(input[r]);
        if (rsum > bsum && rarr.length < barr.length) {
            console.log("YES");
            return;
        } else {
            l++;
            r--;
        }
    }
    console.log("NO");
}

const fs = require('fs');

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

let currentline = 0;

function readline() {
    return input[currentline++];
}

let str = readline();

for(let q=1;q<=str;q++) {
const inp = readline()
   let data = readline().split(' ').map(numb => parseInt(numb));
   data.sort((a,b) => a-b);
   let sum = [];
   sum[-1] = 0;
   for(let i=0; i<inp; i++) {
       sum[i]=sum[i-1]+data[i]
   }
   let mid = Math.floor(inp/2)+1;
   mid--;
   let result = "NO";
   let j = 2;

   for(var i=1;i<=mid;i++) {
       if(sum[i] < (sum[inp-1]-sum[inp-j])) result = "YES";
       j++;
   }
   console.log(result);
}

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 q=1;q<=T;q++) {
   var n = readline()
   var a = readline().split(' ').map(w => parseInt(w));
    // var a =[3, 5, 4, 2]
    // var n = a.length;
   a.sort(function(ar,br) { return ar-br })
   var sum = []
   sum[-1] = 0;
   for(var i=0;i<n;i++) {
       sum[i]=sum[i-1]+a[i]
   }
   var mid = Math.floor(n/2)+1;
   mid--;
   var ok = false;
   var j = 2;

   for(var i=1;i<=mid;i++) {
       if(sum[i] < (sum[n-1]-sum[n-j])) ok = true;
       j++;
   }
   console.log(ok ? 'YES' : 'NO');
   //var [n,s] =[7,0]
//    var sum = 0;
//    var j = n*n;
//    for(var i=1;i<=n+1;i++) {
//        var nw = sum
//        if(sum+j <= s && s-sum ) {
//            sum += j;
//        }
//        else {
//            i--;
//            break;
//        }
//    }
//    if(i > n+1) i--;
//    console.log(i);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

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

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);

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

        let R, B;

        if (n % 2 === 0) {
            let div = (n / 2) - 1;
            R = arr.slice(0, div);
            B = arr.slice(div + 1, n);
        } else {
            R = arr.slice(0, Math.floor(n / 2));
            B = arr.slice(Math.floor(n / 2), n);
        }

        let sumR = R.reduce((a, b) => a + b, 0);
        let sumB = B.reduce((a, b) => a + b, 0);

        output(sumR > sumB ? 'YES': 'NO');
    }
}

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

let currentline = 0;
function readline(){
    return input[currentline++];
}
let t = +readline();
let result = 0;
while(t--){
    let n = +readline();
    let arr = readline().split(' ').map(x=>+x);
    console.log(`${solve(arr, n)}`)
}

function solve(nums, n){
    if(n < 3) return 'NO';

    nums.sort((a, b)=>a-b);
    let redSum = nums[n-1];
    let blueSum = nums[0] + nums[1];
    if(redSum > blueSum) return 'YES';
    let l = 2;
    let r = n-2;

    while(l < r){
        blueSum += nums[l];
        redSum += nums[r];
        l++;
        r--;
        if(redSum > blueSum) return 'YES';
    }
    return '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 k = lines[i].split(' ').map(Number).sort(function(a, b){return a - b});
            var blue = k[0] + k[1];
            var red = k[n - 1];
            var l = 2, r = n - 2;
            var flag = false;
            while(l < r){
                if(red > blue){
                    flag = true;
                    break;
                }
                blue += k[l], red +=k[r];
                l++;
                r--;
            }
            console.log(flag || red > blue ? 'YES':'NO');
        }
    }
});

 var tests = parseInt(readline());
    var n, s;
    for (var t=0; t < tests; t++) {
        n = parseInt(readline());
        s = readline().split(' ').map(x=>parseInt(x));
        s.sort((a, b)=>a-b);
        var suma = 0, sumb = s[0];
        var a = n-1, b = 1;
        while ( b < a && suma <= sumb ) {
            suma += s[a];
            sumb += s[b];
            b++;
            a--;
        }
        if (suma > sumb) {
            print('YES');
        } else {
            print('NO');
        }
    }

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;

function readline() {
    return input[currentline++];
}
var tc = parseInt(readline());
while(tc--)
{
    var n = parseInt(readline());
    var arr = readline().split(' ').map(Number);
    var poss = false;
    arr.sort((a,b)=>b-a);
    var sumRed = 0, sumBlue = arr[n-1];
    for(var i=1; i<parseInt((n-1)/2); i++)
    {
        sumBlue += arr[n-i-2];
        sumRed  += arr[i];
        if(sumRed > sumBlue)
        {
            poss = true;
            break;
        }
    }
    if(poss) console.log("YES");
    else console.log("NO");
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;

function readline() {
    return input[currentline++];
}
var tc = parseInt(readline());
while(tc--)
{
    var n = parseInt(readline());
    var arr = readline().split(' ').map(Number);
    var sumBlue = 0, sumRed = 0;
    var poss = false;
    for(var i=0;i<n;i++)
    {
        sumBlue += arr[i];
    }
    arr.sort((a,b)=>b-a);
    for(var i=0; i<n; i++)
    {
        let countRed = i+1, countBlue = n-i-1;
        sumBlue -= arr[i]; sumRed += arr[i];
        if(countRed < countBlue && sumRed > sumBlue)
        {
            poss = true;
            break;
        }
    }
    if(poss) console.log("YES");
    else console.log("NO");
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;

function readline() {
    return input[currentline++];
}
var tc = parseInt(readline());
while(tc--)
{
    var n = parseInt(readline());
    var arr = readline().split(' ').map(Number);
    var sumBlue = 0, sumRed = 0;
    var poss = false;
    for(var i=0;i<n;i++)
    {
        sumBlue += arr[i];
    }
    arr.sort((a,b)=>b-a);
    for(var i=0; i<n; i++)
    {
        let countRed = i+1, countBlue = n-i-1;
        if(countRed < countBlue && sumRed > sumBlue)
        {
            poss = true;
            break;
        }
    }
    if(poss) console.log("YES");
    else console.log("NO");
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;

function readline() {
    return input[currentline++];
}
var tc = parseInt(readline());
console.log(tc);
while(tc--)
{
    var n = parseInt(readline());
    var arr = readline().split(' ').map(Number);
    var sumBlue = 0, sumRed = 0;
    var poss = false;
    for(var i=0;i<n;i++)
    {
        sumBlue += arr[i];
    }
    arr.sort((a,b)=>b-a);
    for(var i=0; i<n; i++)
    {
        let countRed = i+1, countBlue = n-i-1;
        sumBlue -= arr[i]; sumRed += arr[i];
        if(countRed < countBlue && sumRed > sumBlue)
        {
            poss = true;
            break;
        }
    }
    if(poss) console.log("YES");
    else console.log("NO");
}

'use strict';
const { throws } = require('assert');

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

module.exports = E;

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

const EPS = 1e-6;
const MOD = 1e9+7;

const calc = (arr)=>{
  arr.sort((a, b)=>a-b);
  let blue_sum = arr[0]+arr[1];
  let blue_cnt = 2;
  let red_sum = arr[arr.length-1];
  let bi = 2;
  let ri = arr.length-2;
  while (bi<ri && blue_sum>=red_sum){
    bi++;
    ri--;
  }
  return red_sum>blue_sum
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let arr = ra();
      print(calc(arr) ? 'YES' : 'NO');
    }
}

E.calc = calc;

'use strict';
const { throws } = require('assert');

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

module.exports = E;

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

const EPS = 1e-6;
const MOD = 1e9+7;

const calc = (arr)=>{
  arr.sort((a, b)=>a-b);
  return arr[0]+arr[1]<arr[arr.length-1];
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let arr = ra();
      print(calc(arr) ? 'YES' : 'NO');
    }
}

E.calc = calc;

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
function readLine() {
    return inputString[currentLine++];
};
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
    // cmd(not powershell): node cp.js < input.txt
});

function main() {
    let t = parseInt(readLine());
    while (t-- > 0) {
        solve();
    }
}
function solve() {
    readLine();
    let input = readLine().split(" ").map(i => parseInt(i)).sort();
    const rarr = [], barr = [];
    let l = 0; r = input.length - 1;
    let rsum = 0; bsum = 0;
    bsum += input[l];
    barr.push(input[l++]);
    while (l < r) {
        bsum += input[l];
        rsum += input[r];
        barr.push(input[l]);
        rarr.push(input[r]);
        if (rsum > bsum && rarr.length < barr.length) {
            console.log("YES");
            return;
        } else {
            l++;
            r--;
        }
    }
    console.log("NO");
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
function readLine() {
    return inputString[currentLine++];
};
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
    // cmd(not powershell): node cp.js < input.txt
});

function main() {
    let t = parseInt(readLine());
    while (t--) {
        solve();
    }
}
function solve() {
    readLine();
    let input = readLine().split(" ").map(i => parseInt(i)).sort();
    const rarr = [], barr = [];
    let l = 0; r = input.length - 1;
    let rsum = 0; bsum = 0;
    bsum += input[l];
    barr.push(input[l++]);
    while (l < r) {
        bsum += input[l];
        rsum += input[r];
        barr.push(input[l]);
        rarr.push(input[r]);
        if (rsum > bsum && rarr.length < barr.length) {
            console.log("YES");
            break;
        } else {
            l++;
            r--;
        }
    }
    console.log("NO");
}

let input = "";
process.stdin.on("data", (chunk) => {
  input += chunk;
});

 process.stdin.on("end", () => {
  let lines = input.trim().split(" ");
  qualityVSQuantity(lines)

 })

function findBestCase(arr) {
    var sortedArr = arr.sort((a, b) => a - b);
    var maxElem = sortedArr[sortedArr.length - 1];
    var blueArr = ''
    var redArr = [];
    redArr[0] =(sortedArr[sortedArr.length - 1]);
    var sumOfBlue = 0;
    var sumOfRed = maxElem;

    for (var i = 0; i < arr.length; i++) {
      if (arr[i] < maxElem && sumOfBlue < maxElem) {
        if (blueArr.split(" ").length === 2) {
          var item = Math.max(blueArr.split(" ")[0], blueArr.split(" ")[1]);
          blueArr = item;
        }
        blueArr = blueArr + ' ' + arr[i]
      }
    }
    if (blueArr.split(" ").length) sumOfBlue = blueArr.split(" ").reduce(function (a, b) {return  +a + +b});
    if (sumOfBlue > sumOfRed) findBestCase(arr.filter(function(el) {return el !== maxElem}));
    else if (sumOfRed > sumOfBlue && redArr.length < blueArr.split(" ").length) console.log("YES");
    else console.log("NO");
  }

function qualityVSQuantity (a) {
    if (a.length <= 1) {
    console.log("NO");
    }
    findBestCase(a);
  }

let input = "";
process.stdin.on("data", (chunk) => {
  input += chunk;
});

 process.stdin.on("end", () => {
  let lines = input.trim().split(" ");
  qualityVSQuantity(lines)

 })

function findBestCase(arr) {
    var sortedArr = arr.sort((a, b) => a - b);
    var maxElem = sortedArr[sortedArr.length - 1];
    var blueArr = ''
    var redArr = [];
    redArr[0] =(sortedArr[sortedArr.length - 1]);
    var sumOfBlue = 0;
    var sumOfRed = maxElem;

    for (var i = 0; i < arr.length; i++) {
      if (arr[i] < maxElem && sumOfBlue < maxElem) {
        if (blueArr.length === 2) {
          var item = Math.max(blueArr[0], blueArr[1]);
          blueArr = item;
        }
        blueArr = blueArr + ' ' + arr[i]
      }
    }
    if (blueArr.split(" ").length) sumOfBlue = blueArr.split(" ").reduce(function (a, b) {return  a + b});

    if (sumOfBlue > sumOfRed) findBestCase(arr.filter(function(el) {return el !== maxElem}));
    else if (sumOfRed > sumOfBlue && redArr.length < blueArr.length) console.log("YES");
    else console.log("NO");
  }

function qualityVSQuantity (a) {
    if (a.length <= 1) {
    console.log("NO");
    }
    findBestCase(a);
  }

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 q=1;q<=T;q++) {
   var n = readline()
   var a = readline().split(' ').map(w => parseInt(w));
    // var a =[3, 5, 4, 2]
    // var n = a.length;
   a.sort(function(ar,br) { return ar-br })
   var sum = []
   sum[-1] = 0;
   for(var i=0;i<n;i++) {
       sum[i]=sum[i-1]+a[i]
   }
   var mid = Math.floor(n/2)+1;
   mid--;
   var ok = false;
   var j = 2;

   for(var i=1;i<=mid;i++) {
       if(sum[i] < (sum[n-1]-sum[n-j])) ok = true;
   }
   console.log(ok ? 'YES' : 'NO');
   //var [n,s] =[7,0]
//    var sum = 0;
//    var j = n*n;
//    for(var i=1;i<=n+1;i++) {
//        var nw = sum
//        if(sum+j <= s && s-sum ) {
//            sum += j;
//        }
//        else {
//            i--;
//            break;
//        }
//    }
//    if(i > n+1) i--;
//    console.log(i);
}

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 q=1;q<=T;q++) {
   var n = readline()
   var a = readline().split(' ').map(w => parseInt(w));
//    var a =[1,2,3]
//    var n = a.length;
   a.sort(function(ar,br) { return ar-br })
   var sum = []
   sum[-1] = 0;
   for(var i=0;i<n;i++) {
       sum[i]=sum[i-1]+a[i]
   }
   var mid = Math.floor(n/2)+1;
   mid--;
   var ok = false;

   for(var i=mid;i<n;i++) {
       //console.log(sum[i], sum[n-1])
       if(sum[i] < (sum[n-1]-sum[i])) ok = true;
   }
   console.log(ok ? 'YES' : 'NO');
   //var [n,s] =[7,0]
//    var sum = 0;
//    var j = n*n;
//    for(var i=1;i<=n+1;i++) {
//        var nw = sum
//        if(sum+j <= s && s-sum ) {
//            sum += j;
//        }
//        else {
//            i--;
//            break;
//        }
//    }
//    if(i > n+1) i--;
//    console.log(i);
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

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

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);

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

        let R, B;

        if (n % 2 === 0) {
            let div = (n / 2) - 1;
            R = arr.slice(0, div);
            B = arr.slice(div, n);
        } else {
            R = arr.slice(0, Math.floor(n / 2));
            B = arr.slice(Math.floor(n / 2), n);
        }

        let sumR = R.reduce((a, b) => a + b, 0);
        let sumB = B.reduce((a, b) => a + b, 0);

        output(sumR > sumB ? 'YES': 'NO');
    }
}


Little Dormi received a histogram with $$$n$$$ bars of height $$$a_1, a_2, \ldots, a_n$$$ for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking.To modify the histogram, Little Dormi is able to perform the following operation an arbitrary number of times: Select an index $$$i$$$ ($$$1 \le i \le n$$$) where $$$a_i>0$$$, and assign $$$a_i := a_i-1$$$.Little Dormi defines the ugliness score of his histogram (after performing some number of operations) as the sum of the vertical length of its outline and the number of operations he performed on it. And to make the histogram as perfect as possible, he would like to minimize the ugliness score after modifying it with some number of operations.However, as his histogram is very large, Little Dormi is having trouble minimizing the ugliness score, so as Little Dormi's older brother, help him find the minimal ugliness.Consider the following example where the histogram has $$$4$$$ columns of heights $$$4,8,9,6$$$:  The blue region represents the histogram, and the red lines represent the vertical portion of the outline. Currently, the vertical length of the outline is $$$4+4+1+3+6 = 18$$$, so if Little Dormi does not modify the histogram at all, the ugliness would be $$$18$$$.However, Little Dormi can apply the operation once on column $$$2$$$ and twice on column $$$3$$$, resulting in a histogram with heights $$$4,7,7,6$$$:  Now, as the total vertical length of the outline (red lines) is $$$4+3+1+6=14$$$, the ugliness is $$$14+3=17$$$ dollars. It can be proven that this is optimal.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 4 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$4 \cdot 10^5$$$.

For each test case output one integer, the minimal ugliness Little Dormi can achieve with the histogram in that test case.

NoteExample $$$1$$$ is the example described in the statement.The initial histogram for example $$$2$$$ is given below:  The ugliness is currently $$$2+1+6+3+4=16$$$.By applying the operation once on column $$$1$$$, six times on column $$$3$$$, and three times on column $$$4$$$, we can end up with a histogram with heights $$$1,1,1,1,0,0$$$:  The vertical length of the outline is now $$$1+1=2$$$ and Little Dormi made $$$1+6+3=10$$$ operations, so the final ugliness is $$$2+10=12$$$, which can be proven to be optimal.

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 06/13/21 noon

const solve = (n, a) => {
    let res = ugliness(a);
    for (let i = 0; i < n; i++) {
        if (i + 1 < n && a[i] <= a[i + 1]) continue;
        if (i - 1 >= 0 && a[i] <= a[i - 1]) continue;
        let h = 0;
        if (i - 1 >= 0) h = mx(h, a[i - 1]);
        if (i + 1 < n) h = mx(h, a[i + 1]);
        if (a[i] > h) res -= a[i] - h;
    }
    pr(res);
};

// my code
const ugliness = (A) => {
    let a = [...A];
    a.unshift(0);
    a.push(0);
    let n = a.length;
    let sum = 0;
    let pre = a[0];
    for (let i = 1; i < n; i++) {
        let tmp = abs(a[i] - pre);
        sum += tmp;
        pre = a[i];
    }
    return sum;
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i + 1]);
            i += 2;
        }
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 06/13/21 noon

const solve = (n, a) => {
    let res = ugliness(a);
    for (let i = 0; i < n; i++) {
        let max = 0;
        if (i - 1 >= 0) max = mx(max, a[i - 1]);
        if (i + 1 < n) max = mx(max, a[i + 1]);
        if (a[i] > max) res -= a[i] - max;
    }
    pr(res);
};

const ugliness = (A) => {
    let a = [...A];
    a.unshift(0);
    a.push(0);
    let n = a.length;
    let sum = 0;
    let pre = a[0];
    for (let i = 1; i < n; i++) {
        let tmp = abs(a[i] - pre);
        sum += tmp;
        pre = a[i];
    }
    return sum;
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i + 1]);
            i += 2;
        }
    });
};

main()

"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 n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    if (n === 1) {
      console.log(arr[0]);
      continue;
    }
    let sum = arr[0] + arr[n - 1];
    for (let i = 1; i < n; i++) {
      sum += Math.abs(arr[i] - arr[i - 1]);
    }
    let r = 0;
    for (let i = 1; i < n - 1; i++) {
      if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {
        r += (arr[i] - Math.max(arr[i - 1], arr[i + 1])) * 2;
        sum += arr[i] - Math.max(arr[i - 1], arr[i + 1]);
      }
    }
    if (arr[0] > arr[1]) {
      r += (arr[0] - arr[1]) * 2;
      sum += arr[0] - arr[1];
    }
    if (arr[n - 1] > arr[n - 2]) {
      r += (arr[n - 1] - arr[n - 2]) * 2;
      sum += arr[n - 1] - arr[n - 2];
    }
    console.log(sum - r);
  }
};
solve();

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

const getLine = (function () {
    const getLineGen = (async function* () {
        for await (const line of rl) {
            yield line;
        }
    })();
    return async () => ((await getLineGen.next()).value);
})();

let solve = async () => {
    const nsc = parseInt(await getLine());
    for(let sc = 0; sc < nsc; sc++) {
        const n = parseInt(await getLine());
        const g = (await getLine()).split(' ').map(num => parseInt(num));
        g.unshift(0);
        g.push(0);
        let ugly = 0;
        for(let i = 1; i <= n; i++) {
            ugly += Math.abs(g[i] - g[i - 1]);
            if (g[i] > g[i-1] && g[i] > g[i+1]) {
                ugly -= Math.min(g[i] - g[i-1], g[i] - g[i+1]);
            }
        }
        ugly += g[n];
        console.log(ugly);
    }
}

solve();

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 06/13/21 noon
 * https://codeforces.com/contest/1534/problem/B
 */
const solve = (n, a) => {
    // pr(a)
    let m = counter(a);
    let min = Number.MAX_SAFE_INTEGER;
    let max = 0;
    for(const e of a) {
        max = mx(max, e);
        if (e != 0) min = mi(min, e);
    }
    let op = 0;
    let curMax = max;
    let ugly = ugliness(a);
    let res = ugly;
    while(curMax >= min) {
        // pr(curMax);
        for (let i = 0; i < n; i++) {
            if (a[i] > curMax) {
                a[i]--;
                op++;
                // if (i == 0) {
                //     if (a[i] > a[i + 1]) ugly--;
                // } else if (i == n - 1) {
                //     if (a[i] > a[i - 1]) ugly--;
                // } else {
                //     if (a[i] > a[i - 1] && a[i] > a[i + 1]) ugly--;
                // }
            }
        }
        let curUg = ugliness(a);
        // pr(a, curUg, op);
        res = mi(res, curUg + op);
        curMax--;
    }
    pr(res);
};

const ugliness = (A) => {
    let a = [...A];
    a.unshift(0);
    a.push(0);
    let n = a.length;
    let sum = 0;
    let pre = a[0];
    // pr(a);
    for (let i = 1; i < n; i++) {
        let tmp = abs(a[i] - pre);
        sum += tmp;
        pre = a[i];
        // pr(a[i], tmp);
    }
    return sum;
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i + 1]);
            i += 2;
        }
    });
};

main()

///////////////////////////////// pre-define ////////////////////////////////////////////////////////////////////////////////
const pr = console.log;
const mi = Math.min;
const mx = Math.max;
const mxll = (...args) => args.reduce((m, e) => e > m ? e : m);
const mill = (...args) => args.reduce((m, e) => e < m ? e : m);
const sqll = (v) => { if (v < 0n) throw 'negative input'; if (v < 2n) return v; const dfs = (n, x0) => { let x1 = ((n / x0) + x0) >> 1n; if (x0 === x1 || x0 === (x1 - 1n)) return x0; return dfs(n, x1); }; return dfs(v, 1n); }; // has >> 0
const abs = Math.abs;
const fl = Math.floor;
const ce = Math.ceil;
const sq = Math.sqrt;
const lge = Math.log;
const lg10 = Math.log10;
const ll = BigInt;
const combination = (m, n) => { return factorial(m, n) / factorial(n, n); };
const factorial = (m, n) => { let num = 1n; let cnt = 0; for (let i = ll(m); i > 0; i--) { if (cnt == n) break; num *= i; cnt++; } return num; };
const gcd = (a, b) => b == 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a / gcd(a, b)) * b;
const bitCount = (n) => { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; };
const powmod = (a, b, mod) => { let r = 1n; while (b > 0n) { if (b % 2n == 1) r = r * a % mod; b >>= 1n; a = a * a % mod; } return r; };
const amax = (a) => mx.apply(Math, a);
const amin = (a) => mi.apply(Math, a);
const sm = (a) => a.reduce(((x, y) => x + y), 0);
const aeq = (a, b) => JSON.stringify(a) == JSON.stringify(b);
const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
const stin = (a) => a.sort((x, y) => x - y);
const stde = (a) => a.sort((x, y) => y - x);
const sortPart = (a, k) => { let l = a.slice(0, k); l.sort((x, y) => x - y); let r = a.slice(k); return l.concat(r); }; // sort first kth
const initialize2DArrayNew = (m, n) => { let data = []; for (let i = 0; i < m; i++) { let tmp = Array(n).fill(0); data.push(tmp); } return data; };
const stmkey_in = (m) => new Map([...m].sort((x, y) => x[0] - y[0]));
const stmkey_de = (m) => new Map([...m].sort((x, y) => y[0] - x[0]));
const stmvalue_in = (m) => new Map([...m].sort((x, y) => x[1] - y[1]));
const stmvalue_de = (m) => new Map([...m].sort((x, y) => y[1] - x[1]));
const counter = (a_or_s) => { let map = new Map(); for (const i of a_or_s) map.set(i, map.get(i) + 1 || 1); return map; };
const counter_value_in_indexA_in = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).push(i); } return m; };
const counter_value_in_indexA_de = (a_or_s) => { let m = new Map(); let n = a_or_s.length; for (let i = 0; i < n; i++) { if (!m.has(a_or_s[i])) m.set(a_or_s[i], []); m.get(a_or_s[i]).unshift(i); } return m; };
const reverse2 = (s) => { let res = ""; for (let i = s.length - 1; i >= 0; i--) { res += s[i]; } return res; };
const isPalindrome = (s) => { let n = s.length; let i = 0; let j = n - 1; while (i < j) { if (s[i++] != s[j--]) return false; } return true; };
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * 06/13/21 noon
 * https://codeforces.com/contest/1534/problem/B
 */
const solve = (n, a) => {
    // pr(a)
    let m = counter(a);
    let min = Number.MAX_SAFE_INTEGER;
    let max = 0;
    for(const e of a) {
        max = mx(max, e);
        if (e != 0) min = mi(min, e);
    }
    let op = 0;
    let curMax = max - 1;
    let ugly = ugliness(a);
    let res = ugly;
    while(curMax >= min) {
        // pr(curMax);
        for (let i = 0; i < n; i++) {
            if (a[i] > curMax) {
                a[i]--;
                op++;
                // if (i == 0) {
                //     if (a[i] > a[i + 1]) ugly--;
                // } else if (i == n - 1) {
                //     if (a[i] > a[i - 1]) ugly--;
                // } else {
                //     if (a[i] > a[i - 1] && a[i] > a[i + 1]) ugly--;
                // }
            }
        }
        let curUg = ugliness(a);
        // pr(a, curUg, op);
        res = mi(res, curUg + op);
        curMax--;
    }
    pr(res);
};

const ugliness = (A) => {
    let a = [...A];
    a.unshift(0);
    a.push(0);
    let n = a.length;
    let sum = 0;
    let pre = a[0];
    // pr(a);
    for (let i = 1; i < n; i++) {
        let tmp = abs(a[i] - pre);
        sum += tmp;
        pre = a[i];
        // pr(a[i], tmp);
    }
    return sum;
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = input[0][0];
        let i = 1;
        while (t--) {
            solve(input[i][0], input[i + 1]);
            i += 2;
        }
    });
};

main()

// pr(ugliness([4, 8, 9, 6]), 0)
// pr(ugliness([4, 8, 8, 6]), 1)
// pr(ugliness([4, 7, 7, 6]), 3)

"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 n = parseInt(readline());
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    let sum = arr[0] + arr[n - 1];
    for (let i = 1; i < n; i++) {
      sum += Math.abs(arr[i] - arr[i - 1]);
    }
    let r = 0;
    for (let i = 1; i < n - 1; i++) {
      if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {
        r += (arr[i] - Math.max(arr[i - 1], arr[i + 1])) * 2;
        sum += arr[i] - Math.max(arr[i - 1], arr[i + 1]);
      }
    }
    if (arr[0] > arr[1]) {
      r += (arr[0] - arr[1]) * 2;
      sum += arr[0] - arr[1];
    }
    if (arr[n - 1] > arr[n - 2]) {
      r += (arr[n - 1] - arr[n - 2]) * 2;
      sum += arr[n - 1] - arr[n - 2];
    }
    console.log(sum - r);
  }
};
solve();


Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.Mr. Scrooge's signature can be represented as a polyline A1A2... An. Scrooge signs like that: first it places a pen at the point A1, then draws a segment from point A1 to point A2, then he draws a segment from point A2 to point A3 and so on to point An, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — 50 millimeters per second.Scrooge signed exactly k papers throughout his life and all those signatures look the same.Find the total time Scrooge wasted signing the papers.

The first line contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ 1000). Each of the following n lines contains the coordinates of the polyline's endpoints. The i-th one contains coordinates of the point Ai — integers xi and yi, separated by a space. All points Ai are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters.

Print one real number — the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10 - 6.

print(function(n, k) {

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

	var d = 0;
	a.reduce(function(a, b) {
		var x = a[0] - b[0];
		var y = a[1] - b[1];
		d += Math.sqrt(x * x + y * y);
		return b;
	});

	return d * k / 50;

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

;(function () {
	var n = readline().split(' ');
	var k = +n[1];
	n = +n[0];

	var s = readline().split(' ').map(Number);
	var t = 0;
	for (var i = 1; i < n; i++) {
		var a = readline().split(' ').map(Number);

		t += Math.pow( Math.pow(a[0] - s[0], 2) + Math.pow(a[1] - s[1], 2), 0.5);

		s = a;
	}

	print(t * k / 50);

}).call(this);

var nk = readline();
nk = nk.split(" ");
nk[0] = parseInt(nk[0]);
nk[1] = parseInt(nk[1]);
var v = 50, s = 0;
var xy0 = readline();
xy0 = xy0.split(" ");
xy0[0] = parseInt(xy0[0]);
xy0[1] = parseInt(xy0[1]);
for(var i = 1; i < nk[0]; ++i)
{
    var xy = readline();
    xy = xy.split(" ");
    xy[0] = parseInt(xy[0]);
    xy[1] = parseInt(xy[1]);
    s += Math.sqrt(Math.pow((xy[0] - xy0[0]), 2) + Math.pow((xy[1] - xy0[1]), 2));
    xy0 = xy;
}
print(((s / v)*nk[1]).toFixed(6));


You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0.You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set cu = x.It is guaranteed that you have to color each vertex in a color different from 0.You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).

The first line contains a single integer n (2 ≤ n ≤ 104) — the number of vertices in the tree. The second line contains n - 1 integers p2, p3, ..., pn (1 ≤ pi < i), where pi means that there is an edge between vertices i and pi. The third line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ n), where ci is the color you should color the i-th vertex into. It is guaranteed that the given graph is a tree.

Print a single integer — the minimum number of steps you have to perform to color the tree into given colors.

NoteThe tree from the first sample is shown on the picture (numbers are vetices' indices):On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):On seond step we color all vertices in the subtree of vertex 5 into color 1:On third step we color all vertices in the subtree of vertex 2 into color 1:The tree from the second sample is shown on the picture (numbers are vetices' indices):On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):On second step we color all vertices in the subtree of vertex 3 into color 1:On third step we color all vertices in the subtree of vertex 6 into color 2:On fourth step we color all vertices in the subtree of vertex 4 into color 1:On fith step we color all vertices in the subtree of vertex 7 into color 3:

var n = Number(readline());
var tree = [];
var arr = readline().split(' ').map(Number);
for (var i = 0; i < n - 1; i++) {
	if (!tree[arr[i] - 1]) {
		tree[arr[i] - 1] = [];
	}
	tree[arr[i] - 1].push(i+1);
}
var color = readline().split(' ').map(Number);

var result = 0;
var curColor = 0;

//print(JSON.stringify(tree));

function order(i, curColor) {
	if (color[i] !== curColor) {
		result += 1;
		curColor = color[i];
	}
	if (tree[i]) {
		for (var j = 0; j < tree[i].length; j++) {
			var child = tree[i][j];
			order(child, curColor);
		}
	}
}

order(0, 0);
print(result);

var n=Number(readline())
var P=readline().split(' ').map(Number)
var C=readline().split(' ').map(Number)
var T=new Array(n)
for (var i=0; i<n; ++i) T[i]={}

for (var i=0; i<P.length; ++i) {
	var q = P[i]-1, w = i + 1;
	T[q][w] = 1;
	T[w][q] = 1;
}

var R=1

function walk(v, p) {
	// print(v, p, C[v], C[p])
	if (p >= 0 && C[v] !== C[p]) ++R;

	for (var k in T[v]) {
		if (k != p) {
			walk(k, v)
		}
	}
}

walk(0, -1)
print(R)

// print(JSON.stringify(T))

function main(){
    function solution(n, p, c){
        var graph = [];
        var rootNode = 1;
        var visited = new Set();
        var currentNode = 1;
        var queue = [];
        var currentColors = []; // [0, 0, 0, ..., 0]
        var endingColors = [];
        var steps = 0;
        var colorToPaint = "";

        // var graph = [
        // 	[],
        // 	[2, 5],
        // 	[4, 3],
        // 	[],
        // 	[],
        // 	[6],
        // 	[]
        // ];

        function colorGraph(someNode, someColor){
            if(visited.has(someNode)){
                return;
            }

            currentColors[someNode] = someColor;
            visited.add(someNode);

            var childNodes = graph[someNode];

            if(!childNodes){
                return;
            }

            for(var i = 0; i < childNodes.length; i++){
                var childNode = childNodes[i];
                colorGraph(childNode, someColor);
            }
        }

        var stack = [];

        function colorGraphUsingStack(someNode, someColor){
            stack.push(someNode);

            while(stack.length > 0){
                var current = stack.pop();
                currentColors[current] = someColor;
                var childNodes = graph[current];

                for(var i = 0; i < childNodes.length; i++){
                    var child = childNodes[i];
                    stack.push(child);
                }

            }
        }

        var queueOffset = 0;
        queue.top = function(){
            var top = queue[queueOffset];
            queueOffset++;
            return top;
            //return queue.shift();
        };

        // This operation is O(n), where n is the number of verticies
        function colorsMatch(currentColors, endingColors){
            for(var i = 0; i < endingColors.length; i++){
                if(currentColors[i] !== endingColors[i]){
                    return false;
                }
            }
            return true;
        }

        function bfs(someNode){
            if(colorsMatch(currentColors, endingColors)){
                queue = [];
                return;
            }

            // process current node
            colorToPaint = endingColors[someNode];

            if(currentColors[someNode] !== endingColors[someNode]){
                steps++;
                colorGraphUsingStack(someNode, colorToPaint);
                visited = new Set();
            }

            // get next nodes to process
            var childNodes = graph[someNode];

            if(!childNodes){
                return;
            }

            for(var i = 0; i < childNodes.length; i++){
                var childNode = childNodes[i];
                queue.push(childNode);
            }

            while(queue.length > 0){
                var nextNode = queue.top();
                bfs(nextNode);
            }
        }

        /* A bunch of code needed just to map input into adjacency list */
        /**
         * @Tigran
         * There has to be a better way of creating an adjacency list from the input.
         *
         * Perhaps I shouldn't be using an adjacency list data structure or I am
         * over complicating this in some way.
         *
         */
        function getAdjacencyListFromInput(n, p){

            /**
             * Creates [[], ..., []] of size n
             * @param n
             * @returns {Array}
             */
            function createEmptyAdjacencyList(n){
                var adjancencyList = [];
                for(var i = 0; i < n; i++){
                    adjancencyList.push([]);
                }

                return adjancencyList;
            }

            /**
             * Creates array [2, 3, ..., n+1]
             * @param n
             * @returns {Array}
             */

            function createI(n){
                var i = [];
                for(var k = 0; k < n; k++){
                    i.push(k + 2);
                }
                return i;
            }

            debugger;

            var c = createEmptyAdjacencyList(n + 1); // [[], ..., []] of size n + 1 (where 0 index isn't used)
            var i = createI(n + 1); // [2, 3, ... n+1]

            for(var k = 0; k < n - 1; k++){
                var p_k = p[k]; // e.g. [1, 2, 2, 1, 5]
                var i_k = i[k]; // e.g. [2, 3, 4, 5, 6]
                c[p_k].push(i_k);
            }

            /**
             *  Above could also be this, but makes it harder to read
             *  */
            // for(var k = 0; k < n-1; k++){
            //     var p_k = p[k]; // e.g. [1, 2, 2, 1, 5]
            //     c[p_k].push(k+2);
            // }

            return c; // e.g. [[], [2, 5], [3, 4], [], [], [6]]
        }

        // currentColors = [0, 0, ..., 0] for size N
        function initializeCurrentColors(n){
            // can't use currentColors var name due to compilation issues in codeforces
            var someColors = new Array(n);
            for(var i=0; i < someColors.length; i++){
                someColors[i] = 0;
            }
            return someColors;
        }

        function addZeroToFrontOfArray(someArray){
            someArray.unshift(0);
        }

        graph = getAdjacencyListFromInput(n, p);
        currentColors = initializeCurrentColors(n+1);
        addZeroToFrontOfArray(c);
        endingColors = c;

        bfs(rootNode);
        ans = steps;
    }

    var ans = 0;

    const n = parseInt(readline());
    const p = readline().split(" ").map(Number);
    const c = readline().split(" ").map(Number);

    solution(n, p, c);
    print(ans);
}

main();

function main(){
    function solution(n, p, c){
        var graph = [];
        var rootNode = 1;
        var dfs_visited = new Set();
        var currentNode = 1;
        var queue = [];
        var currentColors = []; // [0, 0, 0, ..., 0]
        var endingColors = [];
        var steps = 0;
        var colorToPaint = "";

        // var graph = [
        // 	[],
        // 	[2, 5],
        // 	[4, 3],
        // 	[],
        // 	[],
        // 	[6],
        // 	[]
        // ];

        /**
         * This is just a dfs for some starting node, to change colors
         * @param someNode
         * @param someColor
         */
        function colorGraph(someNode, someColor){
            if(dfs_visited.has(someNode)){
                return;
            }

            currentColors[someNode] = someColor;
            dfs_visited.add(someNode);

            var childNodes = graph[someNode];

            if(!childNodes){
                return;
            }

            for(var i = 0; i < childNodes.length; i++){
                var childNode = childNodes[i];
                colorGraph(childNode, someColor);
            }
        }

        var stack = [];

        function colorGraphUsingStack(someNode, someColor){
            stack.push(someNode);

            while(stack.length > 0){
                var current = stack.pop();
                currentColors[current] = someColor;
                var childNodes = graph[current];

                if(childNodes == undefined){
                    return;
                }

                for(var i = 0; i < childNodes.length; i++){
                    var child = childNodes[i];
                    stack.push(child);
                }

            }
        }

        var queueOffset = 0;
        queue.top = function(){
            var top = queue[queueOffset];
            queueOffset++;
            return top;
            //return queue.shift();
        };

        // This operation is O(n), where n is the number of vertices
        function colorsMatch(currentColors, endingColors){
            for(var i = 0; i < endingColors.length; i++){
                if(currentColors[i] !== endingColors[i]){
                    return false;
                }
            }
            return true;
        }

        function bfs(someNode){
            // O(n)
            if(colorsMatch(currentColors, endingColors)){
                queue = [];
                return;
            }

            // process current node
            colorToPaint = endingColors[someNode];

            if(currentColors[someNode] !== endingColors[someNode]){
                steps++;
                colorGraphUsingStack(someNode, colorToPaint);
                dfs_visited = new Set();
            }

            // get next nodes to process
            var childNodes = graph[someNode];

            if(!childNodes){
                return;
            }

            for(var i = 0; i < childNodes.length; i++){
                var childNode = childNodes[i];
                queue.push(childNode);
            }

            while(queue.length > 0){
                var nextNode = queue.top();
                bfs(nextNode);
            }
        }

        /* A bunch of code needed just to map input into adjacency list */
        /**
         * @Tigran
         * There has to be a better way of creating an adjacency list from the input.
         *
         * Perhaps I shouldn't be using an adjacency list data structure or I am
         * over complicating this in some way.
         *
         */
        function getAdjacencyListFromInput(n, p){

            /**
             * Creates [[], ..., []] of size n
             * @param n
             * @returns {Array}
             */
            function createEmptyAdjacencyList(n){
                var adjancencyList = [];
                for(var i = 0; i < n; i++){
                    adjancencyList.push([]);
                }

                return adjancencyList;
            }

            /**
             * Creates array [2, 3, ..., n+1]
             * @param n
             * @returns {Array}
             */

            function createI(n){
                var i = [];
                for(var k = 0; k < n; k++){
                    i.push(k + 2);
                }
                return i;
            }

            var c = createEmptyAdjacencyList(n); // [[], ..., []] of size n
            var i = createI(n); // [2, 3, ... n+1]

            for(var k = 0; k < n-1; k++){
                var p_k = p[k]; // e.g. [1, 2, 2, 1, 5]
                var i_k = i[k]; // e.g. [2, 3, 4, 5, 6]
                c[p_k].push(i_k);
            }

            /**
             *  Above could also be this, but makes it harder to read
             *  */
            // for(var k = 0; k < n-1; k++){
            //     var p_k = p[k]; // e.g. [1, 2, 2, 1, 5]
            //     c[p_k].push(k+2);
            // }

            return c; // e.g. [[], [2, 5], [3, 4], [], [], [6]]
        }

        // currentColors = [0, 0, ..., 0] for size N
        function initializeCurrentColors(n){
            // can't use currentColors var name due to compilation issues in codeforces
            var someColors = new Array(n);
            for(var i=0; i < someColors.length; i++){
                someColors[i] = 0;
            }
            return someColors;
        }

        function addZeroToFrontOfArray(someArray){
            someArray.unshift(0);
        }

        graph = getAdjacencyListFromInput(n, p); // O(n) + O(n) + O(n-1)
        currentColors = initializeCurrentColors(n+1); // O(n)
        addZeroToFrontOfArray(c); // O(n)
        endingColors = c;

        bfs(rootNode); // O(n^2)
        ans = steps;
    }

    var ans = 0;

    const n = parseInt(readline());
    const p = readline().split(" ").map(Number);
    const c = readline().split(" ").map(Number);

    solution(n, p, c);
    print(ans);
}

main();

function main(){
    function solution(n, p, c){
        var graph = [];
        var rootNode = 1;
        var visited = new Set();
        var currentNode = 1;
        var queue = [];
        var currentColors = []; // [0, 0, 0, ..., 0]
        var endingColors = [];
        var steps = 0;
        var colorToPaint = "";

        // var graph = [
        // 	[],
        // 	[2, 5],
        // 	[4, 3],
        // 	[],
        // 	[],
        // 	[6],
        // 	[]
        // ];

        function colorGraph(someNode, someColor){
            if(visited.has(someNode)){
                return;
            }

            currentColors[someNode] = someColor;
            visited.add(someNode);

            var childNodes = graph[someNode];

            if(!childNodes){
                return;
            }

            for(var i = 0; i < childNodes.length; i++){
                var childNode = childNodes[i];
                colorGraph(childNode, someColor);
            }
        }

        var stack = [];

        function colorGraphUsingStack(someNode, someColor){
            stack.push(someNode);

            while(stack.length > 0){
                var current = stack.pop();
                currentColors[current] = someColor;
                var childNodes = graph[current];

                for(var i = 0; i < childNodes.length; i++){
                    var child = childNodes[i];
                    stack.push(child);
                }

            }
        }

        var queueOffset = 0;
        queue.top = function(){
            var top = queue[queueOffset];
            queueOffset++;
            return top;
            //return queue.shift();
        };

        // This operation is O(n), where n is the number of verticies
        function colorsMatch(currentColors, endingColors){
            for(var i = 0; i < endingColors.length; i++){
                if(currentColors[i] !== endingColors[i]){
                    return false;
                }
            }
            return true;
        }

        function bfs(someNode){
            if(colorsMatch(currentColors, endingColors)){
                queue = [];
                return;
            }

            // process current node
            colorToPaint = endingColors[someNode];

            if(currentColors[someNode] !== endingColors[someNode]){
                steps++;
                colorGraphUsingStack(someNode, colorToPaint);
                visited = new Set();
            }

            // get next nodes to process
            var childNodes = graph[someNode];

            if(!childNodes){
                return;
            }

            for(var i = 0; i < childNodes.length; i++){
                var childNode = childNodes[i];
                queue.push(childNode);
            }

            while(queue.length > 0){
                var nextNode = queue.top();
                bfs(nextNode);
            }
        }

        /* A bunch of code needed just to map input into adjacency list */
        /**
         * @Tigran
         * There has to be a better way of creating an adjacency list from the input.
         *
         * Perhaps I shouldn't be using an adjacency list data structure or I am
         * over complicating this in some way.
         *
         */
        function getAdjacencyListFromInput(n, p){

            /**
             * Creates [[], ..., []] of size n
             * @param n
             * @returns {Array}
             */
            function createEmptyAdjacencyList(n){
                var adjancencyList = [];
                for(var i = 0; i < n; i++){
                    adjancencyList.push([]);
                }

                return adjancencyList;
            }

            /**
             * Creates array [2, 3, ..., n+1]
             * @param n
             * @returns {Array}
             */

            function createI(n){
                var i = [];
                for(var k = 0; k < n; k++){
                    i.push(k + 2);
                }
                return i;
            }

            debugger;

            var c = createEmptyAdjacencyList(n + 1); // [[], ..., []] of size n + 1 (where 0 index isn't used)
            var i = createI(n + 1); // [2, 3, ... n+1]

            for(var k = 0; k < n - 1; k++){
                var p_k = p[k]; // e.g. [1, 2, 2, 1, 5]
                var i_k = i[k]; // e.g. [2, 3, 4, 5, 6]
                c[p_k].push(i_k);
            }

            /**
             *  Above could also be this, but makes it harder to read
             *  */
            // for(var k = 0; k < n-1; k++){
            //     var p_k = p[k]; // e.g. [1, 2, 2, 1, 5]
            //     c[p_k].push(k+2);
            // }

            return c; // e.g. [[], [2, 5], [3, 4], [], [], [6]]
        }

        // currentColors = [0, 0, ..., 0] for size N
        function initializeCurrentColors(n){
            // can't use currentColors var name due to compilation issues in codeforces
            var someColors = new Array(n);
            for(var i=0; i < someColors.length; i++){
                someColors[i] = 0;
            }
            return someColors;
        }

        function addZeroToFrontOfArray(someArray){
            someArray.unshift(0);
        }

        graph = getAdjacencyListFromInput(n, p);
        currentColors = initializeCurrentColors(n+1);
        addZeroToFrontOfArray(c);
        endingColors = c;

        bfs(rootNode);
        ans = steps;
        var end = new Date() - start;
    }

    var ans = 0;

    const n = parseInt(readline());
    const p = readline().split(" ").map(Number);
    const c = readline().split(" ").map(Number);

    solution(n, p, c);
    print(ans);
}

var n = 6;
var p = [1, 2, 2, 1, 5];
var c = [2, 1, 1, 1, 1, 1];

function main(){
    function solution(n, p, c){
        var graph = [];
        var rootNode = 1;
        var visited = new Set();
        var currentNode = 1;
        var queue = [];
        var currentColors = []; // [0, 0, 0, ..., 0]
        var endingColors = [];
        var steps = 0;
        var colorToPaint = "";

        // var graph = [
        // 	[],
        // 	[2, 5],
        // 	[4, 3],
        // 	[],
        // 	[],
        // 	[6],
        // 	[]
        // ];

        function colorGraph(someNode, someColor){
            if(visited.has(someNode)){
                return;
            }

            currentColors[someNode] = someColor;
            visited.add(someNode);

            var childNodes = graph[someNode];

            if(!childNodes){
                return;
            }

            for(var i = 0; i < childNodes.length; i++){
                var childNode = childNodes[i];
                colorGraph(childNode, someColor);
            }
        }

        var stack = [];

        function colorGraphUsingStack(someNode, someColor){
            stack.push(someNode);

            while(stack.length > 0){
                var current = stack.pop();
                currentColors[current] = someColor;
                var childNodes = graph[current];

                for(var i = 0; i < childNodes.length; i++){
                    var child = childNodes[i];
                    stack.push(child);
                }

            }
        }

        var queueOffset = 0;
        queue.top = function(){
            var top = queue[queueOffset];
            queueOffset++;
            return top;
            //return queue.shift();
        };

        // This operation is O(n), where n is the number of verticies
        function colorsMatch(currentColors, endingColors){
            for(var i = 0; i < endingColors.length; i++){
                if(currentColors[i] !== endingColors[i]){
                    return false;
                }
            }
            return true;
        }

        function bfs(someNode){
            if(colorsMatch(currentColors, endingColors)){
                queue = [];
                return;
            }

            // process current node
            colorToPaint = endingColors[someNode];

            if(currentColors[someNode] !== endingColors[someNode]){
                steps++;
                colorGraphUsingStack(someNode, colorToPaint);
                visited = new Set();
            }

            // get next nodes to process
            var childNodes = graph[someNode];

            if(!childNodes){
                return;
            }

            for(var i = 0; i < childNodes.length; i++){
                var childNode = childNodes[i];
                queue.push(childNode);
            }

            while(queue.length > 0){
                var nextNode = queue.top();
                bfs(nextNode);
            }
        }

        /* A bunch of code needed just to map input into adjacency list */
        /**
         * @Tigran
         * There has to be a better way of creating an adjacency list from the input.
         *
         * Perhaps I shouldn't be using an adjacency list data structure or I am
         * over complicating this in some way.
         *
         */
        function getAdjacencyListFromInput(n, p){

            /**
             * Creates [[], ..., []] of size n
             * @param n
             * @returns {Array}
             */
            function createEmptyAdjacencyList(n){
                var adjancencyList = [];
                for(var i = 0; i < n; i++){
                    adjancencyList.push([]);
                }

                return adjancencyList;
            }

            /**
             * Creates array [2, 3, ..., n+1]
             * @param n
             * @returns {Array}
             */

            function createI(n){
                var i = [];
                for(var k = 0; k < n; k++){
                    i.push(k + 2);
                }
                return i;
            }

            debugger;

            var c = createEmptyAdjacencyList(n + 1); // [[], ..., []] of size n + 1 (where 0 index isn't used)
            var i = createI(n + 1); // [2, 3, ... n+1]

            for(var k = 0; k < n - 1; k++){
                var p_k = p[k]; // e.g. [1, 2, 2, 1, 5]
                var i_k = i[k]; // e.g. [2, 3, 4, 5, 6]
                c[p_k].push(i_k);
            }

            /**
             *  Above could also be this, but makes it harder to read
             *  */
            // for(var k = 0; k < n-1; k++){
            //     var p_k = p[k]; // e.g. [1, 2, 2, 1, 5]
            //     c[p_k].push(k+2);
            // }

            return c; // e.g. [[], [2, 5], [3, 4], [], [], [6]]
        }

        // currentColors = [0, 0, ..., 0] for size N
        function initializeCurrentColors(n){
            // can't use currentColors var name due to compilation issues in codeforces
            var someColors = new Array(n);
            for(var i=0; i < someColors.length; i++){
                someColors[i] = 0;
            }
            return someColors;
        }

        function addZeroToFrontOfArray(someArray){
            someArray.unshift(0);
        }

        graph = getAdjacencyListFromInput(n, p);
        currentColors = initializeCurrentColors(n+1);
        addZeroToFrontOfArray(c);
        endingColors = c;

        bfs(rootNode);
        ans = steps;
    }

    var ans = 0;

    const n = parseInt(readline());
    const p = readline().split(" ").map(Number);
    const c = readline().split(" ").map(Number);

    solution(n, p, c);
    print(ans);
}


Petya and Vasya got employed as couriers. During the working day they are to deliver packages to n different points on the line. According to the company's internal rules, the delivery of packages must be carried out strictly in a certain order. Initially, Petya is at the point with the coordinate s1, Vasya is at the point with the coordinate s2, and the clients are at the points x1, x2, ..., xn in the order of the required visit.The guys agree in advance who of them will deliver the package to which of the customers, and then they act as follows. When the package for the i-th client is delivered, the one who delivers the package to the (i + 1)-st client is sent to the path (it can be the same person who went to the point xi, or the other). The friend who is not busy in delivering the current package, is standing still.To communicate with each other, the guys have got walkie-talkies. The walkie-talkies work rather poorly at great distances, so Petya and Vasya want to distribute the orders so that the maximum distance between them during the day is as low as possible. Help Petya and Vasya to minimize the maximum distance between them, observing all delivery rules.

The first line contains three integers n, s1, s2 (1 ≤ n ≤ 100 000, 0 ≤ s1, s2 ≤ 109) — number of points of delivery and starting positions of Petya and Vasya. The second line contains n integers x1, x2, ..., xn — customers coordinates (0 ≤ xi ≤ 109), in the order to make a delivery.  It is guaranteed, that among the numbers s1, s2, x1, ..., xn there are no two equal.

Output the only integer, minimum possible maximal distance between couriers during delivery.

NoteIn the first test case the initial distance between the couriers is 10. This value will be the answer, for example, Petya can perform both deliveries, and Vasya will remain at the starting point.In the second test case you can optimally act, for example, like this: Vasya delivers the package to the first customer, Petya to the second and, finally, Vasya delivers the package to the third client. With this order of delivery, the distance between the couriers will never exceed 1.In the third test case only two variants are possible: if the delivery of a single package is carried out by Petya, the maximum distance between them will be 5 - 2 = 3. If Vasya will deliver the package, the maximum distance is 4 - 2 = 2. The latter method is optimal.

const data = readline().split(" ");
const n = Number(data[0]);
const a = Number(data[1]);
const b = Number(data[2]);
const coords = readline().split(" ").slice(0, n).map(x => Number(x)).reverse();
var min = Math.abs(a - b);
var max = 1e9;
while (min < max) {
  var distance = (min + max) >> 1;
  var left = 0;
  var right = 1e9;
  for (var x of coords) {
    var inRange = left <= x && x <= right;
    var nLeft = x - distance;
    var nRight = x + distance;
    if (inRange || nLeft > left) left = nLeft;
    if (inRange || nRight < right) right = nRight;
  }
  if ((left <= a && a <= right) || (left <= b && b <= right)) max = distance;
  else min = distance + 1;
}
print(min);


Inna loves sweets very much. She has n closed present boxes lines up in a row in front of her. Each of these boxes contains either a candy (Dima's work) or nothing (Sereja's work). Let's assume that the boxes are numbered from 1 to n, from left to right.As the boxes are closed, Inna doesn't know which boxes contain candies and which boxes contain nothing. Inna chose number k and asked w questions to Dima to find that out. Each question is characterised by two integers li, ri (1 ≤ li ≤ ri ≤ n; r - l + 1 is divisible by k), the i-th question is: "Dima, is that true that among the boxes with numbers from li to ri, inclusive, the candies lie only in boxes with numbers li + k - 1, li + 2k - 1, li + 3k - 1, ..., ri?"Dima hates to say "no" to Inna. That's why he wonders, what number of actions he will have to make for each question to make the answer to the question positive. In one action, Dima can either secretly take the candy from any box or put a candy to any box (Dima has infinitely many candies). Help Dima count the number of actions for each Inna's question.Please note that Dima doesn't change the array during Inna's questions. That's why when you calculate the number of operations for the current question, please assume that the sequence of boxes didn't change.

The first line of the input contains three integers n, k and w (1 ≤ k ≤ min(n, 10), 1 ≤ n, w ≤ 105). The second line contains n characters. If the i-th box contains a candy, the i-th character of the line equals 1, otherwise it equals 0. Each of the following w lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th question. It is guaranteed that ri - li + 1 is divisible by k.

For each question, print a single number on a single line — the minimum number of operations Dima needs to make the answer to the question positive.

NoteFor the first question, you need to take a candy from the first box to make the answer positive. So the answer is 1.For the second question, you need to take a candy from the first box, take a candy from the fifth box and put a candy to the sixth box. The answer is 3.For the third question, you need to take a candy from the fifth box and put it to the sixth box. The answer is 2.

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var n = integers[0], jump = integers[1], queryNum = integers[2];
	var candy = "."+trim(readline());

	var sums = [];

	for (var start = 1; start <= jump; ++start) {
		var sum = [];
		for (var pad = 0; pad < start; ++pad) {
			sum.push(0);
		}
		var count = 0;
		for (var pos = start; pos <= n; ++pos) {
			if (candy.charAt(pos) != ((pos-start+1)%jump == 0 ? '1' : '0')) {
				count += 1;
			}
			sum.push(count);
		}
		sums.push(sum);
	}

	for (var i = 0; i < queryNum; ++i) {
		var query = tokenizeIntegers(readline());
		var left = query[0], right = query[1];
		var sumIx = (left-1)%jump;
		var answer = sums[sumIx][right] - sums[sumIx][left-1];
		print(answer);
	}

}

main();

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var n = integers[0], jump = integers[1], queryNum = integers[2];
	var candy = "."+trim(readline());

	var sums = [];

	for (var start = 1; start <= jump; ++start) {
		var sum = [0];
		var count = 0;
		for (var pos = start; pos <= n; ++pos) {
			if (candy.charAt(pos) != ((pos-start+1)%jump == 0 ? '1' : '0')) {
				count += 1;
			}
			sum.push(count);
		}
		sums.push(sum);
	}

	for (var i = 0; i < queryNum; ++i) {
		var query = tokenizeIntegers(readline());
		var left = query[0], right = query[1];
		var sumIx = (left-1)%jump;
		var answer = sums[sumIx][right] - sums[sumIx][left-1];
		print(answer);
	}

}

main();


You are given a binary string of length $$$n$$$ (i. e. a string consisting of $$$n$$$ characters '0' and '1').In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than $$$k$$$ moves? It is possible that you do not perform any moves at all.Note that you can swap the same pair of adjacent characters with indices $$$i$$$ and $$$i+1$$$ arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.You have to answer $$$q$$$ independent test cases.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6, 1 \le k \le n^2$$$) — the length of the string and the number of moves you can perform. The second line of the test case contains one string consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).

For each test case, print the answer on it: the lexicographically minimum possible string of length $$$n$$$ you can obtain from the given one if you can perform no more than $$$k$$$ moves.

NoteIn the first example, you can change the string as follows: $$$1\underline{10}11010 \rightarrow \underline{10}111010 \rightarrow 0111\underline{10}10 \rightarrow 011\underline{10}110 \rightarrow 01\underline{10}1110 \rightarrow 01011110$$$. In the third example, there are enough operations to make the string sorted.

'use strict'

const problem = (n, k, p) => {
    for(let i = 0, j = 0; i < p.length; i++) {
        if (p[i]) continue;
        if (i === j) { j++; continue; }
        p[i] = 1;
        if (k <= i - j) { p[i-k] = 0; return p.join(''); }
        k -= (i - j);
        p[j++] = 0;
    }
    return p.join('');
}

let q = +readline();
while (q--) {
    const nk = readline().split(' ').map(Number);
    const p = readline().split('').map(Number);
    print(problem(nk[0], nk[1], p));
}

let fs = require("fs");

let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    doit(info[1] * 1, txt[index + 1]);
}

function doit(b, str) {
    let tab = str.split("");
    tab.map((data, index) => {
        if (data == 0) {
            return index;
        }
    }).filter(data => {
        return data != undefined
    }).forEach((data, index) => {
        if(b>0){
            tab[data]=1;
           if(data-index<=b){
                tab[index]=0;
                b-=data-index;
           }else{
               tab[data-b]=0;
                b=0;
               return;
           }
        }
    })
    console.log(tab.join(""));
}

'use strict'

const problem = (n, k, p) => {
    let a = 0, b;
    const z = p.reduce((r, i, j) => { if (!i) r.push(j); return r; }, []);
    while (b = z.shift()) {
        if (k <= (b - a)) { p[b] = 1; p[b-k] = 0; return p.join('')}
        p[b] = 1; k -= (b - a); p[a++] = 0;
    }
    return p.join('');
}

let q = +readline();
while (q--) {
    const nk = readline().split(' ').map(Number);
    const p = readline().split('').map(Number);
    print(problem(nk[0], nk[1], p));
}

'use strict'

const problem = (n, k, p) => {
    for(let i = 0, j = 0; i < p.length; i++) {
        if (p[i] || i === j) continue;
        p[i] = 1;
        if (k <= i - j) { p[i-k] = 0; return p.join(''); }
        k -= (i - j);
        p[j++] = 0;
    }
    return p.join('');
}

let q = +readline();
while (q--) {
    const nk = readline().split(' ').map(Number);
    const p = readline().split('').map(Number);
    print(problem(nk[0], nk[1], p));
}

'use strict'

const problem = (n, k, p) => {
    let a = 0, b;
    while ((b = p.slice(a).indexOf(0)) !== -1) {
        if (k < b) { p[a+b-k] = 0; p[a+b] = 1; return p.join('')}
        p[a+b] = 1; p[a++] = 0;k -= b;
    }
    return p.join('');
}

let q = +readline();
while (q--) {
    const nk = readline().split(' ').map(Number);
    const p = readline().split('').map(Number);
    print(problem(nk[0], nk[1], p));
}

'use strict'

const problem = (n, k, p) => {
    for(let i = 0, j = 0; i < p.length; i++) {
        if (p[i]) continue;
        if (i === j) { j++; continue; }
        p[i] = 1;
        if (k <= i - j) { p[i-k] = 0; return p.join(''); }
        k -= (i - j);
        p[j++] = 0;
        print(i, j-1, k, p.join(''))
    }
    return p.join('');
}

let q = +readline();
while (q--) {
    const nk = readline().split(' ').map(Number);
    const p = readline().split('').map(Number);
    print(problem(nk[0], nk[1], p));
}

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    let tab = txt[index + 1].split("").filter(data => {
        return data.length > 0
    });
    binary(info[1] * 1, tab)

}

function binary(x, tab) {
    tab.map((data, index) => {
        return (data == 0) ? index : null;
    }).filter(data => {
        return data;
    }).forEach((data, index) => {
        while (data != index && x > 0) {
            tab[data] = 1;
            tab[data - 1] = 0;
            --x;
            --data;
        }
    });
    console.log(tab.join(""));
}

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    let tab = txt[index + 1].split("").filter(data => {
        return data.length > 0
    });
    binary(info[1] * 1, tab)

}

function binary(x, tab) {
    let pos=-1;
    for (let i = 0; i < tab.length; i++) {
        if(tab[i]==0){
            ++pos;
            if(i!=pos && x>0){
                tab[i]=1;
                if(x>=i-1){
                    tab[pos]=0;
                    x-=i-pos;
                }else{
                    tab[i-x]=0;
                    break;
                }
            }
        }

    }
    console.log(tab.join(""));
}

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    let tab = txt[index + 1].split("").filter(data => {
        return data.length > 0
    });
    binary(info[1] * 1, tab)

}

function binary(x, tab) {
   let pos=0;
   for (let index = 0; index < tab.length; index++) {
      if(tab[index]==0 && index!=pos){
          tab[index]=1;
          if(x-index>=0){
              tab[pos]=0;
              x-=index;
              ++pos;
          }else{
              tab[index-x]=0;
              break;
          }
      }

   }
    console.log(tab.join(""));
}

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    let tab = txt[index + 1].split("").filter(data => {
        return data.length > 0
    });
    binary(info[1] * 1, tab)

}

function binary(x, tab) {
   let pos=0;
   for (let index = 0; index < tab.length; index++) {
      if(tab[index]==0 && index!=pos){
          tab[index]=1;
          if(x-index>=0){
              tab[pos]=0;
              x-=index;
              ++pos;
          }else{
              tab[index-x]=0;
             x=0;
          }
          if(x==0){
              break;
          }
      }

   }
    console.log(tab.join(""));
}
// 01011110
// 0101111
// 0011111

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    binary(info[1] * 1, txt[index+1])

}

function binary(x, tab) {
    let pos=0;
    let arr=new Array(tab.length).fill(1);
    for (let i = 0; i < tab.length; i++) {
        if(tab[i]==0){
            if(i-pos<=x){
                x-=Math.abs(pos-i);
                arr[pos]=0;
            }else{
                arr[i-x]=0;
                x=0
            }
            if(x<=0){
                break;
            }
            ++pos
        }

    }
    console.log(arr.join(""));
}
// 01011110
// 0101111
// 0011111

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    let tab = txt[index + 1].split("").filter(data => {
        return data.length > 0
    });
    binary(info[1] * 1, tab)

}

function binary(x, tab) {
   let pos=0;
   for (let index = 0; index < tab.length; index++) {
      if(tab[index]==0 && index!=pos){
          tab[index]=1;
          if(x-index>=pos){
              tab[pos]=0;
              x-=index;
              ++pos;
          }else{
              tab[index-x]=0;
             x=0;
          }
          if(x==0){
              break;
          }
      }

   }
    console.log(tab.join(""));
}
// 01011110
// 0101111
// 0011111

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    binary(info[1] * 1, txt[index+1])

}

function binary(x, tab) {
    let pos=0;
    let arr=new Array(tab.length).fill(1);
    for (let i = 0; i < tab.length; i++) {
        if(tab[i]==0){
            if(i-pos<=x){
                x-=i-pos;
                arr[pos]=0;
            }else{
                arr[i-x]=0;
                x=0
            }
            if(x==0){
                break;
            }
            ++pos
        }

    }
    console.log(arr.join(""));
}
// 01011110
// 0101111
// 0011111

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    let tab = txt[index + 1].split("").filter(data => {
        return data.length > 0
    });
    binary(info[1] * 1, tab)

}

function binary(x, tab) {
   tab.map((data, index) => {
        return (data == 0) ? index : undefined;
    }).filter(data => {
        return data != undefined;
    }).forEach((data, index) => {
        if(x==0){
            return;
        }else if(data!=index){
           tab[data]=1;
           if(data<=x){
               tab[index]=0;
               x-=data-index;
           }else{
               tab[data-x]=0;
               return;
           }
        }
    });
    console.log(tab.join(""));
}

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    let tab = txt[index + 1].split("").filter(data => {
        return data.length > 0
    });
    binary(info[1] * 1, tab)

}

function binary(x, tab) {
    let r = tab.map((data, index) => {
        return (data == 0) ? index : undefined;
    }).filter(data => {
        return data != undefined;
    }).forEach((data, index) => {
       if(data!=index && x!=0){
           tab[data]=1;
            if(x>=data-index){
                tab[index]=0;
                x-=data;
            }else{
                tab[data-x]=0;
                x=0;
            }
       }
    });
    console.log(tab.join(""));
}

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    let tab = txt[index + 1].split("").filter(data => {
        return data.length > 0
    });
    binary(info[1] * 1, tab)

}

function binary(x, tab) {
   tab.map((data, index) => {
        return (data == 0) ? index : undefined;
    }).filter(data => {
        return data != undefined;
    }).forEach((data, index) => {
        if(x==0){
            return;
        }else if(data!=index){
           tab[data]=1;
           if(data<x){
               tab[index]=0;
               x-=data-index;
           }else{
               tab[data-x]=0;
               return;
           }
        }
    });
    console.log(tab.join(""));
}

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    binary(info[1] * 1, txt[index+1])

}

function binary(x, tab) {
    let pos=0;
    let arr=new Array(tab.length).fill(1);
    for (let i = 0; i < tab.length; i++) {
        if(tab[i]==0){
            if(i-pos<=x){
                x-=Math.abs(pos-i);
                arr[pos]=0;
            }else{
                arr[i-x]=0;
                break;
            }
            ++pos
        }

    }
    console.log(arr.join(""));
}

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    let tab = txt[index + 1].split("").filter(data => {
        return data.length > 0
    });
    binary(info[1] * 1, tab)

}

function binary(x, tab) {
   let pos=0;
   for (let index = 0; index < tab.length; index++) {
      if(tab[index]==0 && index!=pos){
          tab[index]=1;
          if(index-pos<=x){
              tab[pos]=0;
              x-=index;
              ++pos;
          }else{
              tab[index-x]=0;
             x=0;
          }
          if(x==0){
              break;
          }
      }

   }
    console.log(tab.join(""));
}
// 01011110
// 0101111
// 0011111

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    binary(info[1] * 1, txt[index+1])

}

function binary(x, tab) {
    let pos=0;
    let arr=new Array(tab.length).fill(1);
    for (let i = 0; i < tab.length; i++) {
        if(tab[i]==0){
            if(i-pos<=x){
                x-=Math.abs(pos-i);
                arr[pos]=0;
            }else{
                arr[i-x]=0;
            }
            if(x<=0){
                break;
            }
            ++pos
        }

    }
    console.log(arr.join(""));
}

let fs = require('fs');
let txt = fs.readFileSync(0, "utf-8").split("\r\n").filter(data => {
    return data.length > 0
});
txt.shift();
for (let index = 0; index < txt.length; index += 2) {
    let info = txt[index].split(" ")
    binary(info[1] * 1, txt[index+1])

}

function binary(x, tab) {
    let pos=0;
    let arr=new Array(tab.length).fill(1);
    for (let i = 0; i < tab.length; i++) {
        if(tab[i]==0){
            arr[i]=1;
            if(i-pos<=x){
                x-=Math.abs(pos-i);
                arr[pos]=0;
            }else{
                arr[i-x]=0;
                x=0;
                break;
            }
            ++pos
        }

    }
    console.log(arr.join(""));
}