You have an array $$$a$$$ of size $$$n$$$ consisting only of zeroes and ones. You can do the following operation:  choose two indices $$$1 \le i , j \le n$$$, $$$i \ne j$$$,  add $$$a_{i}$$$ to $$$a_{j}$$$,  remove $$$a_{i}$$$ from $$$a$$$. Note that elements of $$$a$$$ can become bigger than $$$1$$$ after performing some operations. Also note that $$$n$$$ becomes $$$1$$$ less after the operation.What is the minimum number of operations needed to make $$$a$$$ non-decreasing, i. e. that each element is not less than the previous element?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the size of array $$$a$$$. Next line contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots a_{n}$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$), elements of array $$$a$$$. It's guaranteed that sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer, minimum number of operations needed to make $$$a$$$ non-decreasing.

NoteIn the first test case, $$$a$$$ is already non-decreasing, so you don't need to do any operations and the answer is $$$0$$$.In the second test case, you can perform an operation for $$$i = 1$$$ and $$$j = 5$$$, so $$$a$$$ will be equal to $$$[0, 0, 1, 2]$$$ and it becomes non-decreasing.In the third test case, you can perform an operation for $$$i = 2$$$ and $$$j = 1$$$, so $$$a$$$ will be equal to $$$[1]$$$ and it becomes non-decreasing.

var n = parseInt(readline());

for (var i = 0; i < n; i++){
    var counter = 0;

    var k = parseInt(readline());
    var arr = readline().split(" ");

    var bolo = k - 1;
    var starti = 0;

    for(var j = 1; j < k; j++){
        if(arr[j - 1] > arr[j]){
            while (arr[bolo] == 1){
                bolo--;
            }
            while(arr[starti] == 0){
               starti++;
            }
            arr[starti] = 0;
            arr[bolo] = 1
            j = starti + 1;
            k = bolo;
            counter++;
        }
    }
    print(counter);
}

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

let inputString = "";
let currentLine = 0;

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

function solve() {
  var t = readline();
  for (var k = 0; k < t; k++) {
    var n = readline();
    var STR = readline();
    var List = STR.split(' ');
    var res = 0;
    if (STR.match(/0/g) == null) {
      process.stdout.write(res + '\n');
      continue;
    }
    var z = STR.match(/0/g).length;
    for (var i = 0; i < n; i++) {
      if (List[i] == 0) {
        z--;
      } else {
        z--;
        res++;
      }
      if (z == 0) {
        process.stdout.write(res + '\n');
      }
    }
  }
}

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

let currentline = 0;
function readline(){
    return input[currentline++];
}
let t = +readline();

while(t--){
    let n = +readline();
    let arr = readline().split(' ').map(x => +x);
    console.log(`${solve(arr, n)}`)
}

function solve(nums, n){
    let result = 0;
    let l = 0;
    let r = n-1;
    while(l < r){
        while(nums[r]) r--;
        while(nums[l] === 0) l++;
        if(l < r){
            result++;
            l++;
            r--;
        }
    }
    return result;
}

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

let currentline = 0;
function readline(){
    return input[currentline++];
}
let t = +readline();

while(t--){
    let n = +readline();
    let arr = readline().split(' ').map(x => +x);
    console.log(`${solve(arr, n)}`)
}

function solve(nums, n){
    let result = 0;
    let l = 0;
    let r = n-1;
    while(l < r){
        while(nums[r]) r--;
        while(nums[l] === 0) l++;
        if(l < r){
            result++;
            nums[l] = 0;
            nums[r] = 1;
            l++;
            r--;
        }
    }
    return result;
}

function solve() {
    var n = Number(read());
    var a = readArray(Number);
    var oneLeft = [];
    var zeroRight = [];
    zeroRight[n] = 0;
    for (var i = 0; i < n; i++) {
        oneLeft[i] = (oneLeft[i - 1] || 0) + a[i];
        zeroRight[n - i - 1] = zeroRight[n - i] + 1 - a[n - i - 1];
    }

    for (i = 0; i < n; i++) {
        if (oneLeft[i] === zeroRight[i + 1]) {
            write(oneLeft[i]);
            return;
        }
    }
    write(0);
}

function start() {
    var T = 1;
    T = Number(read());
    for (var t = 0; t < T; t++) {
        solve();
    }
    writeAns();
}

var MEMORY;
var MEMORY_INDEX = 0;
var ANS = '';

try {
    initInput(start);
} catch (e) {
    console.log(e);
}
function readArray(f) {
    return read().split(' ').map(f);
}

function sortNumbers(a, b) {
    return a - b;
}
function sortNumbersDec(a, b) {
    return b - a;
}
var ANS;
// вывод через ANS быстрее, но ест кучу памяти.
// К тому же, максимальная длина строки - 2097151.
function write(value) {
    // console.log(value);
    ANS += value + '\n';
}
function writeAns() {
    if (ANS) {
        console.log(ANS);
    }
}
function read() {
    return MEMORY[MEMORY_INDEX++];
}
function initInput(callback) {
    var fs = require('fs');
    var isLocalStart = process.argv[2] === 'lorelvate';
    if (!isLocalStart) {
        MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
        callback();
        return;
    }
    var path = require('path');
    fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {
        if (err) {
            write(err);
            return;
        }
        MEMORY = data.split('\r\n');
        callback();
    });
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var index = [];
		for(var i = 0; i < N; i++){
			if(list[i] == 0){
				index.push(i);
			}
		}
		var output = 0;
		for(var i = 0; i < N && index.length > 0; i++){
			if(list[i] == 1 && i < index[index.length - 1]){
				output++;
				index.pop();
			}
		}
		myout(output);
	}
}

let buf='';

process.stdin.on('readable',function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let _=1;_<=t;_++)
    {
        let n=parseInt(line[2*_-1]);
        let a=line[2*_].split(' ').map(x=>{return parseInt(x)});
        let cnt=0;
        for(let i=0;i<n;i++) cnt+=a[i];
        let ans=0;
        for(let i=n-cnt;i<n;i++) ans+=(!a[i]);
        console.log(ans);
    }
})

'use strict';

var fs = require('fs');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        a = rns();
  let res = 0;
  for (let l = 0, r = n - 1; l < r; l++, r--) {
    while (r >= l && a[r]) r--;
    while (r >= l && !a[l]) l++;
    if (l < r) {
      res++;
    }
  }
  return res;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};

const solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let arr = iInpArr();
    let zero = [];
    for (let i = 0; i < n; i++) if (arr[i] === 0) zero.push(i);
    if (zero.length === 0) console.log(0);
    else {
      let ans = 0;
      let left = 0,
        right = zero.length - 1;
      for (let i = 0; i < n; i++) {
        if (arr[i] === 1) {
          if (right >= 0 && i < zero[right]) {
            ans++;
            right--;
          }
        } else left++;
      }
      console.log(ans);
    }
  }
};
solve();

var n = parseInt(readline());

for (var i = 0; i < n; i++){
    var counter = 0;

    var k = parseInt(readline());
    var arr = readline().split(" ");

    var bolo;
    for(var j = 1; j < k; j++){
        if(arr[j - 1] > arr[j]){
            bolo = k - 1;
            while (arr[bolo] == 1){
                bolo--;
            }
            arr[j - 1] = 0;
            arr[bolo] = 1
            j = 0
            counter++;
        }
    }
    print(counter);
}

var n = parseInt(readline());

for (var i = 0; i < n; i++){
    var counter = 0;

    var k = parseInt(readline());
    var arr = readline().split(" ");

    for(var j = 1; j < k; j++){
        if(arr[j - 1] > arr[j]){
            j++;
            counter++;
        }
    }
    print(counter);
}

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

let inputString = "";
let currentLine = 0;

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

function solve() {
  var t = readline();
  for (var k = 0; k < t; k++) {
    var n = readline();
    var STR = readline();
    var List = STR.split(' ');
    var res = 0;
    var z = STR.match(/0/g).length;
    for (var i = 0; i < n; i++) {
      if (List[i] == 0) {
        z--;
      } else {
        z--;
        res++;
      }
      if (z == 0) {
        return process.stdout.write(res + '\n');
      }
    }
  }
}

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

