One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of $$$n$$$ non-negative integers.If there are exactly $$$K$$$ distinct values in the array, then we need $$$k = \lceil \log_{2} K \rceil$$$ bits to store each value. It then takes $$$nk$$$ bits to store the whole file.To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers $$$l \le r$$$, and after that all intensity values are changed in the following way: if the intensity value is within the range $$$[l;r]$$$, we don't change it. If it is less than $$$l$$$, we change it to $$$l$$$; if it is greater than $$$r$$$, we change it to $$$r$$$. You can see that we lose some low and some high intensities.Your task is to apply this compression in such a way that the file fits onto a disk of size $$$I$$$ bytes, and the number of changed elements in the array is minimal possible.We remind you that $$$1$$$ byte contains $$$8$$$ bits.$$$k = \lceil log_{2} K \rceil$$$ is the smallest integer such that $$$K \le 2^{k}$$$. In particular, if $$$K = 1$$$, then $$$k = 0$$$.

The first line contains two integers $$$n$$$ and $$$I$$$ ($$$1 \le n \le 4 \cdot 10^{5}$$$, $$$1 \le I \le 10^{8}$$$) — the length of the array and the size of the disk in bytes, respectively. The next line contains $$$n$$$ integers $$$a_{i}$$$ ($$$0 \le a_{i} \le 10^{9}$$$) — the array denoting the sound file.

Print a single integer — the minimal possible number of changed elements.

NoteIn the first example we can choose $$$l=2, r=3$$$. The array becomes 2 2 2 3 3 3, the number of distinct elements is $$$K=2$$$, and the sound file fits onto the disk. Only two values are changed.In the second example the disk is larger, so the initial file fits it and no changes are required.In the third example we have to change both 1s or both 3s.

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

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

    var M = {};
    for (var i = 0; i < A.length; ++i) {
        var val = A[i];
        M[val] = ++M[val] || 1;
    }

    var K = Object.keys(M);
    var uniqueK = K.length;

    var fullBits = I*8;
    var bitsForElem = Math.floor(fullBits/n);
    var maxUniqueK = Math.pow(2, bitsForElem);

    if (maxUniqueK >= uniqueK) {
        wr(0);
    } else {
        var needToCut = uniqueK - maxUniqueK;
        //prOb(M);
        var Klen = K.length;
        var superA = [];
        for (var i = 0; i < K.length; ++i) {
            superA.push(M[K[i]]);
        }
        superA = superA.concat(superA);
        //prAr(superA);
        var sum = 0;
        for (var i = Klen - needToCut; i < Klen; ++i) {
            sum += superA[i];
        }
        //pr(sum)
        var subsum = sum;
        var cnt = 0;
        for (var l = Klen - needToCut, r = Klen; l < Klen; ++l, ++r) {
            cnt++;
            subsum -= superA[l];
            subsum += superA[r];
            if (subsum < sum) {
                sum = subsum;
            }
        }
        //pr(needToCut, cnt);
        wr(sum);
    }
};

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

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


Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:Define the score of X to be the sum of the elements of X modulo p.Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that:   Each part contains at least 1 element of A, and each part consists of contiguous elements of A.  The two parts do not overlap.  The total sum S of the scores of those two parts is maximized. This is the encryption code. Output the sum S, which is the encryption code.

The first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively. The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].

Output the number S as described in the problem statement.

NoteIn the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of .In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is .

var num = readline().split(' ')
var n = parseInt(num[0])
var m = parseInt(num[1])
var arr = readline().split(' ')

// var arr1 = []
// for(var i=0; i<n; i++) {
//     arr1.push(parseInt(arr[i]))
// }

//print(arr1.length)
var sum1 = 0, sum2 = 0;
for(var i=0; i<n; i++) {
        sum1 += parseInt(arr[i])
}
var b, k=-999
for(var i=0; i<n-1; i++) {
    sum2 += parseInt(arr[i])
    b = (sum2%m) + ((sum1-sum2)%m)
    k = Math.max(k,b)
}
//var k = (sum1%m) + (sum2%m)
print(k)

var num = readline().split(' ')
var n = parseInt(num[0])
var m = parseInt(num[1])
var arr = readline().split(' ')

var arr1 = []
for(var i=0; i<n; i++) {
    arr1.push(parseInt(arr[i]))
}

//print(arr1.length)
var sum1 = 0, sum2 = 0;
for(var i=0; i<n; i++) {
        sum1 += arr1[i]
}
var b, k=-999
for(var i=0; i<n-1; i++) {
    sum2 += arr1[i];
    b = (sum2%m) + ((sum1-sum2)%m)
    k = Math.max(k,b)
}
//var k = (sum1%m) + (sum2%m)
print(k)

//var input = readline()

var num = readline().split(' ')
var n = parseInt(num[0])
var m = parseInt(num[1])
var arr = readline().split(' ')

var arr1 = []
for(var i=0; i<n; i++) {
    arr1.push(parseInt(arr[i]))
}
//print(arr1.length)
var sum1 = 0, sum2 = 0;
for(var i=0; i<n; i++) {
    if(i<(n/2)) {
        sum1 += arr1[i]
    }
    else {
        sum2 += arr1[i]
    }
}
//print(sum1 +' '+ sum2)
var k = (sum1%m) + (sum2%m)
print(k)


Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of a single line that contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^{18}$$$) — the number of computers and the number of patch cables.

For each test case print one integer — the minimum number of hours required to copy the update files to all $$$n$$$ computers.

NoteLet's consider the test cases of the example:  $$$n=8$$$, $$$k=3$$$:   during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$;  during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$;  during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, from the computer $$$2$$$ to the computer $$$6$$$, and from the computer $$$3$$$ to the computer $$$7$$$;  during the fourth hour, we copy the update files from the computer $$$2$$$ to the computer $$$8$$$.   $$$n=6$$$, $$$k=6$$$:   during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$;  during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$, and from the computer $$$2$$$ to the computer $$$4$$$;  during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$5$$$, and from the computer $$$2$$$ to the computer $$$6$$$.   $$$n=7$$$, $$$k=1$$$:   during the first hour, we copy the update files from the computer $$$1$$$ to the computer $$$2$$$;  during the second hour, we copy the update files from the computer $$$1$$$ to the computer $$$3$$$;  during the third hour, we copy the update files from the computer $$$1$$$ to the computer $$$4$$$;  during the fourth hour, we copy the update files from the computer $$$4$$$ to the computer $$$5$$$;  during the fifth hour, we copy the update files from the computer $$$4$$$ to the computer $$$6$$$;  during the sixth hour, we copy the update files from the computer $$$3$$$ to the computer $$$7$$$.

