She is skilled in all kinds of magics, and is keen on inventing new one.—Perfect Memento in Strict SensePatchouli is making a magical talisman. She initially has $$$n$$$ magical tokens. Their magical power can be represented with positive integers $$$a_1, a_2, \ldots, a_n$$$. Patchouli may perform the following two operations on the tokens.  Fusion: Patchouli chooses two tokens, removes them, and creates a new token with magical power equal to the sum of the two chosen tokens.  Reduction: Patchouli chooses a token with an even value of magical power $$$x$$$, removes it and creates a new token with magical power equal to $$$\frac{x}{2}$$$. Tokens are more effective when their magical powers are odd values. Please help Patchouli to find the minimum number of operations she needs to make magical powers of all tokens odd values.

Each test contains multiple test cases.  The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The description of the test cases follows. For each test case, the first line contains one integer $$$n$$$ ($$$1 \leq n\leq 2\cdot 10^5$$$) — the initial number of tokens. The second line contains $$$n$$$ intergers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the initial magical power of the $$$n$$$ tokens. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the minimum number of operations Patchouli needs to make all tokens have an odd value of magical power. It can be shown that under such restrictions the required sequence of operations exists.

NoteTest case 1:$$$a$$$ consists solely of odd numbers initially.Test case 2:Choose the tokens with magical power of $$$1$$$ and $$$2$$$ and perform Fusion. Now $$$a=[1,3]$$$, both are odd numbers.Test case 3:Choose the tokens with magical power of $$$2$$$ and $$$8$$$ and perform Fusion. Now $$$a=[4,10]$$$.Choose the token with magical power of $$$10$$$ and perform Reduction. Now $$$a=[4,5]$$$.Choose the tokens with magical power of $$$4$$$ and $$$5$$$ and perform Fusion. Now $$$a=[9]$$$, and $$$9$$$ is an odd number.It can be shown that you can not make all the magical powers odd numbers in less than $$$3$$$ moves, so the answer is $$$3$$$.

let ryan = '';//.map(Numaer).sort(function(a, a){return a - a})
process.stdin.on('data', c => ryan += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = ryan.split(EOL);
   var t = lines[0];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var a = lines[i].split(' ').map(Number);
            var e = 0, min = 2e9;
            for(j = 0; j < n; j++){
                if(a[j] % 2 === 0){
                    e++;
                }
                var m = 0;
                while(a[j] % 2 === 0){
                    m++;
                    a[j] /= 2;
                }
                min = Math.min(min, m);
            }
            console.log(min === 0 ? e : min + e - 1);
        }
    }
});

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

function solve(n, arr) {
    let odd = 0
    let even = 0
    let min = Infinity
    const ks = arr.map(x => {
        let k = 0
        while (!(x & 1)) {
            x /= 2
            k++
        }
        if (k) {
            even++
            if (k < min) min = k
        } else {
            odd++
        }
        return k
    })
    // console.log(even ? min + (even - 1) : 0)
    if (even) {
        if (odd) {
            return even
        } else {
            return min + (even - 1)
        }
    } else {
        return 0
    }
}

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
    var t = lines[0];
    var n = 0;
    for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var a = lines[i].split(' ').map(Number);
            var e = 0, min = 2e9;
            for(j = 0; j < n; j++){
                if(a[j] % 2 === 0){
                    e++;
                }
                var m = 0;
                while(a[j] % 2 === 0){
                    m++;
                    a[j] /= 2;
                }
                min = Math.min(min, m);
            }
            console.log(min === 0 ? e : min + e - 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++];
}

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

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

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

        let odd = arr.filter(x => x % 2 === 1);
        let even = arr.filter(x => x % 2 === 0);

        if (odd.length > 0) {
            output(even.length);
        } else {
            let min = Infinity;
            for (let i = 0; i < even.length; i++) {
                let count = 0;
                while (even[i] % 2 === 0) {
                    even[i] /= 2;
                    count++;
                }
                if (count < min) {
                    min = count;
                }
            }
            output(even.length + min - 1);
        }

    }
}

const readline = require("readline");

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

class Input {
	constructor(line) {
		this.pointer = -1;
		this.content = [line];
	}
	add(line) {
		this.content.push(line);
	}
	get(line) {
		if (!(this.pointer < this.content.length - 1)) {
			return -1
		}
		return this.content[++this.pointer];
	}
}

const intify = (arr) => {
	if (typeof arr == "string") {
		let temp = "";
		for (let i = 0; i < arr.length; i++) {
			if (arr[i] != ' ') {
				temp += arr[i];
			}
		}
		return parseInt(temp)
	} else {
		return arr.map(ele => parseInt(ele))
	}
}

rl.once("line", line => {
	let inp = new Input(line);
	rl.on("line", line => {
		inp.add(line)
	}).on("close", () => {

		let t = intify(inp.get());
		while (t--) {
			let n = intify(inp.get())
			let arr = intify(inp.get().split(' '))
			let evens = 0;
			let odds = 0;
			for (let i = 0; i < arr.length; i++) {
				if (arr[i] % 2 == 1) {
					odds++;
				} else {
					evens++;
				}
			}
			if (odds > 0) {
				console.log(evens);
			} else {
				let minimum = 40;
				for (let i = 0; i < arr.length; i++) {
					let count = 0;
					while (arr[i] > 1 && arr[i] % 2 == 0) {
						arr[i] /= 2;
						count++;
					}
					minimum = Math.min(minimum, count)
				}
				console.log((arr.length - 1) + minimum);
			}
		}

    });
});

function getRes(countOfEven, minTwoDegree, n) {
    if (countOfEven < n) {
        return countOfEven;
    } else {
        return minTwoDegree + countOfEven - 1;
    }
}

function main() {
    let t = +readline();
    while (t > 0) {
        const n = +readline();
        const ticketsData = readline().split(' ');
        let countOfEven = 0;
        let minTwoDegree = null;

        ticketsData.forEach(ticketData => {
            let numTicketData = +ticketData;

            if ((numTicketData & 1) === 0) {
                ++countOfEven;
            }

            let degree = 0;

            while ((numTicketData & 1) === 0) {
                numTicketData >>= 1;
                ++degree;
            }

            if (degree < minTwoDegree || minTwoDegree === null) {
                minTwoDegree = degree;
            }
        });

        console.log(getRes(countOfEven, minTwoDegree, n));

        --t;
    }
}

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

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

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

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

/*---------------------------------------------------*/

function div(val, by){
    return (val - val % by) / by;
}

const getDigits = (x) => {
    let digits = new Array(10).fill(false);
    let len = 0;
    while (x) {
        len++;
        digits[x % 10n] = true;
        x /= 10n;
    }
    return [digits, len];
}

const getLen = (x) => {
    let str = x.toString(10);
    return str.length;
}

const get2 = (x) => {
    let two = 0;
    while (x % 2 === 0) {
        two++;
        x /= 2;
    }
    return two;
}