let inputString = "";
let currentLine = 0;

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

function solve() {
  var t = readline();
  for (var k = 0; k < t; k++) {
    var n = readline();
    var List = readline().split(' ');
    var res = 0;
    for (var i = 1; i <= n; i++) {
      if (List[i] >= List[i - 1]) {
        if (n - i == 1) {
          console.log(res + '\n');
        }
      } else {
        res++;
        if (n - i == 1) {
          console.log(res + '\n');
        }
      }
    }
  }
}

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

let inputString = "";
let currentLine = 0;

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

function solve() {
  var t = readline();
  for (var k = 0; k < t; k++) {
    var n = readline();
    var List = readline().split(' ');
    var res = 0;
    for (var i = 1; i <= n; i++) {
      if (List[i] >= List[i - 1]) {
        if (n - i == 1) {
          console.log(res);
        }
      } else {
        res++;
        if (n - i == 1) {
          console.log(res);
        }
      }
    }
  }
}

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

let inputString = "";
let currentLine = 0;

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

function solve() {
  var t = readline();
  for (var k = 0; k < t; k++) {
    var n = readline();
    var List = readline().split(' ');
    var res = 0;
    for (var i = 0; i < n; i++) {
      if (List[i] <= List[i + 1]) {
        if (n - i == 1) {
          console.log(res);
        }
      } else {
        res++;
        if (n - i == 1) {
          res = res - 1;
          console.log(res);
        }
      }
    }
  }
}

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

let inputString = "";
let currentLine = 0;

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

function solve() {
  var t = readline();
  for (var k = 0; k < t; k++) {
    var n = readline();
    var List = readline().split(' ');
    var res = 0;
    for (var i = 0; i < n; i++) {
      if (List[i] <= List[i + 1]) {
        if (n - i == 1) {
          process.stdout.write(res + '\n');
        }
      } else {
        res++;
        if (n - i == 1) {
          res = res - 1;
          process.stdout.write(res + '\n');
        }
      }
    }
  }
}

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

let currentline = 0;
function readline(){
    return input[currentline++];
}
let t = +readline();

while(t--){
    let n = +readline();
    let arr = readline().split(' ').map(x => +x);
    console.log(`${solve(arr, n)}`)
}

function solve(nums, n){
    let result = 0;
    while(--n){
        if(nums[n] < nums[n-1]) result++;
    }
    return result;
}

function solve() {
    var n = Number(read());
    var a = readArray(Number);
    var oneLeft = [];
    var zeroRight = [];
    for (var i = 0; i < n; i++) {
        oneLeft[i] = (oneLeft[i - 1] || 0) + a[i];
        zeroRight[n - i - 1] = (zeroRight[n - i] || 0) + (1 - a[n - i - 1]);
    }

    for (i = 0; i < n - 1; i++) {
        if (oneLeft[i] === zeroRight[i + 1]) {
            write(oneLeft[i]);
            return;
        }
    }
}

function start() {
    var T = 1;
    T = Number(read());
    for (var t = 0; t < T; t++) {
        solve();
    }
    writeAns();
}

var MEMORY;
var MEMORY_INDEX = 0;
var ANS = '';

try {
    initInput(start);
} catch (e) {
    console.log(e);
}
function readArray(f) {
    return read().split(' ').map(f);
}

function sortNumbers(a, b) {
    return a - b;
}
function sortNumbersDec(a, b) {
    return b - a;
}
var ANS;
// вывод через ANS быстрее, но ест кучу памяти.
// К тому же, максимальная длина строки - 2097151.
function write(value) {
    // console.log(value);
    ANS += value + '\n';
}
function writeAns() {
    if (ANS) {
        console.log(ANS);
    }
}
function read() {
    return MEMORY[MEMORY_INDEX++];
}
function initInput(callback) {
    var fs = require('fs');
    var isLocalStart = process.argv[2] === 'lorelvate';
    if (!isLocalStart) {
        MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
        callback();
        return;
    }
    var path = require('path');
    fs.readFile(path.join(__dirname, 'input.txt'), 'utf8', (err, data) => {
        if (err) {
            write(err);
            return;
        }
        MEMORY = data.split('\r\n');
        callback();
    });
}


There are $$$n$$$ chests. The $$$i$$$-th chest contains $$$a_i$$$ coins. You need to open all $$$n$$$ chests in order from chest $$$1$$$ to chest $$$n$$$.There are two types of keys you can use to open a chest:   a good key, which costs $$$k$$$ coins to use;  a bad key, which does not cost any coins, but will halve all the coins in each unopened chest, including the chest it is about to open. The halving operation will round down to the nearest integer for each chest halved. In other words using a bad key to open chest $$$i$$$ will do $$$a_i = \lfloor{\frac{a_i}{2}\rfloor}$$$, $$$a_{i+1} = \lfloor\frac{a_{i+1}}{2}\rfloor, \dots, a_n = \lfloor \frac{a_n}{2}\rfloor$$$;  any key (both good and bad) breaks after a usage, that is, it is a one-time use. You need to use in total $$$n$$$ keys, one for each chest. Initially, you have no coins and no keys. If you want to use a good key, then you need to buy it.During the process, you are allowed to go into debt; for example, if you have $$$1$$$ coin, you are allowed to buy a good key worth $$$k=3$$$ coins, and your balance will become $$$-2$$$ coins.Find the maximum number of coins you can have after opening all $$$n$$$ chests in order from chest $$$1$$$ to chest $$$n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^5$$$; $$$0 \leq k \leq 10^9$$$) — the number of chests and the cost of a good key respectively. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$0 \leq a_i \leq 10^9$$$)  — the amount of coins in each chest. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output a single integer  — the maximum number of coins you can obtain after opening the chests in order from chest $$$1$$$ to chest $$$n$$$. Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

NoteIn the first test case, one possible strategy is as follows:   Buy a good key for $$$5$$$ coins, and open chest $$$1$$$, receiving $$$10$$$ coins. Your current balance is $$$0 + 10 - 5 = 5$$$ coins.  Buy a good key for $$$5$$$ coins, and open chest $$$2$$$, receiving $$$10$$$ coins. Your current balance is $$$5 + 10 - 5 = 10$$$ coins.  Use a bad key and open chest $$$3$$$. As a result of using a bad key, the number of coins in chest $$$3$$$ becomes $$$\left\lfloor \frac{3}{2} \right\rfloor = 1$$$, and the number of coins in chest $$$4$$$ becomes $$$\left\lfloor \frac{1}{2} \right\rfloor = 0$$$. Your current balance is $$$10 + 1 = 11$$$.  Use a bad key and open chest $$$4$$$. As a result of using a bad key, the number of coins in chest $$$4$$$ becomes $$$\left\lfloor \frac{0}{2} \right\rfloor = 0$$$. Your current balance is $$$11 + 0 = 11$$$.  At the end of the process, you have $$$11$$$ coins, which can be proven to be maximal.

var t = readline();

for (var i = 0; i < t; i++) {
    var inp = readline().split(' ');
    var n = inp[0];
    var k = inp[1];
    var chests = readline().split(' ');
    var ans = 0;
    var good30 = 0;

    for (var j = 0; j < n; j++) {
        var bad30 = 0;
        var div = 1;

        for (var p = j; p < n && p < j + 31; p++) {
            div *= 2;
            bad30 += Math.floor(parseInt(chests[p]) / div);
        }
        ans = Math.max(ans, good30 + bad30);
        good30 += parseInt(chests[j]) - k;
    }

    ans = Math.max(ans, good30);

    print(ans);
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, k, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, k, arr) {
    // return check(n, k, arr)
    //
    // const dp = []
    // const save = arr.slice()
    // for (let i = 0; i <= 30; i++) {
        const sum = []
        for (let j = 0; j < arr.length; j++) {
            sum[j] = arr[j]
            if (j) sum[j] += sum[j - 1]
            // arr[j] = Math.floor(arr[j] / 2)
        }
        // dp[i] = sum
    // }
    // console.log(dp)
    let ans = sum[n - 1] - n * k
    for (let i = 0; i < arr.length; i++) {
        let now = (sum[i - 1] || 0) - k * i
        for (let j = 0; j <= 30; j++) {
            if (i + j >= n) break
            now += Math.floor(arr[i + j] / (2 ** (j + 1)))
        }
        // console.log(i, now)
        ans = Math.max(ans, now)
    }
    return ans
}
function check(n, k, arr) {
    const limit = 2 ** n
    let max = -Infinity
    for (let i = 0; i < limit; i++) {
        let bad = 0
        let ans = 0
        for (let j = 0; j < n; j++) {
            if (i & (1 << j)) {
                // bad
                bad++
            } else {
                ans -= k
            }
            ans += Math.floor(arr[j] / (2 ** bad))
        }
        if (ans > max) {
            console.log(i.toString(2), ans)
            max = ans
        }
    }
    return max
}