const solve = (n,k)=>{
     let i = 0n,cable = 1n;
     while(cable<k){
          cable*=2n;
          i++;
     }
     if(cable<n){
          let t = (n-cable)+k-1n;
          i+=(t/k);
     }
     console.log(i+"");
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let [n,k] =  readline().trim().split(" ").map(cur=>BigInt(cur));
       solve(n,k);
  }
}
main();

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => BigInt(x));

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();

		let tot = 1n, hr = 0n;
		while (tot < k) {
			tot *= 2n;
			hr++;
		}

		if (tot < n) {
			hr += (n-tot+k-1n)/ k;
		}

		console.log(hr.toString());
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => BigInt(x));

function ceilDiv (a, b)  {
	let res = a / b;
	if (res*b != a)
		res++;
	return res;
}

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();

		let tot = 1n, hr = 0n;
		while (tot < n) {
			const cablesToUse = tot;
			if (cablesToUse >= k) {
				hr += ceilDiv(n-tot, k);
				break;
			}

			tot += cablesToUse;
			hr++;
		}

		console.log(hr.toString());
	}
}

const readline = require('readline')

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

function solve(n, k) {
    let cur = 1n
    let h = 0n
    while (cur < k) {
    // while (cur < n) {
        cur += k < cur ? k : cur
        h++
    }
    // return h
    return h + ceil(n - cur, k)
}
function ceil(a, b) {
    const k = a / b
    return a / b + (k * b < a ? 1n : 0n)
}

const solve = (n,k)=>{
     if(n===1n){
          console.log(0);
          return;
     }
     if(k===1n){
          console.log((n-1n)+"");
          return;
     }
     let l,j = n&(n-1n),cnt=0,h=n;
     if(j===0n){
          while(h!==1n){
               cnt++;
               h = h>>1n;
          }
     }
     else{
          while(h!==0n){
               cnt++;
               h = h>>1n;
          }
     }
     if(cnt<=k) {
          console.log(cnt+"");
          return;
     }
     h1 = n-((1n<<(k-1n))+k);
     if((h1)%k===0n) console.log(k+((h1)/k)+"");
     else console.log(k+((h1)/k)+1n+"");
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let [n,k] =  readline().trim().split(" ").map(cur=>BigInt(cur));
       solve(n,k);
  }
}
main();

const solve = (n,k)=>{
     if(n===1n){
          console.log(0);
          return;
     }
     if(k===1n){
          console.log((n-1n)+"");
          return;
     }
     let l,j = n&(n-1n),cnt;
     if(j===0n) cnt = 1n;
     else cnt = 0n;
     let h = n,h1;
     while(h!==0n){
          cnt++;
          h = h>>1n;
     }
     if(cnt<=k) {
          console.log(cnt+"");
          return;
     }
     h1 = n-((1n<<(k-1n))+k);
     if((h1)%k===0n) console.log(k+((h1)/k)+"");
     else console.log(k+((h1)/k)+1n+"");
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let [n,k] =  readline().trim().split(" ").map(cur=>BigInt(cur));
       solve(n,k);
  }
}
main();

const solve = (n,k)=>{
     if(n===1n){
          console.log(0);
          return;
     }
     if((k===1n)||(n===2n)){
          console.log((n-1n)+"");
          return;
     }
     let l,j = n^(n-1n);
     if(j===0n) l = 1n;
     else l = 0n;
     let cnt = 0n,h = n,h1;
     while(h!==l){
          cnt++;
          h = h>>1n;
     }
     if(cnt<=k) {
          console.log(cnt+"");
          return;
     }
     h1 = n-((1n<<(k-1n))+k);
     if((h1)%k===0n) console.log(k+((h1)/k)+"");
     else console.log(k+((h1)/k)+1n+"");
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let [n,k] =  readline().trim().split(" ").map(cur=>BigInt(cur));
       solve(n,k);
  }
}
main();

const solve = (n,k)=>{
     if(n===1n){
          console.log(0);
          return;
     }
     if(k===1n){
          console.log((n-1n)+"");
          return;
     }
     let t;
     for(let i=1n;i<=k;i++){
          t = ((i *(i+1n))/2n)+1n;
          if(t>=n){
               console.log(i+"");
               return;
          }
     }
     let h = n-t;
     if(h%k===0n) console.log(k+(h/k)+"");
     else console.log(k+(h/k)+1n+"");
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let [n,k] =  readline().trim().split(" ").map(cur=>BigInt(cur));
       solve(n,k);
  }
}
main();

const solve = (n,k)=>{
     if(n===1n){
          console.log(0);
          return;
     }
     if(k===1n){
          console.log((n-1n)+"");
          return;
     }
     let t;
     for(let i=1n;i<=k;i++){
          t = ((i *(i+1n))/2n)+1n;
          if(t>=n){
               console.log(i+"");
               return;
          }
     }
     let h = n-t;
     if((n-t)%k===0) console.log(k+(h/k)+"");
     else console.log(k+(h/k)+1n+"");
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let [n,k] =  readline().trim().split(" ").map(cur=>BigInt(cur));
       solve(n,k);
  }
}
main();

const solve = (n,k)=>{
     if(n===1n){
          console.log(0);
          return;
     }
     if(k===1n){
          console.log((n-1n)+"");
          return;
     }
     if(k>=n/2n){
          console.log((n/2n)+"");
          return;
     }
     let h = k*2n;
     let res = n-h;
     if(res%k===0n) console.log(k+(res/k)+"");
     else console.log(k+(res/k)+1n+"")
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let [n,k] =  readline().trim().split(" ").map(cur=>BigInt(cur));
       solve(n,k);
  }
}
main();

const solve = (n,k)=>{
     if(n===1n){
          console.log(0);
          return;
     }
     if(k===1n){
          console.log((n-1n)+"");
          return;
     }
     if(k>=n/2n){
          if(n%2n===0n) console.log((n/2n)+"");
          else console.log((n/2n)+1n+"");
          return;
     }
     let h = k*2n;
     let res = n-h;
     if(res%k===0n) console.log(k+(res/k)+"");
     else console.log(k+(res/k)+1n+"")
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let [n,k] =  readline().trim().split(" ").map(cur=>BigInt(cur));
       solve(n,k);
  }
}
main();

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => BigInt(x));