const calc = (t)=>{
    /* read */
    let n = +readline();
    let a = ra();
    let twos = new Array(n);
    let minTwos = Infinity;
    let maxTwos = -1;
    let even = 0;
    let odd = 0;

    for (let i = 0; i < n; i++) {
        twos[i] = get2(a[i]);
        minTwos = Math.min(minTwos, twos[i]);
        maxTwos = Math.max(maxTwos, twos[i]);
        if (twos[i] > 0) even++;
        else odd++;
    }

    if (maxTwos === 0) return 0;

    if (minTwos === 0) return even;

    return minTwos + n - 1;
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc(t));
        // process.stdout.write(`${calc(t)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

'use strict';

function solve(n, a) {
  let even = 0,
      odd = 0;
  for (let num of a) {
    if (num & 1) {
      odd++;
    } else {
      even++;
    }
  }
  if (odd) return even;
  let min = Infinity;
  for (let num of a) {
    for (let i = 0; i < 31; i++) {
      if (num & 1 << i) {
        min = Math.min(min, i);
        break;
      }
    }
  }
  return min + n - 1;
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res.push(solve(n, a));
    }
    console.log(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', () => {
  inputs = str.split('\n').values();
  main(read);
});

        /////////////////////////// JavaScript Lover /////////////////////////////////////
             ////////////////////      ShixyCat       //////////////////////////////
var t = parseInt(readline())
for(var i=0 ; i<t ; i++){
    var n = parseInt(readline())
    var arr = readline().split(" ").map(function(x) { return parseInt(x); });

    var oddFlag =0;
    for(var j=0 ; j<n; j++) if(arr[j]%2 !=0){
        oddFlag =1;
        break;
    }

    var cnt =0;
    if(oddFlag){
        for(var j=0 ; j<n; j++) if(arr[j]%2 ==0) cnt++;
    }else{
       //var min = ;
       var arrTemp = [];
       for(var j=0 ; j<arr.length;j++)arrTemp[j]=0;

       for(var j = 0 ; j<arr.length ;j++){
          for(var k = 0 ; ;k++){
           if(arr[j] % 2 != 0) break;
           arr[j]  = arr[j] /2;
           arrTemp[j]++;
          }
       }
       //print(arrTemp)
        cnt = Math.min(...arrTemp) + arr.length -1;
    }

    print(cnt);
}

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL); /*your input text, split by lines*/
    var n = lines[0]
    for(j = 1; j <= n; j++){
        k = lines[j].split('').map(Number)
        b = lines[j]

        k[0] -= 1
        if(k[0] === 0 && k.length < 1){
            k.splice(0,1)
        }
        console.log(k.join(''))

    }

});

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

function solve(n, arr) {
    let even = 0
    let min = Infinity
    const ks = arr.map(x => {
        let k = 0
        while (!(x & 1)) {
            x /= 2
            k++
        }
        if (k) {
            even++
            if (k < min) min = k
        }
        return k
    })
    return even ? min + (even - 1) : 0
}

        /////////////////////////// JavaScript Lover /////////////////////////////////////
             ////////////////////      ShixyCat       //////////////////////////////
var t = parseInt(readline())
for(var i=0 ; i<t ; i++){
    var n = parseInt(readline())
    var arr = readline().split(" ").map(function(x) { return parseInt(x); });

    var oddFlag =0;
    for(var j=0 ; j<n; j++) if(arr[j]%2 !=0){
        oddFlag =1;
        break;
    }

    var cnt =0;
    if(oddFlag){
        for(var j=0 ; j<n; j++) if(arr[j]%2 ==0) cnt++;
    }else{
       var min = Math.min(...arr);
       for(var j = 0 ; ;j++){
           if(min%2 != 0) break;
           min = min/2;
           cnt++
       }
        cnt += arr.length-1;
    }

    print(cnt);
}

        /////////////////////////// JavaScript Lover /////////////////////////////////////
             ////////////////////      ShixyCat       //////////////////////////////
var t = parseInt(readline())
for(var i=0 ; i<t ; i++){
    var n = parseInt(readline())
    var arr = readline().split(" ").map(function(x) { return parseInt(x); });

    var oddFlag =0;
    for(var j=0 ; j<n; j++) if(arr[j]%2 !=0){
        oddFlag =1;
        break;
    }

    var cnt =0;
    if(oddFlag){
        for(var j=0 ; j<n; j++) if(arr[j]%2 ==0) cnt++;
    }else{
       var min = Math.min(...arr);
       for(var j = 0 ; j<n;j++){
           if(min%2 != 0) break;
           min = min/2;
           cnt++
       }
        cnt += arr.length-1;
    }

    print(cnt);
}

        /////////////////////////// JavaScript Lover /////////////////////////////////////
             ////////////////////      ShixyCat       //////////////////////////////
var t = parseInt(readline())
for(var i=0 ; i<t ; i++){
    var n = parseInt(readline())
    var arr = readline().split(" ").map(function(x) { return parseInt(x); });

    var oddFlag =0;
    for(var j=0 ; j<n; j++) if(arr[j]%2 !=0){
        oddFlag =1;
        break;
    }

    var cnt =0;
    if(oddFlag){
        for(var j=0 ; j<n; j++) if(arr[j]%2 ==0) cnt++;
    }else{
       var min = Math.min(...arr);
       for(var j = 0 ; j<10;j++){
           if(min%2 != 0) break;
           min = min/2;
           cnt++
       }
        cnt += arr.length-1;
    }

    print(cnt);
}


There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i.Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above.

The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes.

Output n - 1 numbers — new representation of the road map in the same format.

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 reorder(parent, oldRoot, newRoot) {
	var adjacent = new Array(parent.length);
	for (var v = 1; v < parent.length; ++v) {
		adjacent[v] = [];
	}

	for (var v = 1; v < parent.length; ++v) {
		if (parent[v]) {
			adjacent[parent[v]].push(v);
			adjacent[v].push(parent[v]);
		}
	}

	var newParent = new Array(parent.length),
		visited = new Array(parent.length);

	function descend(v) {
		visited[v] = true;
		for (var i = 0; i < adjacent[v].length; ++i) {
			var child = adjacent[v][i];
			if (!visited[child]) {
				newParent[child] = v;
				descend(child);
			}
		}
	}

	// Large problem instances cause the V8 stack to overflow, so we'll have
	// to make our own.
	//descend(newRoot);

	var stack = [newRoot];
	while (stack.length > 0) {
		var v = stack.pop();
		visited[v] = true;
		for (var i = 0; i < adjacent[v].length; ++i) {
			var child = adjacent[v][i];
			if (!visited[child]) {
				newParent[child] = v;
				stack.push(child);
			}
		}
	}

	return newParent;
}

function main() {
	var integers = tokenizeIntegers(readline());
	var n = integers[0], oldRoot = integers[1], newRoot = integers[2];
	var parent = tokenizeIntegers(readline());
	parent.unshift(undefined);
	parent.splice(oldRoot, 0, undefined);

	var newParent = reorder(parent, oldRoot, newRoot);
	newParent.splice(newRoot, 1);
	newParent.shift();
	print(newParent.join(" "));
}

main();


Mark is asked to take a group photo of $$$2n$$$ people. The $$$i$$$-th person has height $$$h_i$$$ units.To do so, he ordered these people into two rows, the front row and the back row, each consisting of $$$n$$$ people. However, to ensure that everyone is seen properly, the $$$j$$$-th person of the back row must be at least $$$x$$$ units taller than the $$$j$$$-th person of the front row for each $$$j$$$ between $$$1$$$ and $$$n$$$, inclusive.Help Mark determine if this is possible.