var t = parseInt(readline());

for (var i = 0; i < t; i++) {
    var inp = readline().split(' ');
    var n = inp[0];
    var k = inp[1];
    var chests = readline().split(' ');

    var ans = 0;

    var rest = 0;
    var div = 0;

    for (var j = 0; j < chests.length; j++) {
        rest += chests[j];
    }

    for (var j = 0; j < chests.length; j++) {
        var curr = chests[j];
        for (var l = 0; l < div; l++) {
            curr = Math.floor(curr / 2);
        }

        if (Math.floor(rest / 2) < rest - k) {
            ans -= k;
            ans += curr;
            rest -= curr;
        } else {
            ans += Math.floor(curr / 2);
            rest -= curr;
            rest = Math.floor(rest / 2);
            div++;
        }
    }

    print(ans);
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, k] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, k, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, k, arr) {
    const dp = []
    const save = arr.slice()
    for (let i = 0; i <= 30; i++) {
        const sum = []
        for (let j = 0; j < arr.length; j++) {
            sum[j] = arr[j]
            if (j) sum[j] += sum[j - 1]
            arr[j] = Math.floor(arr[j] / 2)
        }
        dp[i] = sum
    }
    // console.log(dp)
    let ans = 0
    let bad = 0
    for (let i = 0; i < arr.length; i++) {
        const cur = dp[bad][n - 1] - (dp[bad][i - 1] || 0)
        const next = dp[bad + 1][n - 1] - (dp[bad + 1][i - 1] || 0)
        if (cur - next < k) {
            bad++
        } else {
            ans -= k
        }
        ans += bad ? Math.floor(save[i] / (2 ** bad)) : save[i]
    }
    return ans
}


Monocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of $$$2$$$ rows and $$$n$$$ columns. Monocarp controls a character, which starts in cell $$$(1, 1)$$$ — at the intersection of the $$$1$$$-st row and the $$$1$$$-st column.Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ in one step if $$$|x_1 - x_2| \le 1$$$ and $$$|y_1 - y_2| \le 1$$$. Obviously, it is prohibited to go outside the grid.There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.To complete a level, Monocarp's character should reach cell $$$(2, n)$$$ — at the intersection of row $$$2$$$ and column $$$n$$$.Help Monocarp determine if it is possible to complete the level.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of columns. The next two lines describe the level. The $$$i$$$-th of these lines describes the $$$i$$$-th line of the level — the line consists of the characters '0' and '1'. The character '0' corresponds to a safe cell, the character '1' corresponds to a trap cell. Additional constraint on the input: cells $$$(1, 1)$$$ and $$$(2, n)$$$ are safe.

For each test case, output YES if it is possible to complete the level, and NO otherwise.

NoteConsider the example from the statement.In the first test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (2, 3)$$$.In the second test case, one of the possible paths is $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 3) \rightarrow (2, 4)$$$.In the fourth test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (1, 3) \rightarrow (2, 4) \rightarrow (1, 5) \rightarrow (2, 6)$$$.

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

const log = console.log

/********** MAIN *****************/
function main() {
    let t = parseInt(readline());
    let cols,line1,line2,g =[],a
    while(t-->0){
      cols = parseInt(readline());
      line1 = readline().split("")
      line2 = readline().split("")
      g.push(line1)
      g.push(line2)
      a=dfs(g,0,0,cols)
      a?log('YES'):log('NO')
      g =[]
    }
}

const dfs = (g,r,c,cols)=>{
  if(c===cols){
    return true
  }
  if(g[r][c]==='0' || g[r+1][c]==='0'){
    return dfs(g,r,c+1,cols)
  }
  else{
    return false
  }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function Queue() {
    this.length = 0;
}

Queue.prototype.push = function (item) {
  var node = {item: item};
  if (this.last) {
    this.last = this.last.next = node;
  } else {
    this.last = this.first = node;
  }
  this.length++;
};

Queue.prototype.shift = function () {
  var node = this.first;
  if (node) {
    this.first = node.next;
    if (!(--this.length)) {
      this.last = undefined;
    }
    return node.item;
  }
};

Queue.prototype.slice = function (start, end) {
  start = typeof start === 'undefined' ? 0 : start;
  end = typeof end === 'undefined' ? Infinity : end;

  var output = [];

  var i = 0;
  for (var node = this.first; node; node = node.next) {
    if (--end < 0) {
      break;
    } else if (++i > start) {
      output.push(node.item);
    }
  }
  return output;
}

class Logger {

  constructor() {
    this.enabled = false;
  }

  enable() {
    this.enabled = true;
  }

  disable() {
    this.enabled = false;
  }

  log(...str) {
    if (this.enabled) {
      console.error(...str);
    }
  }
}

let logger = new Logger();
// logger.enable();

function main() {

  let t = +readline();

  for (let i = 0; i < t; ++i) {
    let n = +readline();
    let a = readline();
    let b = readline();

    let canReachEnd = true;

    for (let j = 0; j < n; ++j) {
      if (a[j] == '1' && b[j] == '1') {
        canReachEnd = false;
        break;
      }
    }

    console.log(canReachEnd?'YES':'NO')

  }

}

'use strict';

function solve(n, s) {
  const dp = Array.from({
    length: n
  }, () => [0, 0]);
  for (let j = 0; j < 2; j++) if (s[j][0] === '0') dp[0][j] = 1;
  for (let i = 1; i < n; i++) {
    for (let j = 0; j < 2; j++) if (s[j][i] === '0' && (dp[i - 1][0] || dp[i - 1][1])) dp[i][j] = 1;
  }
  return dp[n - 1][0] || dp[n - 1][1] ? 'YES' : 'NO';
}

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

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

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

let ls = [];

function solve(){
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let q = 0; q < t; q++){
        const n = parseInt(ls[l++]);
        const s1 = ls[l++];
        const s2 = ls[l++];
        let res = 'YES';
        for (let i = 0; i < n; i++){
            if (s1[i] == '1' && s2[i] == '1'){
                res = 'NO';
                break;
            }
        }
        console.log(res);
    }
}

rl.on('line', (l) => ls.push(l));
rl.on('close', () => solve());

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

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i = 0; i < t; i++){
		let n = nl.num();
		let a = nl.line().split('');
		let b = nl.line().split('');
		let flag = true;
		for(let j = 0; j < n && flag; j++){
			if (a[j] === '1' && a[j] === b[j]) {
				flag = false;
			}
		}
		ans.push(flag);
	}
	console.log(ans.map(e => e?"YES":"NO").join('\n'));
};

process.stdin.on('end', sol);

let inputText = ''
process.stdin.on('data', c => inputText += c)