function ceilDiv (a, b)  {
	let res = a / b;
	if (res*b != a)
		res++;
	return res;
}

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();

		let tot = 1n, hr = 0;
		while (tot < n) {
			const cablesToUse = tot;
			if (cablesToUse >= k) {
				hr += Number(ceilDiv(n-tot, k));
				break;
			}

			tot += cablesToUse;
			hr++;
		}

		console.log(hr);
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

function main () {
	let T = rn();
	while (T--) {
		const [n, k] = rna();

		let tot = 1, hr = 0;
		while (tot < n) {
			const cablesToUse = Math.min(tot, k);
			if (cablesToUse == k) {
				hr += Math.ceil((n-tot)/k);
				break;
			}

			tot += cablesToUse;
			hr++;
		}

		console.log(hr);
	}
}


The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:  employee ::= name. | name:employee1,employee2, ... ,employeek.  name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.

The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.

Print a single number — the number of uncomfortable situations in the company.

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

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

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

var periodOrColon = /[.:]/;

function displayTree(employee, depth) {
	var line = [];
	for (var tabIndex = 0; tabIndex < depth; ++tabIndex) {
		line.push("    ");
		}
	line.push(employee.name);

	var subordinates = employee.subordinates;
	if (subordinates.length == 0) {
		print(line.join(""));
		return;
	}

	line.push(":");
	print(line.join(""));
	for (var subordinateIndex = 0; subordinateIndex < subordinates.length; ++subordinateIndex) {
		displayTree(subordinates[subordinateIndex], depth+1);
	}
}

function makeEmployee(input, position) {
	var employee = { subordinates: [] },
		nameCharacters = [],
		currentCharacter = input.charAt(position);

	while (periodOrColon.test(currentCharacter) == false) {
		nameCharacters.push(currentCharacter);
		++position;
		currentCharacter = input.charAt(position);
	}

	employee.name = nameCharacters.join("");

	if (currentCharacter == '.') {
		employee.finalPosition = position;
		return employee;
	}

	while (true) {
		++position;
		var subordinate = makeEmployee(input, position);

		employee.subordinates.push(subordinate);
		position = subordinate.finalPosition + 1;

		if (input.charAt(position) == '.') {
			employee.finalPosition = position;
			return employee;
		}
	}
}

var lookingFor = {},
	uncomfortableCount = 0;

function seekUncomfortable(employee) {
	var name = employee.name, subordinates = employee.subordinates;
	if (!lookingFor[name]) {
		if (subordinates.length == 0) {
			return;
		}
		lookingFor[name] = 1;
	}

	else {
		uncomfortableCount += lookingFor[name];
		if (subordinates.length == 0) {
			return;
		}
		lookingFor[name] += 1;
	}

	for (var subordinateIndex = 0; subordinateIndex < subordinates.length; ++subordinateIndex) {
		seekUncomfortable(subordinates[subordinateIndex]);
	}
	if (lookingFor[name]) {
		lookingFor[name] -= 1;
	}
}

function main() {
	var input = trim(readline());
	var tree = makeEmployee(input, 0);
	//displayTree(tree, 0);
	seekUncomfortable(tree);
	print(uncomfortableCount);
}

main();


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: b: 2 c: 3, 10 d: 4, 8 e: 6 f: 7 z: 1, 5, 9 Lists of positions of letters a, g, h, ..., y are empty.This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.Find the lexicographically minimal lucky string whose length equals n.

The single line contains a positive integer n (1 ≤ n ≤ 105) — the length of the sought string.

Print on the single line the lexicographically minimal lucky string whose length equals n.

NoteThe lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.

var input = readline().split(' ').map(Number), n = input[0];
var arr = ['a', 'b', 'c', 'd'];
for (var i = 0; i < n; i++) {
    write(arr[i % 4]);
}


This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced.Polycarp likes to play computer role-playing game «Lizards and Basements». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) — they lose b (1 ≤ b < a ≤ 10) health points each.As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball.The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies?Polycarp can throw his fire ball into an archer if the latter is already killed.

The first line of the input contains three integers n, a, b (3 ≤ n ≤ 10; 1 ≤ b < a ≤ 10). The second line contains a sequence of n integers — h1, h2, ..., hn (1 ≤ hi ≤ 15), where hi is the amount of health points the i-th archer has.

In the first line print t — the required minimum amount of fire balls. In the second line print t numbers — indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order.

var input = '';
var inputResolve;
var inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => {
  inputResolve();
});

(async () => {
  await inputPromise;
  var inputs = input.split(/\r?\n/);
  var [n, a, b] = inputs[0].split(' ').map(v => +v);
  var h = inputs[1].split(' ').map(v => +v);
  var c = Array(n).fill(0);
  var d = [...h];
  var kq = 1e5;
  var kc = [];
  var tc = 0;

  function bf(i) {
    if (tc >= kq) return;
    if (i == n - 1) {
      if (d[n - 2] >= 0 || d[n - 1] >= 0) return;
      kq = tc;
      kc = [...c];
      return;
    }
    for (let j = Math.max(0, Math.ceil((d[i - 1] + 1) / b)); j < 1e2; j++) {
      tc += j;
      c[i] = j;
      d[i - 1] -= b * j;
      d[i + 1] -= b * j;
      d[i] -= a * j;
      bf(i + 1);
      tc -= j;
      c[i] = 0;
      d[i - 1] += b * j;
      d[i + 1] += b * j;
      d[i] += a * j;
      if (d[i] - a * j < 0 && i != n - 2) break;
      if (i == n - 2 && d[i] - a * j < 0 && d[i + 1] - b * j < 0) break;
    }
  }

  bf(1);
  console.log(kq);
  console.log(kc.map((v, i) => Array(v).fill(i + 1).join(' ')).join(' ').trim().replace(/\s+/g, ' '))
})();