The first line contains one integer $$$t$$$ ($$$1\leq t\leq 100$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains two positive integers $$$n$$$ and $$$x$$$ ($$$1\leq n\leq 100$$$, $$$1\leq x\leq 10^3$$$) — the number of people in each row and the minimum difference Mark wants. The second line of each test case contains $$$2n$$$ positive integers $$$h_1,h_2,\ldots,h_{2n}$$$ ($$$1\leq h_i\leq 10^3$$$) — the height of each person in units. Note that the sum of $$$n$$$ over all test cases is not bounded.

For each test case, print a single line containing "YES" if Mark could arrange people satisfying his condition and "NO" otherwise. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answers).

NoteIn the first test case, one possible order is to have the third, fifth, and sixth person on the back row and the second, first, and fourth on the front row. The heights of the people will look like this. Back$$$9$$$$$$12$$$$$$16$$$Front$$$3$$$$$$1$$$$$$10$$$ It works because   $$$h_3-h_2 = 9-3 \geq 6$$$,    $$$h_5-h_1 = 12-1\geq 6$$$, and    $$$h_6-h_4 = 16-10\geq 6$$$. In the second test case, it can be shown there is no way to order people in a way that satisfies the condition.In the third test case, the only way to arrange people to satisfy the condition is to have the first person on the back row and the second person on the front row.

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function isPossible(n, x, heights) {
    heights.sort();
    heights.sort(function(a, b) {
        return a - b;
      });
    // console.log(heights)

    let front = []
    let back = []

    for (let i = 0; i < heights.length; i++) {
        if (i < n) {
            front.push(heights[i])
        } else {
            back.push(heights[i])
        }
    }

    // console.log(front)
    // console.log(back)
    for (let j = 0; j < front.length; j++) {
        if (back[j] - front[j] < x) {
            // console.log(back[j] + " " + front[j])
            return "NO";
        }
    }

    return "YES";
}

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

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

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

        if ((n >= 1 && n <= 100) && (x >= 1 && x <= 1000)) {
            const heights = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
            if (heights.length == 2*n) {
                const result = isPossible(n, x, heights);
                console.log(result)
            }
        }
        // ws.write(result + '\n');
    }

    // ws.end();
}

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

});

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

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

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

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

    testLoop: for (let test = 0; test < N; test++) {
        let [n, x] = readline().split(' ').map(Number);
        let arr = readline().split(' ').map(Number);

        // sort array ascending:
        arr.sort((a, b) => a - b);

        let no = false;
        for (let i = 0; i < n; i++) {
            let diff = arr[n + i] - arr[i];
            if (diff < x) {
                no = true;
            }
        }

        output(no ? 'NO' : 'YES');
    }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main(){
    var tests = parseInt(readline());
    for (let t = 0;t < tests; ++t) {
        var nm = readline().split(" ").map(x => parseInt(x));
        let n = nm[0];
        let m = nm[1];
        let res = true;
        var arr = readline().split(" ").map(x=> parseInt(x));
        arr.sort((n1,n2) => {return n1-n2;});
        for (let i = 0;i < n;++i) {
            if (arr[i+n] - arr[i] < m) {
                res = false;
            }
        }
        console.log((res?'YES':'NO'));
    }

}

function photographer() {
  let [n, dx] = r().split` `.map(Number);
  a = r().split` `.map(Number).sort((a, b) => a - b);
  heights = a.slice(0, n).map((d, i) => a[i + n] >= d + dx);
  return heights.every(d => d) ? 'YES' : 'NO';
}

function main() {
  tt = +r();
  for (; tt; tt--) log(photographer());
}

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++];
}

r = readline;
log = console.log;

'use strict';
/*
Mark is asked to take a group photo of 2n people. The i-th person has height hi units.

To do so, he ordered these people into two rows, the front row and the back row, each consisting of n people. However, to ensure that everyone is seen properly, the j-th person of the back row must be at least x units taller than the j-th person of the front row for each j between 1 and n, inclusive.

Help Mark determine if this is possible.
*/
const main = () => {
  const n = parseInt(readline());

  for (let i = 0; i < n; ++i) {
    const [k, minDiff] = readline().split(' ').map(Number);
    const heights = readline().split(' ').map(Number);
    heights.sort((a, b) => a - b);
    let result = true;
    for (let j = 0; j < k; ++j) {
      if (heights[j + k] < heights[j] + minDiff) {
        result = false;
        break;
      }
    }
    console.log(result ? 'YES' : 'NO');
  }
};

const readline = () => {
  return inputString[currentLine++];
};

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

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
const solve = () => {
  let t = parseInt(readline());
  while (t--) {
    let [n, d] = readline()
      .trim(" ")
      .split(" ")
      .map((cur) => parseInt(cur));
    let arr = readline()
      .trim()
      .split(" ")
      .map((cur) => parseInt(cur));
    arr.sort((a, b) => a - b);
    let i = 0,
      ans = true;
    while (i < n) {
      if (arr[i + n] - arr[i] < d) {
        ans = false;
        break;
      }
      i++;
    }
    console.log(`${ans === true ? "YES" : "NO"}`);
  }
};
solve();

T = readline()

while(T--){
  nx = readline().split(' ').map(el => +el)
  n = nx[0]
  x = nx[1]

  h = readline().split(' ').map(el => +el)
  h.sort((next, prev) => next - prev)

  ans = 'YES'
  for(i = 0; i < n; i++){
    for(j = n; j < n*2; j++){

      if(h[j] - h[i] < x){
        ans = 'NO'
        break
      }
      if(ans == 'NO')
        break
      i++
    }
  }

  print(ans)
}

var tests = parseInt(readline());
    for (var t=0; t < tests; t++) {
        var nx = readline().split(' ').map(x=>parseInt(x));
        var n = nx[0];
        var arr = readline().split(' ').map(x=>parseInt(x));
        arr.sort((a,b)=>a-b);
        var ans = 'yes';
        for (var i =0; i < n; i++) {
            if (arr[i+n] - arr[i] < nx[1]) {
                ans = 'no';
                break;
            }
        }
        print(ans);
    }

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function isPossible(n, x, heights) {
    heights.sort();

    let front = []
    let back = []

    for (let i = 0; i < heights.length; i++) {
        if (i < n) {
            front.push(heights[i])
        } else {
            back.push(heights[i])
        }
    }

    if (back[0] - front[0] >= x) {
        return "YES"
    } else {
        return "NO"
    }
}

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

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

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

        if ((n >= 1 && n <= 100) && (x >= 1 && x <= 1000)) {
            const heights = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
            if (heights.length == 2*n) {
                const result = isPossible(n, x, heights);
                console.log(result)
            }
        }
        // ws.write(result + '\n');
    }

    // ws.end();
}

'use strict';