process.stdin.on('end', () => {

    const {EOL} = require('os')
    const lines = inputText.split(EOL) /*your input text, split by lines*/

    // console.log(lines);

    let pointer = 0;
    let k = parseInt(lines[pointer++]);
    outer : while (k -- > 0) {

        let len = parseInt(lines[pointer++]);
        let line1 = lines[pointer++];
        let line2 = lines[pointer++];

        // console.log("NO");
        for(let i = 0 ; i < len ; i++) {
            if(line1[i] === '1' && line2[i] === '1') {
                console.log("NO");
                continue outer;
            }
        }

        console.log("YES");
    }

    // [n, m, a] = inputText.split(' ');
    // let k1 = n / a;
    // let k2 = m / a;
    // console.log(Math.ceil(k1) * Math.ceil(k2))
})

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var dy = [-1,-1,-1,0,1,1,1,0];
	var dx = [-1,0,1,1,1,0,-1,-1];
	while(hasNext()){
		var N = nextInt();
		var s = [next(), next()];
		var list = new Array(2);
		for(var i = 0; i < 2; i++){
			list[i] = new Array(N).fill(false);
		}

		var queue = [];
		if(s[0][0] == "0"){
			queue.push([0,0]);
			list[0][0] = true;
		}
		while(queue.length > 0){
			var now = queue.shift();
			var y = now[0];
			var x = now[1];
			for(var i = 0; i < dy.length; i++){
				var nextY = y + dy[i];
				var nextX = x + dx[i];
				if(nextY < 2 && nextY >= 0 && nextX < N && nextX >= 0){
					if(s[nextY][nextX] == "0" && !list[nextY][nextX]){
						list[nextY][nextX] = true;
						queue.push([nextY, nextX]);
					}
				}
			}
		}
		myout((list[1][N - 1]) ? "YES" : "NO");
	}
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const grid = lines.slice(l, l + 2).map(str => str.trim())
        l += 2
        output[i] = solve(n, grid)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, grid) {
    const q = [[0, 0]]
    const visited = {}
    while (q.length) {
        // console.log(q)
        const [x, y] = q.shift()
        if (x === 1 && y === n - 1) return 'YES'
        const k = x + ',' + y
        if (visited[k]) continue
        visited[k] = 1

        add(n, grid, q, x, y + 1)
        add(n, grid, q, x + 1, y)
        add(n, grid, q, x + 1, y + 1)
        add(n, grid, q, x - 1, y)
        add(n, grid, q, x - 1, y + 1)
    }
    return 'NO'
}
function add(n, grid, q, x, y) {
    if (x >= 0 && x < 2 && y >= 0 && y < n && grid[x][y] === '0') {
        q.push([x, y])
    }
}

var t = parseInt(readline());
for (var i=0; i<t; i++) {
	var n = parseInt(readline());
	var l1 = readline().split('').map(function(x) { return parseInt(x); });
	var l2 = readline().split('').map(function(x) { return parseInt(x); });
	var b = true;
	for (var j=0; j<n; j++) {
		if (l1[j] === 1 && l2[j] === 1) {
			b = false;
			break;
		}
	}
	print(b ? 'YES' : 'NO');
}

var t = readline();
while (t-- > 0) {
    var n, c1, c2;
    n = readline();
    c1 = readline();
    c2 = readline();
    for (var i = 0; i < n; i++)
        if (c1[i] == '1' && c2[i] == '1')
            n = -1;
    write(n == -1 ? "NO\n" : "YES\n");
}

var testcase=parseInt(readline())
while(testcase--)
{
    var n=parseInt(readline())
    var s1=readline()
    var s2=readline()

    var ans=true
    var ind=0;
    while(ind<n)
    {
        var curr1=s1[ind]-'0';
        var curr2=s2[ind]-'0';
        if(curr1 && curr2)
        {
            ans=false;
        }
        ind++;

    }
    if(ans)
    {
        print("YES");
    }
    else
    {
        print("NO");
    }

}

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

  // multi line input
  readline.on('line', line => {
    input+=line
  });

  readline.on('end',()=>{
      console.log(input)
  })

/****************************************************************\
                   BISMILLAHIR RAHMANIR RAHIM
****************************************************************
               AUTHOR NAME: MD. TAHURUZZOHA TUHIN
\****************************************************************/

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {

    let n, m, p, mx = [], mn = [], mp = [], mk = [], mh = [], t;
    t = input();
    let a = 0;
    while (a < t) {
        a++;
        n = input();
        n = parseInt(n);
        m = input();
        p = input();

        for (const x of m) {
            mx.push(x.toString());
        }

        for (const x of p) {
            mn.push(x.toString());
        }
        mp = [mx, mn];
        for (let i = 0; i < 2; i++) {
            for (let j = 0; j < n; j++) {
                if (mp[i][j] === '0' && i == 0) {
                    mk.push(i + 1, j + 1);
                }
                if (mp[i][j] === '0' && i == 1) {
                    mh.push(i + 1, j + 1);
                }
            }
        }
        let mg = [...mk, ...mh];
        let cnt = 0, pnt = 1;
        for (let i = 0; i < mg.length / 2; i += 1) {
            let v1 = Math.abs(mg[i] - mg[i + 2]);
            if (v1 >= 2) pnt = 0;
        }

        if (pnt === 0) {
            for (let i = 0; i < mk.length; i += 2) {
                let v3 = Math.abs(mk[i] - mh[i]);
                let v4 = Math.abs(mk[i + 1] - mh[i + 1]);
                if (((v3 >= 2 || v4 >= 2))) {
                    cnt = 0;
                } else {
                    cnt = 1;
                }
            }
        }
        console.log((pnt || cnt ? "YES" : "NO"));
        mk.length = 0;
        mh.length = 0;
        mg.length = 0;
        mp.length = 0;
        mx.length = 0;
        mn.length = 0;
    }

}

/****************************************************************\
                   BISMILLAHIR RAHMANIR RAHIM
****************************************************************
               AUTHOR NAME: MD. TAHURUZZOHA TUHIN
\****************************************************************/

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {

    let n, m, p, mx = [], mn = [], mp = [], mk = [], mh = [], t;
    t = input();
    let a = 0;
    while (a < t) {
        a++;
        n = input();
        n = parseInt(n);
        m = input();
        p = input();

        for (const x of m) {
            mx.push(x.toString());
        }

        for (const x of p) {
            mn.push(x.toString());
        }
        mp = [mx, mn];
        for (let i = 0; i < 2; i++) {
            for (let j = 0; j < n; j++) {
                if (mp[i][j] === '0' && i == 0) {
                    mk.push(i + 1, j + 1);
                }
                if (mp[i][j] === '0' && i == 1) {
                    mh.push(i + 1, j + 1);
                }
            }
        }
        let mg = [...mk, ...mh];
        let cnt = 0, pnt = 1;
        for (let i = 0; i < mg.length / 2; i += 1) {
            let v1 = Math.abs(mg[i] - mg[i + 2]);
            if (v1 >= 2) pnt = 0;
        }

        if (pnt === 0) {
            for (let i = 0; i < mk.length; i += 2) {
                let v3 = Math.abs(mk[i] - mh[i]);
                let v4 = Math.abs(mk[i + 1] - mh[i + 1]);
                if (((v3 >= 2 || v4 >= 2))) {
                    cnt = 0;
                } else {
                    cnt = 1;
                }
            }
        }
        console.log((pnt || cnt ? "YES" : "NO"));
        mk = mk.splice(0, mk.lenth);
        mh = mh.splice(0, mh.lenth);
        mg = mg.splice(0, mg.lenth);
        mp = mp.splice(0, mp.lenth);
        mx = mx.splice(0, mx.lenth);
        mn = mn.splice(0, mn.lenth);
    }

}


Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 104) — number of pebbles of each type.

The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles.

NoteIn the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day.Optimal sequence of actions in the second sample case:   In the first day Anastasia collects 8 pebbles of the third type.  In the second day she collects 8 pebbles of the fourth type.  In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.  In the fourth day she collects 7 pebbles of the fifth type.  In the fifth day she collects 1 pebble of the second type.

// Polyfill for NodeJS
if (undefined == readline) {
	var rLines = require('fs').readFileSync("/dev/stdin", "utf8").split("\n"),
		rIndex = 0,
		readline = function() {
			rIndex ++
			return rLines[rIndex - 1]
		}
}
if (undefined == print) {
	var print = console.log
}

// Useful Read functions
var int = function() {
	return parseInt(readline())
}

var ints = function() {
	return readline().split(' ')
		.map(function(x) {
			return parseInt(x)
		})
}

var numbers = ints(),
	n = numbers[0],
	k = numbers[1],
	s = ints().reduce(function(s, x) {
		return s + Math.floor(x / k) + (x % k == 0 ? 0 : 1)
	}, 0)

print(Math.floor(s / 2) + (s % 2))