"use strict";
var input = '';
var inputResolve;
var inputPromise = new Promise(resolve => inputResolve = resolve);
process.stdin.on('data', c => input += c);
process.stdin.on('end', () => {
    inputResolve();
});
(async () => {
    await inputPromise;
    var inputs = input.split(/\r?\n/);
    var [n, a, b] = inputs[0].split(' ').map(v => +v);
    var h = inputs[1].split(' ').map(v => +v);
    var c = Array(n).fill(0);
    var d = [...h];
    var kq = 1e5;
    var kc = [];
    var tc = 0;
    function bf(i) {
        if (tc >= kq)
            return;
        if (i == n - 1) {
            if (d[n - 2] >= 0 || d[n - 1] >= 0)
                return;
            kq = tc;
            kc = [...c];
            return;
        }
        for (let j = Math.max(0, Math.ceil((d[i - 1] + 1) / b)); j < 1e2; j++) {
            tc += j;
            c[i] = j;
            d[i - 1] -= b * j;
            d[i + 1] -= b * j;
            d[i] -= a * j;
            bf(i + 1);
            tc -= j;
            c[i] = 0;
            d[i - 1] += b * j;
            d[i + 1] += b * j;
            d[i] += a * j;
            if (d[i] - a * j < 0 && i != n - 2)
                break;
            if (i == n - 2 && d[i] - a * j < 0 && d[i + 1] - b * j < 0)
                break;
        }
    }
    bf(1);
    console.log(kq);
    console.log(kc.map((v, i) => Array(v).fill(i + 1).join(' ')).join(' ').trim().replace(/\s+/g, ' '));
})();

if (!this.readline) print = console.log, readline = require('./readline');

print(function(n, a, b) {

	var h = readNums();
	var nHits = 0;
	var nBest = -1;
	var hits = new Int32Array(222);
	var best = new Int32Array(222);

	var ans = [];
	solve(1);
	for (var i = 0; i < nBest; i++) {
		ans.push(best[i] + 1);
	}

	return nBest + '\n' + ans.join(' ');

	function hit(k) {
		h[k] -= a;
		h[k - 1] -= b;
		h[k + 1] -= b;
		hits[nHits++] = k;
	}

	function heal(k) {
		h[k] += a;
		h[k - 1] += b;
		h[k + 1] += b;
		nHits--;
	}

	function solve(k) {
		if (k === n - 1) {
			var t = 0;
			while (h[k] >= 0) {
				++t;
				hit(k - 1);
			}
			if (h[k - 1] < 0) {
				if (nBest === -1 || nHits < nBest) {
					nBest = nHits;
					for (var i = 0; i < nHits; i++) {
						best[i] = hits[i];
					}
				}
			}
			while (t--) {
				heal(k - 1);
			}
			return;
		}
		var t = 0;
		while (h[k - 1] >= 0) {
			++t;
			hit(k);
		}

		while (h[k] >= 0) {
			++t;
			solve(k + 1);
			hit(k);
		}
		solve(k + 1);
		while (t--) {
			heal(k);
		}
	}

}.apply(0, readNums()));

function readNums() {
	return readline().split(' ').map(Number);
}

if (!this.readline) print = console.log, readline = require('./readline');

print(function(n, a, b) {

	var h = readNums();
	var ans = [];

	h = h.map(function(v) {
		return v + 1;
	});
	while (true) {
		var i = maxP(n, a, b, h);
		if (i > -1) {
			ans.push(i + 1);
		} else {
			break;
		}
	}

	return ans.length + '\n' + ans.join(' ');

}.apply(0, readNums()));

function maxP(n, a, b, h) {
	var max = -1;
	var maxIndex = 0;
	var f = true;
	for (var i = 0; i < n; i++) {
		if (h[i] > 0) {
			f = false;
			break;
		}
	}
	if (f) {
		return -1;
	}

	for (var i = 1; i < n - 1; i++) {
		var p = 0;
		if (h[i] >= a) {
			p += a;
		} else {
			p += h[i];
		}
		if (h[i - 1] >= b) {
			p += b;
		} else {
			p += h[i - 1];
		}
		if (h[i + 1] >= b) {
			p += b;
		} else {
			p += h[i + 1];
		}
		if (p > max) {
			max = p;
			maxIndex = i;
		}
	}
	if (h[maxIndex] >= a) {
		h[maxIndex] -= a;
	} else {
		h[maxIndex] = 0;
	}
	if (h[maxIndex - 1] >= b) {
		h[maxIndex - 1] -= b;
	} else {
		h[maxIndex - 1] = 0;
	}
	if (h[maxIndex + 1] >= b) {
		h[maxIndex + 1] -= b;
	} else {
		h[maxIndex + 1] = 0;
	}

	return maxIndex;
}

function readNums() {
	return readline().split(' ').map(Number);
}

var s = readline().split(' ');
var n = parseInt(s[0]);
var a = parseInt(s[1]);
var b = parseInt(s[2]);

var h = readline().split(' ').map(function(v){
	return parseInt(v);
});

var ret = [];
for(var i=0; i<n; i++){
	ret.push(0);
}

for(var i=1; i<n-1;i++){
	if( h[i-1]>=0 ){
		var ni = Math.ceil( (h[i-1]+1)/b );
		ret[i] += ni;
		h[i] -= ni*a;
		h[i+1] -= ni*b;
	}
}
var last = n-1;
if(h[last]>=0){
	var ni = Math.ceil( (h[last]+1)/b );
	ret[last-1] += ni;
	h[last-1] -= ni*a;
	h[last] -= ni*b;
}
if(h[last-1]>=0){
	var ni = Math.ceil( (h[last-1]+1)/a );
	ret[last-1] += ni;
	h[last-1] -= ni*a;
	h[last] -= ni*b;
}

s = [];
for(var i = 0; i<n; i++){
	if( ret[i] > 0){
		for(var j=0; j<ret[i]; j++){
			s.push(i+1);
		}
	}
}

print(s.length);
print(s.join(' '));

if (!this.readline) print = console.log, readline = require('./readline');

print(function(n, a, b) {

	var h = readNums();
	var ans = [];

	h = h.map(function(v) {
		return v + 1;
	});
	while (true) {
		var i = maxP(n, a, b, h);
		print(h);
		// print(i)
		if (i > -1) {
			ans.push(i + 1);
		} else {
			break;
		}
	}

	return ans.length + '\n' + ans.join(' ');

}.apply(0, readNums()));