const fs = require('fs');

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function isPossible(n, x, heights) {
    // console.log(n)
    // console.log(x)
    // console.log(heights)

    heights.sort();

    let front = []
    let back = []

    for (let i = 0; i < heights.length; i++) {
        if (i < n) {
            front.push(heights[i])
        } else {
            back.push(heights[i])
        }
    }

    // console.log(front)
    // console.log(back)

    if (back[0] - front[0] >= x) {
        return "YES"
    } else {
        return "NO"
    }
}

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

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

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

        const result = isPossible(n, x, heights);

        console.log(result)
        // ws.write(result + '\n');
    }

    // ws.end();
}


A social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.For each video find the moment it stops being recompressed.

The first line of the input contains integers n and k (1 ≤ n, k ≤ 5·105) — the number of videos and servers, respectively. Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 ≤ si, mi ≤ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.

Print n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.

var pair = readline().split(' '),
    n = +pair[0],
    k = +pair[1],
    servers = {
        'parent': function(i) {
            return Math.floor((i-1)/2);
        },
        'children': function(i) {
            return [2*i + 1, 2*i + 2];
        },
        'index': [],
        'heapify': function() {
            var i = 0,
                index = this.index,
                j,
                k,
                l = index.length,
                temp;
            while ((j = this.children(i))[0] < l
                && (index[i] >= index[j[0]] || index[i] >= index[j[1]])) {
                k = (j[1] >= l || index[j[0]] < index[j[1]]) ? j[0] : j[1];
                temp = index[i];
                index[i] = index[k];
                index[k] = temp;
                i = k;
            }
        }
    },
    s,
    m,
    e = [],
    i = 0;
for (;i<k;i++) {
    servers.index[i] = 0;
}
for (i=0;i<n;i++) {
    pair = readline().split(' ');
    s = +pair[0];
    m = +pair[1];
    e[i] = servers.index[0] = Math.max(servers.index[0], s) + m;
    servers.heapify();
}
print(e.join(' '));

var BinaryHeap = (function() {
    function BinaryHeap(predicate) {
        this.predicate = predicate || function(a, b) { return a > b; };

        this.items = new Float64Array(1 + 1) /* zero index + initial capacity */;
        this.count = 0;
    }

    BinaryHeap.prototype.toArray = function() {
        var array = [];
        for (var i = 1; i <= this.count; i++) {
            array.push(this.items[i]);
        }
        return array;
    };

    BinaryHeap.prototype.insert = function(item) {
        this.items[++this.count] = item;

        /* ensure binary heap invariant */
        var child = this.count;
        var parent = child >> 1;
        while (child > 1 && this.predicate(this.items[child], this.items[parent])) {
            var tmp = this.items[child];
            this.items[child] = this.items[parent];
            this.items[parent] = tmp;

            child = parent;
            parent = child >> 1;
        }

        /* expand array if necessary */
        if (this.count === this.items.length - 1) {
            this.resize(this.count * 2 + 1);
        }
    };

    BinaryHeap.prototype.delete = function() {
        if (this.count === 0) throw "Heap is empty";

        var item = this.items[1];
        this.items[1] = this.items[this.count];
        this.items[this.count--] = null;

        /* ensure binary heap invariant */
        var parent = 1;
        var child = parent << 1;
        while (child <= this.count) {
            if (child < this.count) {
                child = this.predicate(this.items[child], this.items[child + 1]) ? child : child + 1;
            }

            if (this.predicate(this.items[parent], this.items[child])) break;

            var tmp = this.items[parent];
            this.items[parent] = this.items[child];
            this.items[child] = tmp;

            parent = child;
            child = parent << 1;
        }

        /* shrink array if necessary */
        if (this.count === this.items.length / 4) {
            resize(this.count * 2 + 1);
        }

        return item;
    };

    BinaryHeap.prototype.length = function() {
        return this.count;
    };

    BinaryHeap.prototype.resize = function(capacity) {
        var items = new Float64Array(capacity);
        for (var i = 0; i <= this.count; i++) {
            items[i] = this.items[i];
        }
        this.items = items;
    };

    return BinaryHeap;
})();

/*var lines = [];
lines[0] = "6 1";
lines[1] = "1 1000000000";
lines[2] = "2 1000000000";
lines[3] = "3 1000000000";
lines[4] = "4 1000000000";
lines[5] = "5 1000000000";
lines[6] = "6 3";
var line = 0;
function readline() {
	return lines[line++];
}*/

function readn() {
	return +readline();
}
function parsens(s) {
	return 	s.split(" ").map(function(x) { return +x; });
}
function sortNumbers(a,b) {
	return a-b;
}

var numbers = parsens(readline());
var videosCount = numbers[0];
var serversCount = numbers[1];
var videoIn = [];
var videoSize = [];
for (var i = 0; i < videosCount; i++) {
	var numbers = parsens(readline());
	videoIn[i] = numbers[0];
	videoSize[i] = numbers[1];
}

//console.log(videoIn);
//console.log(videoSize);

var videoOut = [];
var heap = new BinaryHeap(function(a,b){return a<b});
for (var i = 0; i < serversCount; i++) {
	heap.insert(0);//enq()
}

//debugger;
for (var videoIndex = 0; videoIndex < videosCount; videoIndex++) {
	var time = videoIn[videoIndex];
	var size = videoSize[videoIndex];
	var nearestFreeServerTime = Math.max(time, heap.delete());//deq()
	var outTime = nearestFreeServerTime + size;
	heap.insert(outTime);//enq()
	videoOut[videoIndex] = outTime;
}

for (var i = 0; i < videosCount; i++) {
	print(videoOut[i]);//
	//console.log(videoOut[i]);
}

var pair = readline().split(' '),
    n = +pair[0],
    k = +pair[1],
    servers = {
        'parent': function(i) {
            return Math.floor((i-1)/2);
        },
        'children': function(i) {
            return [2*1 + 1, 2*i + 2];
        },
        'index': [],
        'heapify': function() {
            var i = 0,
            index = this.index,
            j,
            k,
            l = index.length - 1,
            temp;
            while ((j = this.children(i))[0] < l
                && (index[i] >= index[j[0]] || index[i] >= index[j[1]])) {
                k = (j[1] >= l || index[j[0]] < index[j[1]]) ? j[0] : j[1];
                temp = index[i];
                index[i] = index[k];
                index[k] = temp;
                i = k;
            }
        }
    },
    s,
    m,
    e = [],
    i = 0;
for (;i<k;i++) {
    servers.index[i] = 0;
}
for (i=0;i<n;i++) {
    pair = readline().split(' ');
    s = +pair[0];
    m = +pair[1];
    e[i] = servers.index[0] = Math.max(servers.index[0], s) + m;
    servers.heapify();
}
print(e.join(' '));

var pair = readline().split(' '),
	n = +pair[0],
	k = +pair[1],
	servers = [],
	s,
	m,
	e,
	i = 0;
for (;i<k;i++) {
	servers[i] = 0;
}
for (i=0;i<n;i++) {
	pair = readline().split(' ');
	s = +pair[0];
	m = +pair[1];
	e = Math.max(servers[0], s) + m;
	print(e);
	servers[0] = e;
	servers.sort();
}

var pair = readline().split(' '),
	n = +pair[0],
	k = +pair[1],
	servers = [],
	s,
	m,
	e = [],
	i = 0;