var params = readline().split(" ").map(function convert(value) {return +value; });

var n = params[0];
var k = params[1];

var counter = readline().split(" ").map(function convert(value) {return +value; })
									.reduce(function (total, current) {
										return total + (current - current % k) / k + (current % k !== 0);}, 0);

print((counter - counter % 2) / 2 + (counter % 2 !== 0));

"use strict";
if (typeof print == 'undefined') var print = console.log;
if (typeof readline == 'undefined') {
    let id = 0, lines = require('fs').readFileSync('/dev/stdin').toString().split('\n');
    var readline = () => lines[id ++];
}

let nums = () => readline().split(' ').map(x => +x);
let t = nums(), n = t[0], k = t[1];

let a = nums().map(x => Math.floor((x + k -1) / k)).reduce((m, n) => m + n, 0);
print(Math.floor((a + 1) / 2));

var g = readline().split(" ");
var n = +g[0];
var k = +g[1];
var y = readline().split(" ");
var sum = 0;
for(i=0;i<n;i++){
    sum += Math.ceil(+y[i]/k);
}
print(Math.ceil(sum/2))

var ints = function() {
	return readline().split(' ').map(function(n){
		return parseInt(n)
	})
}

var numbers = ints(),
	n = numbers[0],
	k = numbers[1],
	s = ints().reduce(function(s, n) {
		return s + Math.round(n / k)
	}, 0)

print(Math.round(s / 2))

"use strict";
if (typeof print == 'undefined') var print = console.log;
if (typeof readline == 'undefined') {
    let id = 0, lines = require('fs').readFileSync('/dev/stdin').toString().split('\n');
    var readline = () => lines[id ++];
}

let nums = () => readline().split(' ').map(x => +x);
let t = nums(), n = t[0], k = t[1];

let ans = 0, c = 0;
let a = nums().map(x => (ans += Math.floor(x / (2 * k)), x % (2 * k)));
for (let i of a) {
    if (i > k) ans ++;
    else ++c;
}
ans += c >>> 1; if (c & 1) ans++;
print(ans);


Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?There are $$$n$$$ students living in a building, and for each of them the favorite drink $$$a_i$$$ is known. So you know $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ ($$$1 \le a_i \le k$$$) is the type of the favorite drink of the $$$i$$$-th student. The drink types are numbered from $$$1$$$ to $$$k$$$.There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are $$$k$$$ types of drink sets, the $$$j$$$-th type contains two portions of the drink $$$j$$$. The available number of sets of each of the $$$k$$$ types is infinite.You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $$$\lceil \frac{n}{2} \rceil$$$, where $$$\lceil x \rceil$$$ is $$$x$$$ rounded up.After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $$$n$$$ is odd then one portion will remain unused and the students' teacher will drink it.What is the maximum number of students that can get their favorite drink if $$$\lceil \frac{n}{2} \rceil$$$ sets will be chosen optimally and students will distribute portions between themselves optimally?

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 1\,000$$$) — the number of students in the building and the number of different drinks. The next $$$n$$$ lines contain student's favorite drinks. The $$$i$$$-th line contains a single integer from $$$1$$$ to $$$k$$$ — the type of the favorite drink of the $$$i$$$-th student.

Print exactly one integer — the maximum number of students that can get a favorite drink.

NoteIn the first example, students could choose three sets with drinks $$$1$$$, $$$1$$$ and $$$2$$$ (so they will have two sets with two drinks of the type $$$1$$$ each and one set with two drinks of the type $$$2$$$, so portions will be $$$1, 1, 1, 1, 2, 2$$$). This way all students except the second one will get their favorite drinks.Another possible answer is sets with drinks $$$1$$$, $$$2$$$ and $$$3$$$. In this case the portions will be $$$1, 1, 2, 2, 3, 3$$$. Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with $$$a_i = 1$$$ (i.e. the first, the third or the fourth).

function main() {
    // write code here:
    const nk = stdin[0].split(' ').map(Number)
    var arr = new Array(nk[1]).fill(0),
        result = 0,
        t = 0;
    for (let i = 1; i <= nk[0]; i++) {
        var a = Number(stdin[i]) - 1;
        arr[a]++;
    }
    for (let j = 0; j < nk[1]; j++) {
        result += Math.floor(arr[j] / 2) * 2;
        //如果arr[j]为奇数，则先记录下来为奇数的个数
        if (arr[j] % 2 === 1) t++;
    }
    //在最后的 result 加上 （奇数个数+1）/ 2 的结果
    result += Math.floor((t + 1) / 2);
    console.log(result);
}

const readline = require('readline');
const rl = readline.createInterface({input: process.stdin});
var stdin = [];
rl.on('line', function (line) {
    stdin.push(line);
});
rl.on('close', main);

var r = readline().split(' ').map(Number);
var n = r[0], k = r[1], d = {};
for (var i = 0; i < n; i++) {
    var j = readline();
    d[j] = d[j] ? 0 : 1;
}
var x = Object.keys(d).reduce((r, i) => r + d[i], 0);
print(n - x + Math.ceil(x/2));

var n = Number(readline().split(' ')[0]), d = {};
for (var i = 0; i < n; i++) {var j = readline(); d[j] = d[j] ? 0 : 1;}
var x = Object.keys(d).reduce((r, i) => r + d[i], 0);
write(n - x + Math.ceil(x/2));

var arr = readline().split(' ').map(item => +item);
var n = arr[0], k = arr[1];

arr = new Array(k).fill(0);

for(var i = 0; i < n; i++) {
  var j = +readline() - 1;
  arr[j]++;
}

count = 0;
mod = 0;

for(var i = 0; i < arr.length; i++) {
  var j = arr[i] % 2;
  count += arr[i] - j;
  mod += j;
}

count += parseInt(mod / 2) + mod % 2;

print(count);

"use strict";

var main = function() {
    var input = rdAr();
    var n = input[0];
    var k = input[1];
    var C = crAr(2000, 0);
    for (var i = 0; i < n; ++i) {
        var a = +rd();
        C[a] = (++C[a]) % 2;
    }
    var r = C.reduce((v, a) => v + a);
    var bad = r >> 1;
    wr(n - bad);
};

const rd = readline;
const wr = write;
const pr = print;
const rdAr = () => rd().split(' ').map(v => +v);
const prAr = (a) => pr(a.join(' '));
const cmpLt = (a, b) => a - b;
const cmpGt = (a, b) => b - a;
Array.prototype.sortLt = function() { return this.sort(cmpLt); };
Array.prototype.sortGt = function() { return this.sort(cmpGt); };
const crAr = function(length, ...fillArgs) { return new Array(length).fill(...fillArgs); };

main();

var v = readline().split(' ');
v.map(x => Number(x));
var cnt = new Array;
cnt.length = v[1];
cnt.fill(0,0, v[1]);
for(var i = 0;i < v[0];i++){
    var x = Number(readline());
    cnt[x - 1]++;
}

var ans = 0;
var have = Math.floor((v[0] + 1)/2);
var t = 0;
for(i = 0;i < v[1];i++){
    ans += Math.floor( (cnt[i] / 2)) * 2;
    if(cnt[i] % 2 == 1) t++;
}
ans +=  Math.floor((t + 1)/2);
print(ans);


A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring.You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print "NO" (without quotes).A substring of a string is a contiguous subsequence of letters in the string. For example, "ab", "c", "abc" are substrings of string "abc", while "ac" is not a substring of that string.The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap.String a is lexicographically smaller than string b, if a is a prefix of b, or a has a smaller letter at the first position where a and b differ.

The first line contains integer n (1 ≤ n ≤ 105) — the number of strings in the set. Each of the next n lines contains a non-empty string consisting of lowercase English letters. It is guaranteed that the strings are distinct. The total length of the strings doesn't exceed 105.

Print the non-empty good string with minimum length. If several good strings exist, print lexicographically minimum among them. Print "NO" (without quotes) if there are no good strings.

NoteOne can show that in the first sample only two good strings with minimum length exist: "cfmailru" and "mailrucf". The first string is lexicographically minimum.

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var map = {};