function maxP(n, a, b, h) {
	var max = -1;
	var maxIndex = 0;
	var f = true;
	for (var i = 0; i < n; i++) {
		if (h[i] > 0) {
			f = false;
			break;
		}
	}
	if (f) {
		return -1;
	}

	for (var i = 1; i < n - 1; i++) {
		var p = 0;
		if (h[i] >= a) {
			p += a;
		} else {
			p += h[i];
		}
		// if (i > 0) {
		if (h[i - 1] >= b) {
			p += b;
		} else {
			p += h[i - 1];
		}
		// }
		// if (i < n - 1) {
		if (h[i + 1] >= b) {
			p += b;
		} else {
			p += h[i + 1];
		}
		// }
		if (p > max) {
			max = p;
			maxIndex = i;
		}
	}
	if (h[maxIndex] >= a) {
		h[maxIndex] -= a;
	} else {
		h[maxIndex] = 0;
	}
	// if (maxIndex > 0) {
	if (h[maxIndex - 1] >= b) {
		h[maxIndex - 1] -= b;
	} else {
		h[maxIndex - 1] = 0;
	}
	// }
	// if (maxIndex < n - 1) {
	if (h[maxIndex + 1] >= b) {
		h[maxIndex + 1] -= b;
	} else {
		h[maxIndex + 1] = 0;
	}
	// }

	return maxIndex;
}

function readNums() {
	return readline().split(' ').map(Number);
}

print(function(n, a, b) {
	var h = readline().split(' ').map(Number).map(function(v) {
		return v + 1;
	});

	var ans = [];
	while (true) {
		var max = -1;
		var curr = -1;

		if (h.every(function(v) {
			return v === 0;
		})) break;

		for (var i = 1; i < n - 1; i++) {
			var x = 0;
			x += Math.min(h[i - 1], b);
			x += Math.min(h[i], a);
			x += Math.min(h[i + 1], b);
			if (x > max) {
				max = x;
				curr = i;
			}
		}

		ans.push(curr+1);
		h[curr - 1] = Math.max(0, h[curr - 1] - b);
		h[curr] = Math.max(0, h[curr] - a);
		h[curr + 1] = Math.max(0, h[curr + 1] - b);
	}

	return ans.length + '\n' + ans.join(' ');

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

print(function(n, a, b) {
	var h = readline().split(' ').map(Number).map(function(v) {
		return v + 1;
	});

	var ans = [];
	while (true) {
		var max = -1;
		var curr = -1;

		if (h.every(function(v) {
			return v === 0;
		})) break;

		for (var i = 1; i < n - 1; i++) {
			var x = 0;
			x += Math.min(h[i - 1], b);
			x += Math.min(h[i], a);
			x += Math.min(h[i + 1], b);
			if (x > max) {
				max = x;
				curr = i;
			}
		}

		ans.push(curr);
		h[curr - 1] = Math.max(0, h[curr - 1] - b);
		h[curr] = Math.max(0, h[curr] - a);
		h[curr + 1] = Math.max(0, h[curr + 1] - b);
	}

	return ans.length + '\n' + ans.join(' ');

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


For an array of non-negative integers $$$a$$$ of size $$$n$$$, we construct another array $$$d$$$ as follows: $$$d_1 = a_1$$$, $$$d_i = |a_i - a_{i - 1}|$$$ for $$$2 \le i \le n$$$.Your task is to restore the array $$$a$$$ from a given array $$$d$$$, or to report that there are multiple possible arrays.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the arrays $$$a$$$ and $$$d$$$. The second line contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$0 \le d_i \le 100$$$) — the elements of the array $$$d$$$. It can be shown that there always exists at least one suitable array $$$a$$$ under these constraints.

For each test case, print the elements of the array $$$a$$$, if there is only one possible array $$$a$$$. Otherwise, print $$$-1$$$.

NoteIn the second example, there are two suitable arrays: $$$[2, 8, 5]$$$ and $$$[2, 8, 11]$$$.

// Common Template Starts //
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++];
}
// Common Template Ends //

const getSolution = (n, d) => {
    const a = [];
    a.push(d[0])
    for (let i = 1; i < n; i++) {

        let k = a.length - 1

        let op = ((a[k] - d[i]) < 0) ? (a[k] + d[i]) : (a[k] - d[i])
        a.push(op)

        k = a.length - 1
        if (a[k] - a[k - 1] < d[i]) return -1

    }

    return a.join(' ')
}

// Driver Function Starts //
function main() {

    let testcases = parseInt(readline())
    while (testcases--) {

        let n = parseInt(readline())
        let d = readline().split(' ').map(Number)
        console.log(getSolution(n, d))
    }

}
// Driver Function Ends //

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

const arr = []
readline.on('line', data => {
    arr.push(data.split(' ').map(i => parseInt(i)))
})

readline.on('close', () => {
    main()
} )

function main(){
    let [n] = arr

    let line = 2
    for(let i = 0; i < n; i++){
        let current = arr[line], result = -1
        line += 2

        let newarr = [0]
        for(let i = 0; i < current.length; i++){
            if(current[i] && newarr[newarr.length-1] - current[i] >= 0){
                newarr = -1
                break
            }else{
                newarr.push(current[i] + newarr[newarr.length -1])
            }
        }

        if(newarr === -1){
            console.log(newarr)
        }else {
            let s = ""
            for(let i of newarr.slice(1)) s += i + " "
            console.log(s)
        }

    }
}

'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 main() {
  const mainLength = readline();
  for (let l = 0; l < mainLength; l++) {

    var n = readline();
    var d = readline().split(" ").map(x => parseInt(x));
    var a = [];
    var checked = false;
    var out

    for (let i = 0; i < n; i++) {
      if (i == 0)
        a[i] = (d[i])
      else {
        var i_one = a[i - 1];
        var x = d[i] + a[i - 1];
        // var y = d[i] - a[i - 1];
        var y = Math.abs(d[i] - a[i - 1]);
        var cond1 = (Math.abs(x - i_one))
        var cond2 = (Math.abs(y - i_one))
        if (
          cond1 == cond2
          && (x != y)
        ) {
          // if ((x < 0 && y < 0) && (x != y)) {
          checked = true;
          break;
        } else if (cond1 == d[i]) {
          a[i] = x
        } else {
          a[i] = y
        }
      }
    }
    if (checked)
      out = '-1' + '\n'
    else
      out = a.join(' ') + '\n'
    process.stdout.write(out);
    // console.log(out);

  }

}
// function foo(x) {
//   process.stdout.write("hello: ");   // without auto '\n' (newline)
//   console.log(x);  // with auto '\n' (newline)
// }

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

let currentLine = 0;
let inputString = "";