for (;i<k;i++) {
	servers[i] = 0;
}
for (i=0;i<n;i++) {
	pair = readline().split(' ');
	s = +pair[0];
	m = +pair[1];
	e[i] = servers[0] = Math.max(servers[0], s) + m;
	servers.sort(function(a,b){
		return a < b;
	});
}
print(e.join(' '));

var pair = readline().split(' '),
	n = +pair[0],
	k = +pair[1],
	servers = [],
	s,
	m,
	e = [],
	i = 0;
for (;i<k;i++) {
	servers[i] = 0;
}
for (i=0;i<n;i++) {
	pair = readline().split(' ');
	s = +pair[0];
	m = +pair[1];
	e[i] = servers[0] = Math.max(servers[0], s) + m;
	servers.sort();
}
print(e.join(' '));

var BinaryHeap = (function() {
    function BinaryHeap(predicate) {
        this.predicate = predicate || function(a, b) { return a > b; };

        this.items = new Float64Array(1 + 1) /* zero index + initial capacity */;
        this.count = 0;
    }

    BinaryHeap.prototype.toArray = function() {
        var array = [];
        for (var i = 1; i <= this.count; i++) {
            array.push(this.items[i]);
        }
        return array;
    };

    BinaryHeap.prototype.insert = function(item) {
        this.items[++this.count] = item;

        /* ensure binary heap invariant */
        var child = this.count;
        var parent = child >> 1;
        while (child > 1 && this.predicate(this.items[child], this.items[parent])) {
            var tmp = this.items[child];
            this.items[child] = this.items[parent];
            this.items[parent] = tmp;

            child = parent;
            parent = child >> 1;
        }

        /* expand array if necessary */
        if (this.count === this.items.length - 1) {
            this.resize(this.count * 2 + 1);
        }
    };

    BinaryHeap.prototype.delete = function() {
        if (this.count === 0) throw "Heap is empty";

        var item = this.items[1];
        this.items[1] = this.items[this.count];
        this.items[this.count--] = null;

        /* ensure binary heap invariant */
        var parent = 1;
        var child = parent << 1;
        while (child <= this.count) {
            if (child < this.count) {
                child = this.predicate(this.items[child], this.items[child + 1]) ? child : child + 1;
            }

            if (this.predicate(this.items[parent], this.items[child])) break;

            var tmp = this.items[parent];
            this.items[parent] = this.items[child];
            this.items[child] = tmp;

            parent = child;
            child = parent << 1;
        }

        /* shrink array if necessary */
        if (this.count === this.items.length / 4) {
            resize(this.count * 2 + 1);
        }

        return item;
    };

    BinaryHeap.prototype.length = function() {
        return this.count;
    };

    BinaryHeap.prototype.resize = function(capacity) {
        var items = new Float64Array(capacity);
        for (var i = 0; i <= this.count; i++) {
            items[i] = this.items[i];
        }
        this.items = items;
    };

    return BinaryHeap;
})();

var lines = [];
lines[0] = "6 1";
lines[1] = "1 1000000000";
lines[2] = "2 1000000000";
lines[3] = "3 1000000000";
lines[4] = "4 1000000000";
lines[5] = "5 1000000000";
lines[6] = "6 3";
var line = 0;
function readline() {
	return lines[line++];
}

function readn() {
	return +readline();
}
function parsens(s) {
	return 	s.split(" ").map(function(x) { return +x; });
}
function sortNumbers(a,b) {
	return a-b;
}

var numbers = parsens(readline());
var videosCount = numbers[0];
var serversCount = numbers[1];
var videoIn = [];
var videoSize = [];
for (var i = 0; i < videosCount; i++) {
	var numbers = parsens(readline());
	videoIn[i] = numbers[0];
	videoSize[i] = numbers[1];
}

//console.log(videoIn);
//console.log(videoSize);

var videoOut = [];
var heap = new BinaryHeap(function(a,b){return a<b});
for (var i = 0; i < serversCount; i++) {
	heap.insert(0);//enq()
}

//debugger;
for (var videoIndex = 0; videoIndex < videosCount; videoIndex++) {
	var time = videoIn[videoIndex];
	var size = videoSize[videoIndex];
	var nearestFreeServerTime = Math.max(time, heap.delete());//deq()
	var outTime = nearestFreeServerTime + size;
	heap.insert(outTime);//enq()
	videoOut[videoIndex] = outTime;
}

for (var i = 0; i < videosCount; i++) {
	print(videoOut[i]);//
	//console.log(videoOut[i]);
}


Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles.This task is a generalisation of a described example. Imagine that your group of friends has n people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.

The first line contains two integers n and m (1 ≤ n ≤ 100; 0 ≤ m ≤ 104). The next m lines contain the debts. The i-th line contains three integers ai, bi, ci (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ ci ≤ 100), which mean that person ai owes person bi ci rubles. Assume that the people are numbered by integers from 1 to n. It is guaranteed that the same pair of people occurs at most once in the input. The input doesn't simultaneously contain pair of people (x, y) and pair of people (y, x).

Print a single integer — the minimum sum of debts in the optimal rearrangement.

NoteIn the first sample, you can assume that person number 1 owes 8 rubles to person number 2, 1 ruble to person number 3 and 1 ruble to person number 4. He doesn't owe anybody else anything. In the end, the total debt equals 10.In the second sample, there are no debts.In the third sample, you can annul all the debts.

'use strict';

// let inpFileStrArr = `
// 4 3
// 1 2 1
// 2 3 1
// 3 1 1
// `.trim().split('\n'), inpFileCounter = 0;
// function readline() {
//   return inpFileStrArr[inpFileCounter++];
// }
// function print(x) {
//   console.log(x);
// }

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _readline$split$map = readline().split(' ').map(Number);

var _readline$split$map2 = _slicedToArray(_readline$split$map, 2);

var n = _readline$split$map2[0];
var m = _readline$split$map2[1];var arr = [];

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

for (var _i = 0; _i < m; _i++) {
  var _readline$split$map3 = readline().split(' ').map(Number);

  var _readline$split$map4 = _slicedToArray(_readline$split$map3, 3);

  var a = _readline$split$map4[0];
  var b = _readline$split$map4[1];
  var c = _readline$split$map4[2];

  arr[a - 1] -= c;arr[b - 1] += c;
}

print(arr.filter(function (x) {
  return x > 0;
}).reduce(function (a, b) {
  return a + b;
}, 0));

// Generated by CoffeeScript 1.4.0
(function() {
  var a, add, b, c, d, global, i, m, max, min, n, readints, x, _i, _ref, _ref1, _ref2;

  readints = function() {
    var x, _i, _len, _ref, _results;
    _ref = readline().split(' ');
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      x = _ref[_i];
      _results.push(x | 0);
    }
    return _results;
  };

  add = function(a, b) {
    return a + b;
  };

  global = (function() {
    return this;
  })();

  _ref = [Math.max, Math.min], max = _ref[0], min = _ref[1];

  _ref1 = readints(), n = _ref1[0], m = _ref1[1];

  d = (function() {
    var _i, _results;
    _results = [];
    for (_i = 0; 0 <= n ? _i <= n : _i >= n; 0 <= n ? _i++ : _i--) {
      _results.push(0);
    }
    return _results;
  })();

  for (i = _i = 0; 0 <= m ? _i < m : _i > m; i = 0 <= m ? ++_i : --_i) {
    _ref2 = readints(), a = _ref2[0], b = _ref2[1], c = _ref2[2];
    d[a] += c;
    d[b] -= c;
  }

  d = (function() {
    var _j, _len, _results;
    _results = [];
    for (_j = 0, _len = d.length; _j < _len; _j++) {
      x = d[_j];
      _results.push(max(x, 0));
    }
    return _results;
  })();

  print(d.reduce(add));

}).call(this);