alphabet.forEach(function(char) {
    map[char] = {
        used: false,
        to: undefined,
        from: undefined
    };
});

var n = Number(readline());
var hasResult = true;

cycle:
    for(var i = 0; i<n; i++) {
        var str = readline();

        for (var j = 0; j < str.length; j++) {
            var curChar = str[j];
            var nextChar = str[j+1];
            var prevChar = str[j-1];
            var to = map[curChar].to;
            var from = map[curChar].from;

            if (to && nextChar && to != nextChar ||
                from && prevChar && from != prevChar
            ) {
                hasResult = false;
                break cycle;
            }

            if (j != str.length -1 ) map[curChar].to = nextChar;
            if (j != 0 ) map[curChar].from = prevChar;
            map[curChar].used = true;
        }
    }

if (!hasResult) {
    print ("NO");
} else {
    var isOk = true;
    var result = '';
    var usedCount = 0;
    var charMapForStr = {};
    for(var i=0; i<alphabet.length; i++) {
        var char = alphabet[i];
        if (map[char].used) usedCount++;
        if (map[char].used && !map[char].from) {
            var curChar = char;
            result = result + curChar;
            if (charMapForStr[curChar]) {
                isOk = false;
                break;
            }
            charMapForStr[curChar] = true;
            while(map[curChar].to) {
                curChar = map[curChar].to;
                result = result + curChar;
                if (charMapForStr[curChar]) {
                    isOk = false;
                    break;
                }
                charMapForStr[curChar] = true;
            }
        }
    }
    if (!isOk ||usedCount > result.length) {
        print('NO');
    } else {
        print(result);
    }
}

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var map = {};

alphabet.forEach(function(char) {
    map[char] = {
        used: false,
        to: undefined,
        from: undefined
    };
});

var n = Number(readline());
var hasResult = true;

cycle:
    for(var i = 0; i<n; i++) {
        var str = readline();

        var charMapForStr = {};
        for (var j = 0; j < str.length; j++) {
            var curChar = str[j];
            var nextChar = str[j+1];
            var prevChar = str[j-1];
            var to = map[curChar].to;
            var from = map[curChar].from;

            if (charMapForStr[curChar] ||
                to && nextChar && to != nextChar ||
                from && prevChar && from != prevChar
            ) {
                hasResult = false;
                break cycle;
            }

            charMapForStr[curChar] = true;
            if (j != str.length -1 ) map[curChar].to = nextChar;
            if (j != 0 ) map[curChar].from = prevChar;
            map[curChar].used = true;
        }
    }

if (!hasResult) {
    print ("NO");
} else {
    var isOk = true;
    var result = '';
    var usedCount = 0;
    var charMapForStr = {};
    for(var i=0; i<alphabet.length; i++) {
        var char = alphabet[i];
        if (map[char].used) usedCount++;
        if (map[char].used && !map[char].from) {
            var curChar = char;
            result = result + curChar;
            if (charMapForStr[curChar]) {
                isOk = false;
                break;
            }
            charMapForStr[curChar] = true;
            while(map[curChar].to) {
                curChar = map[curChar].to;
                result = result + curChar;
                if (charMapForStr[curChar]) {
                    isOk = false;
                    break;
                }
                charMapForStr[curChar] = true;
            }
        }
    }
    if (!isOk ||usedCount > result.length) {
        print('NO');
    } else {
        print(result);
    }
}

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var map = {};

alphabet.forEach(function(char) {
	map[char] = {
		isFirstChar: false,
		used: false,
		direction: undefined
	};
});

var n = Number(readline());
var hasResult = true;

cycle:
for(var i = 0; i<n; i++) {
	var str = readline();

	var charMapForStr = {};
	for (var j = 0; j < str.length - 1; j++) {
		var curChar = str[j];
		var nextChar = str[j+1];
		var direction = map[curChar].direction;

		if (charMapForStr[curChar] || direction && direction != nextChar) {
			hasResult = false;
			break cycle;
		}

		charMapForStr[curChar] = true;
		if (map[curChar].isFirstChar) {
			map[curChar].isFirstChar = j===0;
		} else {
			map[curChar].isFirstChar = j===0 && !map[curChar].used;
		}
		map[curChar].used = true;
		map[curChar].direction = nextChar;
	}
	var lastChar = str[str.length - 1];
	map[lastChar].used = true;
	if (charMapForStr[lastChar]) {
		hasResult = false;
		break cycle;
	}
}

if (!hasResult) {
	print ("NO");
} else {
	var result = '';
	alphabet.forEach(function(char) {
		if (map[char].isFirstChar) {
			var curChar = char;
			result = result + curChar;
			while(map[curChar].direction) {
				curChar = map[curChar].direction;
				result = result + curChar;
			}
		}
	});
	print(result);
}

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var map = {};

alphabet.forEach(function(char) {
	map[char] = {
		isFirstChar: false,
		used: false,
		direction: undefined
	};
});

var n = Number(readline());
var hasResult = true;

cycle:
for(var i = 0; i<n; i++) {
	var str = readline();

	var charMapForStr = {};
	for (var j = 0; j < str.length; j++) {
		var curChar = str[j];
		var nextChar = str[j+1];
		var direction = map[curChar].direction;

		if (charMapForStr[curChar] || direction && nextChar && direction != nextChar) {
			hasResult = false;
			break cycle;
		}

		charMapForStr[curChar] = true;
		if (map[curChar].isFirstChar) {
			map[curChar].isFirstChar = j===0;
		} else {
			map[curChar].isFirstChar = j===0 && !map[curChar].used;
		}
		map[curChar].used = true;
		if (j != str.length -1 ) map[curChar].direction = nextChar;
	}
}

if (!hasResult) {
	print ("NO");
} else {
	var result = '';
	alphabet.forEach(function(char) {
		if (map[char].isFirstChar) {
			var curChar = char;
			result = result + curChar;
			while(map[curChar].direction) {
				curChar = map[curChar].direction;
				result = result + curChar;
			}
		}
	});
	print(result);
}

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var map = {};

alphabet.forEach(function(char) {
    map[char] = {
        used: false,
        to: undefined,
        from: undefined
    };
});

var n = Number(readline());
var hasResult = true;

cycle:
    for(var i = 0; i<n; i++) {
        var str = readline();

        var charMapForStr = {};
        for (var j = 0; j < str.length; j++) {
            var curChar = str[j];
            var nextChar = str[j+1];
            var prevChar = str[j-1];
            var to = map[curChar].to;
            var from = map[curChar].from;

            if (charMapForStr[curChar] ||
                to && nextChar && to != nextChar ||
                from && prevChar && from != prevChar
            ) {
                hasResult = false;
                break cycle;
            }

            charMapForStr[curChar] = true;
            if (j != str.length -1 ) map[curChar].to = nextChar;
            if (j != 0 ) map[curChar].from = prevChar;
            map[curChar].used = true;
        }
    }

if (!hasResult) {
    print ("NO");
} else {
    var isOk = true;
    var result = '';
    var charMapForStr = {};
    for(var i=0; i<alphabet.length; i++) {
        var char = alphabet[i];
        if (map[char].used && !map[char].from) {
            var curChar = char;
            result = result + curChar;
            if (charMapForStr[curChar]) {
                isOk = false;
                break;
            }
            charMapForStr[curChar] = true;
            while(map[curChar].to) {
                curChar = map[curChar].to;
                result = result + curChar;
                if (charMapForStr[curChar]) {
                    isOk = false;
                    break;
                }
                charMapForStr[curChar] = true;
            }
        }
    }
    if (result === 'crehpuqmbao') {
        Object.keys(map).forEach(function(key) {
            print(key + ": used = " + map[key].used + ", from = " + map[key].from + ", to = " + map[key].to);
        })
    }
    if (!result || !isOk) {
        print('NO');
    } else {
        print(result);
    }
}

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var map = {};

alphabet.forEach(function(char) {
	map[char] = {
		isFirstChar: false,
		used: false,
		direction: undefined
	};
});

var n = Number(readline());
var hasResult = true;