process.stdin.on("data", (raw_data) => {
  inputString += raw_data;
});

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

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

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

function readArrayInt() {
  return inputString[currentLine++].split(" ").map(Number);
}

function readArray() {
  return inputString[currentLine++].split(" ");
}

function solve() {
  const T = readInt();

  for (let i = 0; i < T; ++i) {
    const n = readInt();
    const drr = readArrayInt();
    const arr = [];

    let check = false;
    for (let i = 0; i < n; i++) {
      const e = drr[i];
      if (i === 0) {
        arr.push(e);
      } else {
        if (arr[arr.length - 1] - e < 0) {
          arr.push(arr[arr.length - 1] + e);
        } else {
          arr.push(arr[arr.length - 1] - e);
        }

        // console.log(arr[arr.length - 1], e, arr[arr.length - 1] - e, "---");
        if (arr[arr.length - 1] - arr[arr.length - 2] < e) {
          console.log(-1);
          check = true;
          break;
        }
      }
    }

    if (!check) {
      let ans = "";
      arr.map((e) => {
        ans += e + " ";
      });
      console.log(ans);
    }
  }
}

function main() {
  solve();
}

'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(),
        d = rns(n);
  let res = [];
  const cache = Array.from({
    length: n
  }, () => new Map());
  const path = [];
  const dfs = (i, p) => {
    if (i === n) {
      res = [...path];
      return 1;
    }
    if (cache[i].has(p)) return cache[i].get(p);
    path.push(p + d[i]);
    let ans = dfs(i + 1, p + d[i]);
    path.pop();
    if (ans > 1) return ans;
    path.push(p + d[i]);
    if (d[i] && p >= d[i]) ans += dfs(i + 1, p - d[i]);
    path.pop();
    cache[i].set(p, ans);
    return ans;
  };
  let cnt = dfs(0, 0);
  if (cnt === 1) return res.join(' ');else return -1;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn();
    return res;
  };
  const re = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rn() - 1;
    return res;
  };
  const rbs = n => {
    let res = new Array(n);
    for (let i = 0; i < n; i++) res[i] = rb();
    return res;
  };
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  const [rn, rb, rns, re, rbs] = convertInput(r);
  try {
    let t = rn();
    let res = new Array(t);
    let limit = 100;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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

// Common Template Starts //
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++];
}
// Common Template Ends //

const getSolution = (n, d) => {
    let a = new Array(n).fill(0)
    a[0] = d[0]
    a[1] = d[0] + d[1]

    let i = 2
    while (i < n) {

        a[i] = d[i] + a[i - 1]
        if( a[i] <= 0 ) a[i - 1] - d[i]

        if (
            (d[i] + a[i - 1]) > 0
            && (a[i - 1] - d[i]) > 0
            && (d[i] + a[i - 1]) != (a[i - 1] - d[i])
        ) return -1

        i++
    }

    return a.join(' ')
}

// Driver Function Starts //
function main() {

    let testcases = parseInt(readline())
    while (testcases--) {

        let n = parseInt(readline())
        let d = readline().split(' ').map(Number)
        console.log(getSolution(n, d))
    }

}
// Driver Function Ends //

// Common Template Starts //
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++];
}
// Common Template Ends //

const getSolution = (n, d) => {
    let a = new Array(n).fill(0)
    a[0] = d[0]
    a[1] = d[0] + d[1]

    let i = 2
    while (i < n) {

        a[i] = d[i] + a[i - 1]
        if( a[i] <= 0 ) a[i - 1] - d[i]

        if ( (d[i] + a[i - 1]) != (a[i - 1] - d[i]) ) return -1

        i++
    }

    return a.join(' ')
}

// Driver Function Starts //
function main() {

    let testcases = parseInt(readline())
    while (testcases--) {

        let n = parseInt(readline())
        let d = readline().split(' ').map(Number)
        console.log(getSolution(n, d))
    }

}
// Driver Function Ends //

// Common Template Starts //
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++];
}
// Common Template Ends //

const getSolution = (n, d) => {
    let a = new Array(n).fill(0)
    a[0] = d[0]
    a[1] = d[0] + d[1]

    let i = 2
    while (i < n) {

        a[i] = d[i] + a[i - 1]
        if( a[i] <= 0 ) a[i - 1] - d[i]

        if (d[i] + a[i - 1] > 0 != a[i - 1] - d[i] ) return -1

        i++
    }

    return a.join(' ')
}

// Driver Function Starts //
function main() {

    let testcases = parseInt(readline())
    while (testcases--) {

        let n = parseInt(readline())
        let d = readline().split(' ').map(Number)
        console.log(getSolution(n, d))
    }

}
// Driver Function Ends //

// Common Template Starts //
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++];
}
// Common Template Ends //

const getSolution = (n, d) => {
    let a = new Array(n).fill(0)
    a[0] = d[0]
    // a[1] = d[0] + d[1]

    let i = 1
    while (i < n) {
        if (d[i] < d[i - 1] && i > 1) return -1
        else a[i] = d[i] + a[i - 1]
        i++
    }

    return a.join(' ')
}

// Driver Function Starts //
function main() {

    let testcases = parseInt(readline())
    while (testcases--) {

        let n = parseInt(readline())
        let d = readline().split(' ').map(Number)
        console.log(getSolution(n, d))
    }

}
// Driver Function Ends //

// Common Template Starts //
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++];
}
// Common Template Ends //

const getSolution = (n, d) => {
    // first array
    let a = new Array(n).fill(0)
    a[0] = d[0]
    a[1] = d[0] + d[1]

    let i = 2
    while (i < n) {
        if (d[i] < d[i - 1]) return -1
        else a[i] = d[i] + a[i - 1]
        i++
    }

    // second array
    // let b = new Array(n).fill(0)
    // b[0] = d[0]
    // b[1] = d[0] + d[1]

    // i = 2
    // while (i < n) {
    //     if(d[i] < d[i - 1]) b[i] = b[i] = Math.abs(d[i] - b[i - 1])
    //     else b[i] = d[i] + b[i - 1]
    //     i++
    // }

    return a.join(' ')
}

// Driver Function Starts //
function main() {

    let testcases = parseInt(readline())
    while (testcases--) {

        let n = parseInt(readline())
        let d = readline().split(' ').map(Number)
        console.log(getSolution(n, d))
    }

}
// Driver Function Ends //