var nm = readline().trim().split(' ').map((x)=>parseInt(x));
var n=nm[0],m=nm[1];
var d = {};
var _d={};
var debt= function(a,b,c) {
	this.a=a;
	this.b=b;
	this.c=c;

	if(d[a]==undefined)
		d[a]=0;

	if(_d[b]==undefined)
		_d[b]=0;

	d[a]+=c;
	_d[b]+=c;
}

var debts=[];
var input;
for (var i = 0; i <m; i++) {
	input = readline().trim().split(' ').map((x)=>parseInt(x));
	debts.push(new debt(input[0],input[1],input[2]));
}

var ans=0;
for (var i in d) {
	ans+=Math.max(d[i]-(_d[i]==undefined?0:_d[i]),0);
}

print(ans);

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var n = integers[0], m = integers[1];

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

	for (var i = 0; i < m; i += 1) {
		var integers = tokenizeIntegers(readline());
		var a = integers[0], b = integers[1], debt = integers[2];
		funds[a-1] -= debt;
		funds[b-1] += debt;
	}

	var total = 0;
	for (var i = 0; i < n; i += 1) {
		if (funds[i] > 0) {
			total += funds[i];
		}
	}

	print(total);
}

main();

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var n = integers[0], m = integers[1];

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

	for (var i = 0; i < m; i += 1) {
		var integers = tokenizeIntegers(readline());
		var a = integers[0], b = integers[1], debt = integers[2];
		funds[a-1] -= debt;
		funds[b-1] += debt;
	}

	var total = 0;
	for (var i = 0; i < n; i += 1) {
		total += Math.abs(funds[i]);
	}

	print(total/2);
}

main();

var input = readline();
    input = input.split(' ');
    var people = [];
    var n = input[0],
        m = input[1];
    for(var i=0; i<n; i++) people[i]=0;
    for(var i=0; i<m; i++)
    {
        input = readline();
        input = input.split(' ');
        var a = parseInt(input[0]),
            b = parseInt(input[1]),
            c = parseInt(input[2]);
        people[a-1]-=c;
        people[b-1]+=c;
    }
    var result=0;
    for(var i=0; i<n; i++) result+=Math.abs(people[i]);
    print(result/2);

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

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

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

function main() {
	var integers = tokenizeIntegers(readline());
	var n = integers[0], m = integers[1];

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

	for (var i = 0; i < m; i += 1) {
		var integers = tokenizeIntegers(readline());
		var a = integers[0], b = integers[1], debt = integers[2];
		funds[a] -= debt;
		funds[b] += debt;
	}

	var total = 0;
	for (var i = 0; i < n; i += 1) {
		if (funds[i] > 0) {
			total += funds[i];
		}
	}

	print(total);
}

main();


You're given an array $$$a$$$ of $$$n$$$ integers, such that $$$a_1 + a_2 + \cdots + a_n = 0$$$.In one operation, you can choose two different indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$), decrement $$$a_i$$$ by one and increment $$$a_j$$$ by one. If $$$i < j$$$ this operation is free, otherwise it costs one coin.How many coins do you have to spend in order to make all elements equal to $$$0$$$?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 5000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$)  — the number of elements. The next line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). It is given that $$$\sum_{i=1}^n a_i = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print the minimum number of coins we have to spend in order to make all elements equal to $$$0$$$.

NotePossible strategy for the first test case:   Do $$$(i=2, j=3)$$$ three times (free), $$$a = [-3, 2, 0, 1]$$$.  Do $$$(i=2, j=1)$$$ two times (pay two coins), $$$a = [-1, 0, 0, 1]$$$.  Do $$$(i=4, j=1)$$$ one time (pay one coin), $$$a = [0, 0, 0, 0]$$$.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    for (let i = 0; i < len - 1; i++) {
      if (arr[i] > 0) {
        arr[i + 1] += arr[i];
        arr[i] = 0;
      }
    }

    console.log(arr[len - 1]);
  }
}

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

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i <= b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = a; i >= b; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function Arr(a, b, cb, prev) {
  let p = prev || 0;
  if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb ? (p = cb(a + i, p)) : a + i);
  return Array(a - b + 1).fill(0).map((v, i) => cb ? (p = cb(a - i, p)) : a - i);
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex(v => v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex(v => v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  t = inp[r++];
  while (t--) {
    let n = inp[r++];
    let a = inp.slice(r, r = r + n);
    // console.log(a);
    let i = j = 0;
    while (1) {
      while (i < n && a[i] <= 0) i++;
      while ((j <= i || (j < n && a[j] >= 0))) j++;
      if (j >= n) break;
      let v = Math.min(Math.abs(a[i]), Math.abs(a[j]));
      a[i] -= v
      a[j] += v
    }
    // console.log(a);
    let s = 0n;
    a.filter(v => v > 0).forEach(v => s += BigInt(v));
    console.log(s + '');
  }
})();

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

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i <= b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = a; i >= b; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function Arr(a, b, cb, prev) {
  let p = prev || 0;
  if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb ? (p = cb(a + i, p)) : a + i);
  return Array(a - b + 1).fill(0).map((v, i) => cb ? (p = cb(a - i, p)) : a - i);
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex(v => v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex(v => v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  t = inp[r++];
  while (t--) {
    let n = inp[r++];
    let s = c = 0;
    For(1, n, i => {
      let x = inp[r++];
      c = c + x;
      if (c < 0) { s -= c; c = 0 }
    })
    console.log(s);
  }
})();

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

    B();
});

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

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

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

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

    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        for(let i = 0; i < Math.floor(n/2); i++){
            let temp = a[i];
            a[i] = a[n-i-1];
            a[n-i-1] = temp;
        }

        for(let num of a)
            console.log(num);
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));

        let tot = 0;
        for(let i = 0; i < n; i++){
            if(a[i] > 0)
                tot += a[i];
            else{
                if(a[i] + tot > 0){
                    tot += a[i];
                    a[i] = 0;
                }else{
                    a[i] += tot;
                    tot = 0;
                }
            }
        }

        let res = 0;
        for(let i = 0; i < n; i++)
            if(a[i] < 0)
                res += a[i];

        console.log(res !== 0 ? -1 * res : 0);
    }
}

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

        // let dp = new Array(n);
        // for(let i = 0; i < n; i++){
        //     dp[i] = new Array(k+1);
        //     for(let j = 0; j < k+1; j++){
        //         dp[i][j] = new Array(2);
        //     }
        // }

        // for(let i = 0; i < n; i++){
        //     for(let j = 0; j < k+1; j++){
        //         if(k % 2 !== 0){
        //             dp[i][j][0] = dp[i][j][1] = 0;
        //         }else{

        //         }
        //     }
        // }

        let isKBalanced = (s) => {
            let p1 = 0;
            let p2 = 0;
            let c0 = 0;
            let c1 = 0;
            while(p2-p1 <= k-1){
                if(s.charAt(p2) === '0')
                    c0++;
                else
                    c1++;
                p2++
            }
            if(c0 !== k/2 || c1 !== k/2)
                return false;

            p2--;
            while(p2 < s.length){
                p2++;
                let x = s.charAt(p1);
                p1++;
                if(p2 < s.length)
                    if(s.charAt(p2) !== x)
                        return false;
            }

            return true;
        }

        let map = {};
        let solve = (s, i) => {
            if(i >= s.length)
                return isKBalanced(s);

            if(map[`${s}_${i}`] !== undefined)
                return map[`${s}_${i}`];

            if(s.charAt(i) === '?'){
                let res0 = solve(s.substring(0,i) + '0' + s.substring(i+1, s.length), i+1);
                if(!res0)
                    return map[`${s}_${i}`] = solve(s.substring(0,i) + '1' + s.substring(i+1, s.length), i+1);
                else
                    return map[`${s}_${i}`] = res0;
            }else{
                return map[`${s}_${i}`] = solve(s, i+1);
            }
        }

        console.log(solve(str, 0) ? 'YES' : 'NO');
    }
}