cycle:
for(var i = 0; i<n; i++) {
	var str = readline();

	var charMapForStr = {};
	for (var j = 0; j < str.length; j++) {
		var curChar = str[j];
		var nextChar = str[j+1];
		var direction = map[curChar].direction;

		if (charMapForStr[curChar] || direction && nextChar && direction != nextChar) {
			hasResult = false;
			break cycle;
		}

		charMapForStr[curChar] = true;
		if (map[curChar].isFirstChar) {
			map[curChar].isFirstChar = j===0;
		} else {
			map[curChar].isFirstChar = j===0 && !map[curChar].used;
		}
		map[curChar].used = true;
		if (j != str.length -1 ) map[curChar].direction = nextChar;
	}
}

if (!hasResult) {
	print ("NO");
} else {
	var result = '';
	alphabet.forEach(function(char) {
		if (map[char].isFirstChar) {
			var curChar = char;
			result = result + curChar;
			while(map[curChar].direction) {
				curChar = map[curChar].direction;
				result = result + curChar;
			}
		}
	});
	var isOk = true;
	var charMapForStr = {};
	for (var j = 0; j < result.length; j++) {
	    if (charMapForStr[result[j]]) {
	        isOk = false;
	        break;
	    }
	    charMapForStr[result[j]] = true;
	}
	if (!result || !isOk) {
	    print('NO');
	}
	print(result);
}

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var map = {};

alphabet.forEach(function(char) {
    map[char] = {
        to: undefined,
        from: undefined
    };
});

var n = Number(readline());
var hasResult = true;

cycle:
    for(var i = 0; i<n; i++) {
        var str = readline();

        var charMapForStr = {};
        for (var j = 0; j < str.length; j++) {
            var curChar = str[j];
            var nextChar = str[j+1];
            var prevChar = str[j-1];
            var to = map[curChar].to;
            var from = map[curChar].from;

            if (charMapForStr[curChar] ||
                to && nextChar && to != nextChar ||
                from && prevChar && from != prevChar
                ) {
                hasResult = false;
                break cycle;
            }

            charMapForStr[curChar] = true;
            if (j != str.length -1 ) map[curChar].to = nextChar;
            if (j != 0 ) map[curChar].from = prevChar;
        }
    }

if (!hasResult) {
    print ("NO");
} else {
    var isOk = true;
    var result = '';
    var charMapForStr = {};
    for(var i=0; i<alphabet.length; i++) {
        var char = alphabet[i];
        if (!map[char].from) {
            var curChar = char;
            result = result + curChar;
            if (charMapForStr[curChar]) {
                isOk = false;
                break;
            }
            charMapForStr[curChar] = true;
            while(map[curChar].to) {
                curChar = map[curChar].to;
                result = result + curChar;
                if (charMapForStr[curChar]) {
                    isOk = false;
                    break;
                }
                charMapForStr[curChar] = true;
            }
        }
    }
    if (!isOk) {
        print('NO');
    } else {
        print(result);
    }
}

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var map = {};

alphabet.forEach(function(char) {
    map[char] = {
        used: false,
        to: undefined,
        from: undefined
    };
});

var n = Number(readline());
var hasResult = true;

cycle:
    for(var i = 0; i<n; i++) {
        var str = readline();

        var charMapForStr = {};
        for (var j = 0; j < str.length; j++) {
            var curChar = str[j];
            var nextChar = str[j+1];
            var prevChar = str[j-1];
            var to = map[curChar].to;
            var from = map[curChar].from;

            if (charMapForStr[curChar] ||
                to && nextChar && to != nextChar ||
                from && prevChar && from != prevChar
            ) {
                hasResult = false;
                break cycle;
            }

            charMapForStr[curChar] = true;
            if (j != str.length -1 ) map[curChar].to = nextChar;
            if (j != 0 ) map[curChar].from = prevChar;
            map[curChar].used = true;
        }
    }

if (!hasResult) {
    print ("NO");
} else {
    var isOk = true;
    var result = '';
    var charMapForStr = {};
    for(var i=0; i<alphabet.length; i++) {
        var char = alphabet[i];
        if (map[char].used && !map[char].from) {
            var curChar = char;
            result = result + curChar;
            if (charMapForStr[curChar]) {
                isOk = false;
                break;
            }
            charMapForStr[curChar] = true;
            while(map[curChar].to) {
                curChar = map[curChar].to;
                result = result + curChar;
                if (charMapForStr[curChar]) {
                    isOk = false;
                    break;
                }
                charMapForStr[curChar] = true;
            }
        }
    }
    if (result === 'crehpuqmbao') {
        Object.keys(map).forEach(function(key) {
            print(key + ":u=" + map[key].used + ",f=" + map[key].from + ",t=" + map[key].to);
        })
    }
    if (!result || !isOk) {
        print('NO');
    } else {
        print(result);
    }
}

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var map = {};

alphabet.forEach(function(char) {
	map[char] = {
		isFirstChar: false,
		used: false,
		direction: undefined
	};
});

var n = Number(readline());
var hasResult = true;

cycle:
for(var i = 0; i<n; i++) {
	var str = readline();

	var charMapForStr = {};
	for (var j = 0; j < str.length; j++) {
		var curChar = str[j];
		var nextChar = str[j+1];
		var direction = map[curChar].direction;

		if (charMapForStr[curChar] || direction && nextChar && direction != nextChar) {
			hasResult = false;
			break cycle;
		}

		charMapForStr[curChar] = true;
		if (map[curChar].isFirstChar) {
			map[curChar].isFirstChar = j===0;
		} else {
			map[curChar].isFirstChar = j===0 && !map[curChar].used;
		}
		map[curChar].used = true;
		if (j != str.length -1 ) map[curChar].direction = nextChar;
	}
}

if (!hasResult) {
	print ("NO");
} else {
	var result = '';
	alphabet.forEach(function(char) {
		if (map[char].isFirstChar) {
			var curChar = char;
			result = result + curChar;
			while(map[curChar].direction) {
				curChar = map[curChar].direction;
				result = result + curChar;
			}
		}
	});
	var isOk = true;
	var charMapForStr = {};
	for (var j = 0; j < result.length; j++) {
	    if (charMapForStr[result[j]]) {
	        isOk = false;
	        break;
	    }
	    charMapForStr[result[j]] = true;
	}
	if (!result || !isOk) {
	    print('NO');
	} else {
	    print(result);
	}
}

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var map = {};

alphabet.forEach(function(char) {
    map[char] = {
        used: false,
        to: undefined,
        from: undefined
    };
});

var n = Number(readline());
var hasResult = true;

cycle:
    for(var i = 0; i<n; i++) {
        var str = readline();

        var charMapForStr = {};
        for (var j = 0; j < str.length; j++) {
            var curChar = str[j];
            var nextChar = str[j+1];
            var prevChar = str[j-1];
            var to = map[curChar].to;
            var from = map[curChar].from;

            if (charMapForStr[curChar] ||
                to && nextChar && to != nextChar ||
                from && prevChar && from != prevChar
            ) {
                hasResult = false;
                break cycle;
            }

            charMapForStr[curChar] = true;
            if (j != str.length -1 ) map[curChar].to = nextChar;
            if (j != 0 ) map[curChar].from = prevChar;
            map[curChar].used = true;
        }
    }

if (!hasResult) {
    print ("NO");
} else {
    var isOk = true;
    var result = '';
    var charMapForStr = {};
    for(var i=0; i<alphabet.length; i++) {
        var char = alphabet[i];
        if (map[char].used && !map[char].from) {
            var curChar = char;
            result = result + curChar;
            if (charMapForStr[curChar]) {
                isOk = false;
                break;
            }
            charMapForStr[curChar] = true;
            while(map[curChar].to) {
                curChar = map[curChar].to;
                result = result + curChar;
                if (charMapForStr[curChar]) {
                    isOk = false;
                    break;
                }
                charMapForStr[curChar] = true;
            }
        }
    }
    if (!result || !isOk) {
        print('NO');
    } else {
        print(result);
    }
}

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var map = {};

alphabet.forEach(function(char) {
    map[char] = {
        used: false,
        to: undefined,
        from: undefined
    };
});

var n = Number(readline());
var hasResult = true;