// Common Template Starts //
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++];
}
// Common Template Ends //

const getSolution = (n, d) => {
    // first array
    let a = new Array(n).fill(0)
    a[0] = d[0]
    a[1] = d[0] + d[1]

    let i = 2
    while (i < n) {
        a[i] = d[i] + a[i - 1]
        i++
    }

    // second array
    let b = new Array(n).fill(0)
    b[0] = d[0]
    b[1] = d[0] + d[1]

    i = 2
    while (i < n) {
        if(d[i] < d[i - 1]) b[i] = b[i] = Math.abs(d[i] - b[i - 1])
        else b[i] = d[i] + b[i - 1]
        i++
    }

    return (a.join(' ') === b.join(' ')) ? a.join(' ') : -1
}

// Driver Function Starts //
function main() {

    let testcases = parseInt(readline())
    while (testcases--) {

        let n = parseInt(readline())
        let d = readline().split(' ').map(Number)
        console.log(getSolution(n, d))
    }

}
// Driver Function Ends //

// Common Template Starts //
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++];
}
// Common Template Ends //

const getSolution = (n, d) => {
    // first array
    let a = new Array(n).fill(0)
    a[0] = d[0]
    a[1] = d[0] + d[1]

    let i = 2
    while (i < n) {
        a[i] = d[i] + a[i - 1]
        i++
    }

    // second array
    let b = new Array(n).fill(0)
    b[0] = d[0]
    b[1] = d[0] + d[1]

    i = 2
    while (i < n) {
        if (d[i] >= d[i - 1]) b[i] = d[i] + b[i - 1]
        else b[i] = b[i] = Math.abs(d[i] - b[i - 1])
        i++
    }

    return (a.join(' ') === b.join(' ')) ? a.join(' ') : -1
}

// Driver Function Starts //
function main() {

    let testcases = parseInt(readline())
    while (testcases--) {

        let n = parseInt(readline())
        let d = readline().split(' ').map(Number)
        console.log(getSolution(n, d))
    }

}
// Driver Function Ends //

// Common Template Starts //
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++];
}
// Common Template Ends //

const getSolution = (n, d) => {
    // first array
    let a = new Array(n).fill(0)
    a[0] = d[0]
    a[1] = d[0] + d[1]

    let i = 2
    while (i < n) {
        a[i] = d[i] + a[i - 1]
        i++
    }

    // second array
    let b = new Array(n).fill(0)
    b[0] = d[0]
    b[1] = d[0] + d[1]

    i = 2
    while (i < n) {
        if (d[i] >= d[i - 1]) b[i] = d[i] + b[i - 1]
        else b[i] = b[i] = Math.abs(d[i] - b[i - 1])
        i++
    }

    return (a.join(' ') === b.join(' ')) ? a.join(' ') : '-1'
}

// Driver Function Starts //
function main() {

    let testcases = parseInt(readline())
    while (testcases--) {

        let n = parseInt(readline())
        let d = readline().split(' ').map(Number)
        console.log(getSolution(n, d))
    }

}
// Driver Function Ends //

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

const arr = []
readline.on('line', data => {
    arr.push(data.split(' ').map(i => parseInt(i)))
})

readline.on('close', () => {
    main()
} )

function main(){
    let [n] = arr

    let line = 2
    for(let i = 0; i < n; i++){
        let current = arr[line], result = -1
        line += 2

        let newarr = [0]
        for(let i = 0; i < current.length; i++){
            if(current[i] !== 0 && newarr[newarr.length-1] - current[i] >= 0){
                newarr = -1
                break
            }else{
                newarr.push(current[i] + newarr[newarr.length -1])
            }
        }

        if(newarr === -1){
            console.log(newarr)
        }else {
            let s = ""
            for(let i of newarr) s += i + " "
            console.log(s)
        }

    }
}

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

const arr = []
readline.on('line', data => {
    arr.push(data.split(' ').map(i => parseInt(i)))
})

readline.on('close', () => {
    main()
} )

function main(){
    let [n] = arr

    let line = 2
    for(let i = 0; i < n; i++){
        let current = arr[line], result = -1
        line += 2

        let newarr = [0]
        for(let i = 0; i < current.length; i++){
            if(current[i] !== 0 && newarr[newarr.length-1] - current[i] >= 0){
                newarr = -1
                break
            }else{
                newarr.push(current[i] + newarr[newarr.length -1])
            }
        }
        console.log(
        newarr === -1 ? -1 : newarr.slice(1))

    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

function main() {
  const x = readline();
  for (let i = 0; i < x; i++) {
    var n = readline();
    var drr = readline().split(" ").map(x => parseInt(x));
    var arr = [];
    var checked = false;
    var out

    for (let j = 0; j < n; j++) {

      var a = arr[j - 1] + drr[j];
      var b = arr[j - 1] - drr[j];
      if ((a > 0 && b > 0) && (a != b)) {
        checked = true;
        break;
      }

      if (j == 0)
        arr.push(drr[j])
      else
        arr.push(drr[j] + arr[j - 1])
    }
    if (checked)
      out = '-1' + '\n'
    else
      out = arr.join(' ') + '\n'
    process.stdout.write(out);
    // console.log(out);

  }

}
// function foo(x) {
//   process.stdout.write("hello: ");   // without auto '\n' (newline)
//   console.log(x);  // with auto '\n' (newline)
// }


One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.

The first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city.

Output n + 1 numbers — indexes of cities in one of the two possible routes of the letter.

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 stampNum = parseInt(readline());

	var cities = [];

	var count = { augment: function(key) {
		if (this[key] === undefined) {
			this[key] = 1;
			cities.push(key);
		}
		else {
			this[key] += 1;
		}
	}};

	var link = { augment: function(key, value) {
		if (this[key] === undefined) {
			this[key] = [value];
		}
		else {
			this[key].push(value);
		}
	}};

	for (var i = 0; i < stampNum; ++i) {
		var pair = tokenizeIntegers(readline());
		count.augment(pair[0]);
		count.augment(pair[1]);
		link.augment(pair[0], pair[1]);
		link.augment(pair[1], pair[0]);
	}

	for (var i = 0; i < cities.length; ++i) {
		if (count[cities[i]] == 1) {
			var previous = cities[i];
			var path = [previous];
			var current = link[previous];
			while (true) {
				path.push(current);
				if (count[current] == 1) {
					print(path.join(" "));
					return;
				}
				if (link[current][0] != previous) {
					previous = current;
					current = link[current][0];
				}
				else {
					previous = current;
					current = link[current][1];
				}
			}
		}
	}
}

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 stampNum = parseInt(readline());

	var cities = [];

	var count = { augment: function(key) {
		if (this[key] === undefined) {
			this[key] = 1;
			cities.push(key);
		}
		else {
			this[key] += 1;
		}
	}};

	var link = { augment: function(key, value) {
		if (this[key] === undefined) {
			this[key] = [value];
		}
		else {
			this[key].push(value);
		}
	}};

	for (var i = 0; i < stampNum; ++i) {
		var pair = tokenizeIntegers(readline());
		count.augment(pair[0]);
		count.augment(pair[1]);
		link.augment(pair[0], pair[1]);
		link.augment(pair[1], pair[0]);
	}

	for (var i = 0; i < cities.length; ++i) {
		if (count[cities[i]] == 1) {
			var previous = cities[i];
			var path = [previous];
			var current = link[previous];
			while (true) {
				path.push(current);
				if (count[current] == 1) {
					print(path.join(" "));
					return;
				}
				var neighbors = link[current];
				if (neighbors[0] != previous) {
					previous = current;
					current = neighbors[0];
				}
				else {
					previous = current;
					current = neighbors[1];
				}
			}
		}
	}
}