function F(){
    let [n,x] = ti(readline().split(' '));
    let s = readline();
    let t = readline();

    let dp = new Array(n);
    for(let i = 0; i < n; i++){
        dp[i] = new Array(x+1);
        for(let j = 0; j <= x; j++){
            dp[i][j] = new Array(n);
            dp[i][j].fill(0);
        }
    }

    for(let i = 1; i < n; i++){
        for(let j = 0; j <= x; j++){
            for(let k = 0; k <= n; k++){
                dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j][k-1] + (s.charAt(i) === t.charAt(1) ? k-1 : 0));
                if(j !== 0){
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j-1][k-1] + (t.charAt(0) === t.charAt(1) ? k-1 : 0));
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j-1][k-1] + k-1);
                }
            }
        }
    }

    let max = 0;
    for(let i = 0; i < x; i++)
        for(let j = 0; j < n; j++)
            max = Math.max(max, dp[n-1][i][j]);

    console.log(max);
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => BigInt(n));

    let max = Number.MIN_SAFE_INTEGER;
    for (let i = 0; i < len; i++) {
      if (max < arr[i]) max = arr[i];
    }
    let sum = 0n;
    const numIndex = arr.findIndex((num) => num === max);

    for (let i = numIndex; i < len; i++) sum += arr[i];

    console.log(Number(sum));
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => BigInt(n));

    if (len === 1) {
      console.log(Math.abs(Number(arr[0])));
    } else {
      let max = Number.MIN_SAFE_INTEGER;
      for (let i = 0; i < len; i++) {
        if (max < arr[i]) max = arr[i];
      }
      let sum = 0n;
      const numIndex = arr.findIndex((num) => num === max);
      if (numIndex === 0) {
        console.log(0);
      } else {
        for (let i = numIndex; i < len; i++) sum += arr[i];

        console.log(Number(sum));
      }
    }
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    const max = Math.max(...arr);
    let sum = 0;
    const numIndex = arr.findIndex((num) => num === max);

    for (let i = numIndex; i < len; i++) sum += arr[i];

    console.log(sum);
  }
}

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

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i <= b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = a; i >= b; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function Arr(a, b, cb, prev) {
  let p = prev || 0;
  if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb ? (p = cb(a + i, p)) : a + i);
  return Array(a - b + 1).fill(0).map((v, i) => cb ? (p = cb(a - i, p)) : a - i);
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex(v => v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex(v => v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  t = inp[r++];
  while (t--) {
    let n = inp[r++];
    let a = inp.slice(r, r = r + n);
    let i = 0;
    let j = n - 1;
    while (1) {
      while (i < n && a[i] <= 0) i++;
      while (j >= 0 && a[j] >= 0) j--;
      if (i > j) break;
      let v = Math.min(Math.abs(a[i]), Math.abs(a[j]));
      a[i] -= v
      a[j] += v
    }
    // console.log(a);
    console.log(a.filter(v => v > 0).sum());
  }
})();

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

function For(a, b, cb) {
  let res;
  if (a < b) {
    for (let i = a; i <= b; i++) {
      if ((res = cb(i)) !== undefined) return res;
    }
  } else {
    for (let i = a; i >= b; i--) {
      if ((res = cb(i)) !== undefined) return res;
    }
  }
}

function Arr(a, b, cb, prev) {
  let p = prev || 0;
  if (a < b) return Array(b - a + 1).fill(0).map((v, i) => cb ? (p = cb(a + i, p)) : a + i);
  return Array(a - b + 1).fill(0).map((v, i) => cb ? (p = cb(a - i, p)) : a - i);
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn(v)).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = Math.min(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex(v => v == min);
  return [this[i], i, min];
}
Array.prototype.max = function (fn) {
  let max = Math.max(...this.map((v, i) => fn ? fn(v, i) : v));
  let i = this.findIndex(v => v == max);
  return [this[i], i, max];
}

function gcd(a, b) {
  if (!b) return a;
  return gcd(b, a % b);
}
function mod(a, n, m) {
  if (n == 0n) return 1n;
  if (n % 2n == 0n) return mod(a * a % m, n / 2n, m);
  return a * mod(a, n - 1n, m) % m;
}
function extendedEuclid(a, b) {
  if (!b) return [1, 0];
  else {
    let [x, y] = extendedEuclid(b, a % b);
    return [y, x - (a / b | 0) * y];
  }
}

(async () => {
  await inputPromise;
  let inp = input.split(/\s+/).map(v => +v); r = 0;
  t = inp[r++];
  while (t--) {
    let n = inp[r++];
    let a = inp.slice(r, r = r + n);
    // console.log(a);
    let i = 0;
    while (1) {
      while (i < n && a[i] <= 0) i++;
      let j = i + 1;
      while (j < n && a[j] >= 0) j++;
      if (j >= n) break;
      let v = Math.min(Math.abs(a[i]), Math.abs(a[j]));
      a[i] -= v
      a[j] += v
    }
    console.log(a);
    console.log(a.filter(v => v > 0).sum());
  }
})();

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

    B();
});

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

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

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

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

    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        for(let i = 0; i < Math.floor(n/2); i++){
            let temp = a[i];
            a[i] = a[n-i-1];
            a[n-i-1] = temp;
        }

        for(let num of a)
            console.log(num);
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));

        for(let i = 1; i < n; i++){
            if(a[i] > 0 && a[i-1] > 0){
                a[i] += a[i-1];
            }else if(a[i] < 0 && a[i-1] > 0){
                a[i] += a[i-1];
            }
        }

        let res = 0;
        for(let i = 0; i < n; i++)
            if(a[i] < 0)
                res += a[i];

        console.log(res !== 0 ? -1 * res : 0);
    }
}