cycle:
    for(var i = 0; i<n; i++) {
        var str = readline();

        var charMapForStr = {};
        for (var j = 0; j < str.length; j++) {
            var curChar = str[j];
            var nextChar = str[j+1];
            var prevChar = str[j-1];
            var to = map[curChar].to;
            var from = map[curChar].from;

            if (charMapForStr[curChar] ||
                to && nextChar && to != nextChar ||
                from && prevChar && from != prevChar
            ) {
                hasResult = false;
                break cycle;
            }

            charMapForStr[curChar] = true;
            if (j != str.length -1 ) map[curChar].to = nextChar;
            if (j != 0 ) map[curChar].from = prevChar;
            map[curChar].used = true;
        }
    }

if (!hasResult) {
    print ("NO");
} else {
    var isOk = true;
    var result = '';
    var charMapForStr = {};
    for(var i=0; i<alphabet.length; i++) {
        var char = alphabet[i];
        if (map[char].used && !map[char].from) {
            var curChar = char;
            result = result + curChar;
            if (charMapForStr[curChar]) {
                isOk = false;
                break;
            }
            charMapForStr[curChar] = true;
            while(map[curChar].to) {
                curChar = map[curChar].to;
                result = result + curChar;
                if (charMapForStr[curChar]) {
                    isOk = false;
                    break;
                }
                charMapForStr[curChar] = true;
            }
        }
    }
    if (!isOk) {
        print('NO');
    } else {
        print(result);
    }
}


A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).You are given a permutation of $$$1,2,\dots,n$$$, $$$[a_1,a_2,\dots,a_n]$$$. For integers $$$i$$$, $$$j$$$ such that $$$1\le i<j\le n$$$, define $$$\operatorname{mn}(i,j)$$$ as $$$\min\limits_{k=i}^j a_k$$$, and define $$$\operatorname{mx}(i,j)$$$ as $$$\max\limits_{k=i}^j a_k$$$.Let us build an undirected graph of $$$n$$$ vertices, numbered $$$1$$$ to $$$n$$$. For every pair of integers $$$1\le i<j\le n$$$, if $$$\operatorname{mn}(i,j)=a_i$$$ and $$$\operatorname{mx}(i,j)=a_j$$$ both holds, or $$$\operatorname{mn}(i,j)=a_j$$$ and $$$\operatorname{mx}(i,j)=a_i$$$ both holds, add an undirected edge of length $$$1$$$ between vertices $$$i$$$ and $$$j$$$.In this graph, find the length of the shortest path from vertex $$$1$$$ to vertex $$$n$$$. We can prove that $$$1$$$ and $$$n$$$ will always be connected via some path, so a shortest path always exists.

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

For each test case, print a single line containing one integer — the length of the shortest path from $$$1$$$ to $$$n$$$.

NoteThe following are illustrations of constructed graphs in example test cases.    the constructed graph in test case 1     the constructed graph in test case 2     the constructed graph in test case 3     the constructed graph in test case 4     the constructed graph in test case 5

'use strict';

function solve(n, a) {
  if (n === 1) return 0;
  const next = new Array(n),
        mxr = [],
        mnr = [];
  for (let i = n - 1; i >= 0; i--) {
    var _mnr;
    while (mxr.length && a[mxr[mxr.length - 1]] < a[i]) mxr.pop();
    while (mnr.length && a[mnr[mnr.length - 1]] > a[i]) mnr.pop();
    if (mxr.length && mxr[mxr.length - 1] < ((_mnr = mnr[mnr.length - 1]) !== null && _mnr !== void 0 ? _mnr : Infinity)) {
      var _mnr2;
      let t = (_mnr2 = mnr[mnr.length - 1]) !== null && _mnr2 !== void 0 ? _mnr2 : Infinity;
      let j = binarySearch(mxr, 0, mxr.length - 1, j => mxr[j] > t);
      next[i] = mxr[j];
    } else if (mnr.length) {
      var _mxr;
      let t = (_mxr = mxr[mxr.length - 1]) !== null && _mxr !== void 0 ? _mxr : Infinity;
      let j = binarySearch(mnr, 0, mnr.length - 1, j => mnr[j] > t);
      next[i] = mnr[j];
    }
    mxr.push(i);
    mnr.push(i);
  }
  let res = 0;
  for (let i = 0; i < n - 1; i = next[i]) res++;
  return res;
}
function binarySearch(arr, l, r, comp) {
  while (l < r) {
    const m = l + r >> 1;
    if (comp(m)) l = m + 1;else r = m;
  }
  return l;
}

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

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

'use strict';

function solve(n, a) {
  if (n === 1) return 0;
  const mnl = new Array(n).fill(-1),
        mnr = new Array(n).fill(n);
  let st = [];
  for (let i = 0; i < n; i++) {
    while (st.length && a[st[st.length - 1]] > a[i]) st.pop();
    if (st.length) mnl[i] = st[st.length - 1];
    st.push(i);
  }
  st = [];
  for (let i = n - 1; i >= 0; i--) {
    while (st.length && a[st[st.length - 1]] > a[i]) st.pop();
    if (st.length) mnr[i] = st[st.length - 1];
    st.push(i);
  }
  const h = new Array(n).fill(-1),
        e = [],
        ne = [];
  let idx = 0;
  const add = (i, j) => {
    e[idx] = j, ne[idx] = h[i], h[i] = idx++;
  };
  st = [];
  for (let i = 0; i < n; i++) {
    while (st.length && a[st[st.length - 1]] < a[i]) st.pop();
    for (let j = st.length - 1; j >= 0; j--) {
      if (st[j] < mnl[i]) break;
      add(i, st[j]);
      add(st[j], i);
    }
    st.push(i);
  }
  st = [];
  for (let i = n - 1; i >= 0; i--) {
    while (st.length && a[st[st.length - 1]] < a[i]) st.pop();
    for (let j = st.length - 1; j >= 0; j--) {
      if (st[j] > mnr[i]) break;
      add(i, st[j]);
      add(st[j], i);
    }
    st.push(i);
  }
  let query = [0],
      vis = new Array(n),
      dis = 0;
  while (1) {
    dis++;
    const tmp = [];
    for (let u of query) {
      vis[u] = 1;
      for (let k = h[u]; k !== -1; k = ne[k]) {
        const v = e[k];
        if (vis[v]) continue;
        if (v === n - 1) {
          process.stdout.write(dis + '\n');
          return;
        }
        tmp.push(v);
      }
    }
    query = tmp;
  }
}

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

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


You are given two arrays $$$a$$$ and $$$b$$$, consisting of $$$n$$$ integers each.Let's define a function $$$f(a, b)$$$ as follows:   let's define an array $$$c$$$ of size $$$n$$$, where $$$c_i = a_i \oplus b_i$$$ ($$$\oplus$$$ denotes bitwise XOR);  the value of the function is $$$c_1 \mathbin{\&} c_2 \mathbin{\&} \cdots \mathbin{\&} c_n$$$ (i.e. bitwise AND of the entire array $$$c$$$). Find the maximum value of the function $$$f(a, b)$$$ if you can reorder the array $$$b$$$ in an arbitrary way (leaving the initial order is also an option).

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of arrays $$$a$$$ and $$$b$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < 2^{30}$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \le b_i < 2^{30}$$$). The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the maximum value of the function $$$f(a, b)$$$ if you can reorder the array $$$b$$$ in an arbitrary way.

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const sa = lines[l++].trim().split(' ').map(Number)
        const sb = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, sa, sb)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, sa, sb) {
    let r = 0
    for (let k = 29; k >= 0; k--) {
        const mask = r | (1 << k)
        const m1 = {}
        const m2 = {}
        for (let i = 0; i < n; i++) {
            const k1 = sa[i] & mask
            const k2 = sb[i] & mask
            m1[k1] = (m1[k1] || 0) + 1
            m2[k2] = (m2[k2] || 0) + 1
        }
        // console.log(k, m1, m2)
        let ok = 1
        for (let h1 in m1) {
            const h2 = (~h1) & mask
            if (m1[h1] !== m2[h2]) {
                ok = 0
                break
            }
        }
        if (ok) r |= (1 << k)
    }
    return r
}