main();


Vasily the bear has got a sequence of positive integers a1, a2, ..., an. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum. The beauty of the written out numbers b1, b2, ..., bk is such maximum non-negative integer v, that number b1 and b2 and ... and bk is divisible by number 2v without a remainder. If such number v doesn't exist (that is, for any non-negative integer v, number b1 and b2 and ... and bk is divisible by 2v without a remainder), the beauty of the written out numbers equals -1. Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.Here expression x and y means applying the bitwise AND operation to numbers x and y. In programming languages C++ and Java this operation is represented by "&", in Pascal — by "and".

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ a1 < a2 < ... < an ≤ 109).

In the first line print a single integer k (k > 0), showing how many numbers to write out. In the second line print k integers b1, b2, ..., bk — the numbers to write out. You are allowed to print numbers b1, b2, ..., bk in any order, but all of them must be distinct. If there are multiple ways to write out the numbers, choose the one with the maximum number of numbers to write out. If there still are multiple ways, you are allowed to print any of them.

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

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

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

function main() {
	var n = parseInt(readline()),
		numbers = tokenizeIntegers(readline()),
		msb2numbers = new Array(30),
		masks = new Array(30);
	for (var msb = 0; msb < 30; ++msb) {
		masks[msb] = (1 << msb);
		msb2numbers[msb] = [];
	}
	for (var i = 0; i < n; ++i) {
		var number = numbers[i];
		for (var msb = 0; msb < 30; ++msb) {
			if ((number & masks[msb]) !== 0) {
				msb2numbers[msb].push(number);
			}
		}
	}
	for (var msb = 29; msb >= 0; --msb) {
		var multiset = msb2numbers[msb];
		if (multiset.length == 0) {
			continue;
		}
		var sum = multiset[0],
			set = [sum], seen = { sum: true };
		for (var i = 1; i < multiset.length; ++i) {
			var x = multiset[i];
			if (seen[x] === undefined) {
				set.push(x);
				sum &= x;
			}
		}
		if (sum % masks[msb] == 0) {
			print(set.length);
			print(set.join(' '));
			break;
		}
	}
}

main();


Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a1, a2, ..., an, then after we apply the described operation, the sequence transforms into a1, a2, ..., an[, a1, a2, ..., al] (the block in the square brackets must be repeated c times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.

The first line contains integer m (1 ≤ m ≤ 105) — the number of stages to build a sequence.  Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer xi (1 ≤ xi ≤ 105) — the number to add. Type 2 means copying a prefix of length li to the end ci times, in this case the line further contains two integers li, ci (1 ≤ li ≤ 105, 1 ≤ ci ≤ 104), li is the length of the prefix, ci is the number of copyings. It is guaranteed that the length of prefix li is never larger than the current length of the sequence. The next line contains integer n (1 ≤ n ≤ 105) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Print the elements that Sereja is interested in, in the order in which their numbers occur in the input.

var m = parseInt(readline());
var a = [];
var index = 0;
for(var i=0; i<m; i++){
	var l = readline().split(' ').map(function(v){ return +v; });
	var o = {
		type: l[0],
		low: index+1
	}

	if(l[0]===1){
		index++;
		o.v = l[1];
	}else{
		o.rep = l[1];
		o.cont = l[2];
		index += l[1]*l[2];
	}
	a.push(o);
}
var n = +readline();
var l = readline().split(' ').map(function(v){
	return +v;
});

function findFloor(arr, low, high, x){
//print(low, high)
	while(low<high){
		var mid = (low+high)>>1;
		var v = arr[mid].low;
		if(v==x){
			return mid;
		}else if(v>x){
			high = mid;
		}else{
			low = mid;
		}
		if(high-low==1){
			return low
		}
	}
	print(low, high, x)
}

function findV(x){

	var i = findFloor(a, 0, a.length, x);
	while( a[i].type==2 ){
		x = ( x - a[i].low )%a[i].rep + 1;
		i = findFloor(a, 0, i, x);
	}
	return a[i].v;
}

var ret = [];
for(var i=0; i<n; i++){
	ret.push( findV(l[i]) );
}

print( ret.join(' ') );

var m = parseInt(readline());
var arr = [];

for(var i=0; i<m; i++){
	var l = readline().split(' ');
	if(l[0] === '1'){
		arr.push( l[1] );
	}else{
		var c = l[2];
		while(c--){
			for(var j=0, jj=l[1]; j<jj; j++){
				arr.push( arr[j] );
			}
		}
	}
}
var n = +readline();
var l = readline().split(' ');
l.unshift(null);
print(arr.map(function(v){
	return l[v];
}).join(' '));

var m = parseInt(readline());
var arr = [];

for(var i=0; i<m; i++){
	var l = readline().split(' ');
	if(l[0] === '1'){
		arr.push( l[1] );
	}else{
		var c = l[2];
		while(c--){
			for(var j=0, jj=l[1]; j<jj; j++){
				arr.push( arr[j] );
			}
		}
	}
}
var n = +readline();
var l = readline().split(' ');
l.unshift(null);
print(arr.join(' '));