function F(){
    let [n,x] = ti(readline().split(' '));
    let s = readline();
    let t = readline();

    let dp = new Array(n);
    for(let i = 0; i < n; i++){
        dp[i] = new Array(x+1);
        for(let j = 0; j <= x; j++){
            dp[i][j] = new Array(n);
            dp[i][j].fill(0);
        }
    }

    for(let i = 1; i < n; i++){
        for(let j = 0; j <= x; j++){
            for(let k = 0; k <= n; k++){
                dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j][k-1] + (s.charAt(i) === t.charAt(1) ? k-1 : 0));
                if(j !== 0){
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j-1][k-1] + (t.charAt(0) === t.charAt(1) ? k-1 : 0));
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i-1][j-1][k-1] + k-1);
                }
            }
        }
    }

    let max = 0;
    for(let i = 0; i < x; i++)
        for(let j = 0; j < n; j++)
            max = Math.max(max, dp[n-1][i][j]);

    console.log(max);
}


You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).For example, for string "010210" we can perform the following moves:   "010210" $$$\rightarrow$$$ "100210";  "010210" $$$\rightarrow$$$ "001210";  "010210" $$$\rightarrow$$$ "010120";  "010210" $$$\rightarrow$$$ "010201". Note than you cannot swap "02" $$$\rightarrow$$$ "20" and vice versa. You cannot perform any other operations with the given string excluding described above.You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).String $$$a$$$ is lexicographically less than string $$$b$$$ (if strings $$$a$$$ and $$$b$$$ have the same length) if there exists some position $$$i$$$ ($$$1 \le i \le |a|$$$, where $$$|s|$$$ is the length of the string $$$s$$$) such that for every $$$j < i$$$ holds $$$a_j = b_j$$$, and $$$a_i < b_i$$$.

The first line of the input contains the string $$$s$$$ consisting only of characters '0', '1' and '2', its length is between $$$1$$$ and $$$10^5$$$ (inclusive).

Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).

function main() {
  const is = new Scanner();
  const word = is.nextLine();
  let ones = 0, j = word.length;
  for (let i = 0; i < word.length; i += 1) {
    if (word[i] === '1') {
      ones += 1;
    }
    if (j === word.length && word[i] === '2') {
      j = i;
    }
  }

  for (let i = 0; i < j; i += 1) {
    if (word[i] === '0')
      process.stdout.write('0');
  }
  for (let i = 0; i < ones; i += 1) {
    process.stdout.write('1');
  }

  for (let i = j; i < word.length; i += 1) {
    if (word[i] !== '1') {
      process.stdout.write(String(word[i]));
    }
  }
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const word = is.nextLine();
  let ones = 0, j = word.length;
  for (let i = 0; i < word.length; i += 1) {
    if (word[i] === '1') {
      ones += 1;
    }
    if (j === word.length) {
      if (word[i] === '2') {
        j = i;
      } else {
        if (word[i] === '0') {
          process.stdout.write('0');
        }
      }
    }
  }

  for (let i = 0; i < ones; i += 1) {
    process.stdout.write('1');
  }

  for (let i = j; i < word.length; i += 1) {
    if (word[i] === '0') {
      process.stdout.write('0');
    } else if (word[i] === '2') {
      process.stdout.write('2');
    }
  }
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const word = is.nextLine().split('').map(Number);
  let ones = 0;
  word.forEach((item) => {
    if (item === 1)
      ones += 1;
  });
  let j = word.indexOf(2);
  j = j === -1 ? word.length : j;

  for (let i = 0; i < j; i += 1) {
    if (word[i] === 0)
      process.stdout.write('0');
  }
  for (let i = 0; i < ones; i += 1) {
    process.stdout.write('1');
  }

  for (let i = j; i < word.length; i += 1) {
    if (word[i] !== 1) {
      process.stdout.write(String(word[i]));
    }
  }
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

var str = readline ();
var cnt = 0, i, answer = '';
for ( i = 0; i < str.length; i ++ ) {
    if ( str [ i ] == '1' ) cnt ++;
    else answer += str [ i ];
}
var pos = 0, other = '', actually = '';
while ( cnt -- ) other += '1';
while ( pos < answer.length && answer [ pos ] != '2' ) pos ++;
if ( pos == answer.length ) actually = (answer + other);
else {
    i = 0;
    while ( i < answer.length ) {
        if ( i == pos )
            actually += other;
        actually += answer [ i ];
        i ++;
    }
}
print ( actually );

function main() {
  const is = new Scanner();
  const word = is.nextLine().split('').map(Number);
  let j = 0;
  for (let i = 1; i < word.length; i += 1) {
    if (word[i] === 1 && word[i - 1] === 2) {
      [word[i], word[i - 1]] = [word[i - 1], word[i]];
      [word[i - 1], word[j]] = [word[j], word[i - 1]];
    }
    if (word[j] === 1)
      j += 1;
  }

  const indexLimit = word.indexOf(2);
  const firstWord = word.slice(0, indexLimit);
  const secondWord = word.slice(indexLimit);
  let zeros = 0, ones = 0;
  firstWord.forEach((item) => {
    if (item === 0)
      zeros += 1;
    else
      ones += 1;
  });
  for (let i = 0; i < zeros; i += 1)
    process.stdout.write('0');
  for (let i = 0; i < ones; i += 1)
    process.stdout.write('1');
  console.log(secondWord.join(''));
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const word = is.nextLine();
  let ones = 0, j = word.length;
  for (let i = 0; i < word.length; i += 1) {
    if (word[i] === '1') {
      ones += 1;
    }
    if (j === word.length) {
      if (word[i] === '2') {
        j = i;
      } else {
        process.stdout.write('0');
      }
    }
  }

  for (let i = 0; i < ones; i += 1) {
    process.stdout.write('1');
  }

  for (let i = j; i < word.length; i += 1) {
    if (word[i] === '0') {
      process.stdout.write('0');
    } else if (word[i] === '2') {
      process.stdout.write('2');
    }
  }
}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });

function main() {
  const is = new Scanner();
  const word = is.nextLine().split('').map(Number);
  let ones = 0;
  word.forEach((item) => {
    if (item === 1)
      ones += 1;
  });
  const j = word.indexOf(2);

  for (let i = 0; i < j; i += 1) {
    if (word[i] === 0)
      process.stdout.write('0');
  }
  for (let i = 0; i < ones; i += 1) {
    process.stdout.write('1');
  }

  for (let i = j; i < word.length; i += 1) {
    if (word[i] !== 1) {
      process.stdout.write(String(word[i]));
    }
  }

}

/*
 *  Api Scanner
 */

class Scanner {
  constructor() {
    this.index = 0;
    this.lines = stdinInput.trim().split('\n'); // eslint-disable-line
  }

  nextLine() {
    return this.lines[this.index++]; // eslint-disable-line
  }

  nextInt() {
    return parseInt(this.nextLine(), 10);
  }

  nextDouble() {
    return parseFloat(this.nextLine());
  }

  nextArray() {
    return this.nextLine().split(' ');
  }

  hasNext() {
    return this.index < this.lines.length;
  }
}

let stdinInput = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (input) => { stdinInput += input; });
process.stdin.on('end', () => { main(); });