'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(e)
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(n => {
      stdin.on('data', n => e.push(n)),
        stdin.on('end', function () {
          const t = e.join('').split(os.EOL)
          n(t)
        })
    })
  }
}
async function __main__(e) {
  const n = new InputAndOutput()
  await n.init(), e(n)
}
function solve(e, n) {
  let t = n[0]
  for (let s = 1; s < e; ++s) t &= n[s]
  return t
}
__main__(function (e) {
  const n = Number(e.readLine())
  for (let t = 1; t <= n; ++t) {
    const n = solve(Number(e.readLine()), e.readIntegersOfLine())
    e.print(n + '\n')
  }
})

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 = rn();
		const a = rna();

		let ans = a[0];
		for (const elm of a) ans &= elm;

		console.log(ans);
	}
}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		for(var i = 0; i < N - 1; i++){
			for(var j = i + 1; j < N; j++){
				var L = i;
				var R = j;
				for(var k = L; k <= R; k++){
					var tmp = list[k] & list[R - k];
					list[k] = tmp;
					list[R - k] = tmp;
				}
			}
		}
		for(var i = 0; i < N - 1; i++){
			for(var j = i + 1; j < N; j++){
				var L = i;
				var R = j;
				for(var k = L; k <= R; k++){
					var tmp = list[k] & list[R - k];
					list[k] = tmp;
					list[R - k] = tmp;
				}
			}
		}
		var max = 0;
		for(var i = 0; i < N; i++){
			max = Math.max(max, list[i]);
		}
		myout(max);
	}
}

var t = parseInt(readline())
while(t--){
    var n=parseInt(readline())
    var v=readline().split(' ')
    var res=v[0]
    while(--n)
        res &= v[n]
    print(res)
}

let inputBuffer = ''
process.stdin.on('data', data => {
	inputBuffer += data
})
process.stdin.on('end', _ => {
	inputBuffer = inputBuffer.trim().split('\n')

	main()
})

let currentLine = 0
function readline() {
	return inputBuffer[currentLine++]
}
function readint() {
	return parseInt(readline(), 10)
}
function readints() {
	return readline().split(' ').map(s => parseInt(s, 10))
}
function print(s) {
	process.stdout.write(s + '\n')
}
function write(s) {
	process.stdout.write(s)
}

function range(lowerBound, upperBound = undefined, step = 1) {
	if (upperBound === undefined) {
		upperBound = lowerBound
		lowerBound = 0
	}
	let ret = []
	for (let i = lowerBound; i < upperBound; i += step) ret.push(i)
	return ret
}
function loop(lowerBound, upperBound = undefined, step = 1) {
	return (func) => {
		range(lowerBound, upperBound, step).forEach(i => func(i))
	}
}

function main() {
	let t = readint()
	loop(t)(_ => {
		readint()
		print(readints().reduce((prev, x) => prev & x))
	})
}

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 readLine = () => dataitr.next().value.trim();
function rl () {
	let ans = readLine().split(' ');
	if (!isNaN(Number(ans[0]))) ans = ans.map(x => Number(x));
	return ans.length == 1 ? ans[0] : ans;
}

function main () {
	let t = rl();
	while(t--){
		let n = rl();
		let a = rl();

		let ans = a[0];
		for (let i = 1 ; i < n; i++)
			ans &= a[i];

		console.log(ans);
	}

}

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 readLine = () => dataitr.next().value.trim();
function rl () {
	let ans = readLine().split(' ');
	if (!isNaN(Number(ans[0]))) ans = ans.map(x => Number(x));
	return ans.length == 1 ? ans[0] : ans;
}

function main () {
	let t = rl();
	while(t--) {
		let n = rl();
		let a = rl();
		console.log(a[n - 1]);
	}

}

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

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		for(var i = 0; i < N - 1; i++){
			for(var j = i + 1; j < N; j++){
				var L = i;
				var R = j;
				for(var k = L; k <= R; k++){
					var tmp = list[k] & list[R - k];
					list[k] = tmp;
					list[R - k] = tmp;
				}
			}
		}
		var max = 0;
		for(var i = 0; i < N; i++){
			max = Math.max(max, list[i]);
		}
		myout(max);
	}
}

'use strict'
Object.defineProperty(exports, '__esModule', { value: !0 })
var os = require('os')
const stdin = process.stdin,
  stdout = process.stdout,
  integerRegex = /-?\d+/g,
  decimalRegex = /-?\d+(?:\.\d+)?/g
class InputAndOutput {
  lineIndex = 0
  lines = []
  dried() {
    return this.lineIndex >= this.lines.length
  }
  readLine() {
    const e = this.lines[this.lineIndex]
    return (this.lineIndex += 1), e
  }
  readIntegersOfLine() {
    const e = this.readLine().match(integerRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  readNumsOfLine() {
    const e = this.readLine().match(decimalRegex)
    return null == e ? [] : e.map(e => Number(e))
  }
  print(e) {
    stdout.write(e)
  }
  async init() {
    const e = await this.readLines()
    this.lines = e
  }
  readLines() {
    const e = []
    return new Promise(n => {
      stdin.on('data', n => e.push(n)),
        stdin.on('end', function () {
          const t = e.join('').split(os.EOL)
          n(t)
        })
    })
  }
}
async function __main__(e) {
  const n = new InputAndOutput()
  await n.init(), e(n)
}
function solve() {
  return -1
}
__main__(function (e) {
  const n = Number(e.readLine())
  for (let t = 1; t <= n; ++t) {
    const n = solve()
    e.print(n + '\n')
  }
})


var nk = readline().split(' ').map(Number);
var n = nk[0];
var k = nk[1];
var s = readline().split('');
var count = 0;
for (var i=97; i<=122; i++){
	if (count == k) break;
	for (var j=0; j<s.length; j++){
		if (s[j].charCodeAt(0) == i){
			s[j] = '0';
			count++;
		}
		if (count == k) break;
	}
}
s = s.filter( a => a != '0').join('');
print(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 x = readline();
  const x2 = readline()
    .split(" ")
    .map((x) => +x);

  policeRecruits(x2);
}

function policeRecruits(array) {
  let crimeCount = 0;
  let availableCops = 0;

  for (let i = 0; i < array.length; i++) {
    const element = array[i];
    if (element < 0) {
      if (availableCops > 0) {
        availableCops--;
        crimeCount = Math.max(crimeCount, crimeCount - 1);
      } else {
        crimeCount++;
      }
    } else {
      availableCops += element;
    }
  }
  console.log(crimeCount);
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error("\n");
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function makeClone(obj){return JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw "ArrayIndexOutOfBoundsException ‚There is no more input";}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map(Number);case 6:return i.split("");case 7:return i.split("").map(Number);case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var list = nextIntArray();
  var ok = 0;
  var ng = 0;
  for(var i = 0; i < N; i++){
    if(list[i] > 0){
      ok += list[i];
    }else{
      if(ok > 0){
        ok--;
      }else{
        ng++;
      }
    }
  }
  myout(ng);
}

const readline = require('readline');

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

let counter = 0;

rl.on('line', (input) => {
    if (counter++ === 0) return;
    let line = input.split(' ');
    let inputs = [];
    line.forEach(element => {
        inputs.push(parseInt(element));
    });
    rl.close();
    console.log(solve(inputs));
});

const solve = (inputs) => {
    let currentHired = 0,
        unsolved = 0;
    inputs.forEach(element => {
        if (element === -1 && currentHired === 0) unsolved++;
        else if (element === -1 && currentHired !== 0) currentHired--;
        else currentHired += element;
    });
    return unsolved;
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

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

function main() {
  // input
  const n = readline();
  let l = readline().split(' ').map(x => parseInt(x));
  let result = 0;
  let sum = 0;
  for (let i = 0; i < n; i++) {
    sum += l[i];
    if (sum < 0) {
      result++;
      sum = 0;
    }
  }
  // output
  print(result);
}

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

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

  const arr = d.split(' ').map(Number);
  let ans = 0;
  let cops = 0;

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > 0) {
      cops += arr[i];
    }
    else {
      if (cops === 0) {
        ans++;
      }
      else {
        cops = Math.max(0, --cops);
      }
    }
  }

  console.log(ans);

  c++;
});

const input = [];

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

RL.on('line', (line) => {
    input.push(line);
});

RL.on('close', () => {
  const nums = input[1].split(' ').map(x => parseInt(x));
  let answ = 0; let cops = 0;

  nums.forEach(x => {
    if (x >= 0) cops += x;
    else {
      if (cops + x < 0) answ += 1;
      else cops += x;
    }
  });

  console.log(answ);
});

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

const readLine=()=> inputString[currentLine++];
/* ================================================
           Main Solution Starts Here
===================================================*/

const main=()=>{
	let hired=0
	let untreated=0
	let x=+readLine()
	let order=readLine().split(" ").map(n=>+n)/* +ve int*/
	for(let i=0;i<order.length;i++){
		if(order[i]===-1){
			if(hired){
				hired--
			}else untreated++
		}else hired+=order[i]
	}

	console.log(untreated)
}

// Sample code to perform I/O:

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

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let test = +inputs[0];
    let positive = 0;
    let untreatedCrime = 0;
    let cases = inputs[1].split(' ').map(num => Number(num));

    for (i = 0; i < test; i++) {

        if (cases[i] > 0) {
            positive += cases[i];
        }
        else if (positive > 0) {
            positive--;
        }
        else {
            untreatedCrime++;
        }

    }
    return untreatedCrime.toString();

}

'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.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

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

function main() {
    let n = parseInt(readLine());
    let arr = readLine().split(' ').map(v => parseInt(v));
    let current = 0;
    let ans = 0;
    for (var i = 0; i < n; i++) {
        current += arr[i];
        if (current < 0) {
            ans++;
            current = 0;
        }
    }
    console.log(ans);
}

(function() {
    var n = parseInt(readline());
    var hired = 0, untreated = 0;
    readline().split(' ').forEach(function (v){
        if ( v[0] !== "-" ){
            hired += parseInt(v);
        }else{
            if ( hired > 0 ){
                --hired;
            }else{
                ++untreated;
            }
        }
    });
    print(untreated);
})();

var events = parseInt(readline());

var order = readline().split(" ").map(x => parseInt(x));

var buffer = 0;
var crimes = 0;

for (var i = 0; i < events; i++ ) {
    if (order[i] === -1) {
        if (!buffer) {
            crimes++;
        } else {
            buffer--;
        }
    } else {
        buffer += order[i];
    }
}

print(crimes);

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

function readNums() {
	return readline().split(' ').map(Number);
}
print(function(n) {
	var a = readNums();
	var ans = 0;
	var p = 0;
	for (var i = 0; i < n; i++) {
		if (a[i] === -1) {
			if (p > 0) {
				p--;
			} else {
				ans++;
			}
		} else {
			p += a[i];
		}
	}
	return ans;
}(+readline()));

var n = +readline(), events = readline().split(" "), sum = 0, police = 0;

events.forEach(function(a){
	if(a == "-1" && police == 0){
		sum++;
	}
	else if(a == "-1" && police > 0){
		police--;
	}
	else{
		police += +a;
	}
});

write(sum);

var n = parseInt(readline());
var input = readline().split(' ').map(x=>parseInt(x));

var crime=0;
var officer=0;
var temp;
for(var i=0 ; i<n ;i++){
    if(input[i]>0){
        officer+=input[i];
    }
    else{
       temp = input[i]+ officer;
       if(temp>0){
           officer=temp;
       }
       else{
           crime += temp;
           officer=0;
       }
    }
}

print(Math.abs(crime));

var n = parseInt(readline());
var input = readline().split(' ').map(x=>parseInt(x));

var crime=0;
var officer=0;

for(var i=0 ; i<n ;i++){
    if(input[i]>0){
        officer+=input[i];
    }
    else{
       officer--;
       if(officer<0){
           officer=0;
           crime++;

       }
    }
}

print(crime);

  var numberOfEvents = readline()
  var events = readline().split(' ').map(Number)

  var policeAvailable = 0
  var untreatedEvents = 0

  for (var i = 0; i < numberOfEvents; i++) {
    if (events[i] > 0) {
      policeAvailable += events[i]
    } else if (events[i] < 0 && policeAvailable === 0) {
      untreatedEvents += 1
    } else {
      policeAvailable -= 1
    }
  }

  print(untreatedEvents)

;(function () {

	var n = +readline();
	var s = readline().split(' ').map(Number);
	var x = 0;
	var y = 0;

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

		if (s[i] == -1) {
			if (!x) y++;
			else x--;
		} else x += s[i];

	}

	print(y);

}).call(this);

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

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

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

function main() {
	var n = parseInt(readline());
	var data = tokenizeIntegers(readline());
	var police = 0, crimes = 0;
	for (var i = 0; i < n; ++i) {
		if (data[i] == -1) {
			if (police == 0) {
				++crimes;
			}
			else {
				--police;
			}
		}
		else {
			police += data[i];
		}
	}
	print(crimes);
}

main();

var line = readline();
var n = line.split(' ')[0];
line = readline();
var array=line.split(' ');
var sum =0;
var temp;
var solution = 0;

for(var i = 0 ;  i < array.length;i++){
    temp = parseInt(array[i]);
    if(temp < 0){
        if(sum === 0){
            solution++
        }
        else{
            sum--;
        }
    }
    else{
        sum += temp;
    }
}

print(solution);

'use strict'
String.prototype.getNumArray = function () {
  return String(this).split(' ').map(function (value) {
    return parseInt(value);
  });
}

readline();
let events = readline().getNumArray(),
    crimeCounter = 0,
    availablePolice = 0;

events.map((event) => {
  if (event === -1) {
    if (availablePolice === 0) {
      crimeCounter++;
    } else {
       availablePolice--;
    }
  } else {
     availablePolice += event;
  }
});

write(crimeCounter);

var totalEvents=readline();
var events = readline().split(' ').map(Number);
var availablePolice=0;
var crimes = 0;

for(var i=0;i<totalEvents;i++){
    if(events[i]>0){
        availablePolice += events[i];
    }else if (events[i]<0 && availablePolice ===0){
        crimes +=1;
    }else{
        availablePolice -=1;
    }
}
print(crimes);

var n = readline(),
	num = readline().split(" ").map(function(x) {
        return parseInt(x)
    }),
	p = 0, c = 0;
for (var i = 0; i < n; i++) {
	if (num[i] >= 0) {
		p += num[i];
    } else {
		(p > 0) ? p-- : c++;
    }
}
print(c);

var n =  readline();
var str = readline().split(" ");
var temp = 0;
var res = 0
	for (var i=0; i<+n; i++){
		temp+= Number(str[i]);
		if (temp<0){
			res++;
			temp=0;
			}
	}
print(res);

var n = readline();
var c = readline().split(' ').map(Number);
var person = 0;
var crimes = 0;

for(var i = 0; i < n; i++){
    if(c[i] > 0){
        person += c[i];
    }
    else if(person !== 0){
        person += c[i];
    }
    else {
        crimes ++;
    }
}

print(crimes);

var n = parseInt(readline());
var answ = 0;
var items = readline().split(' ');
var police = 0;
for( var i = 0; i < items.length; ++i) {
  if (items[i] == '-1' && police == 0) {
    answ++;
  } else {
    police += parseInt(items[i]);
  }
}

print(answ);

var hired = 0, arr, events, numOfCrims = 0;

events = readline('Enter Num of Events');
arr = readline().split(' ').map(Number);

for (var i = 0; i < arr.length; i++) {
    if (arr[i] < 0) {
        if (hired === 0)
            numOfCrims++;
        else
            hired--;
    }
    else
        hired = hired +arr[i];

}

print(numOfCrims);

readline();
var a = readline().split(" ").map(function(x) { return parseInt(x); });
var n = 0, police = 0;
for (var i = 0; i < a.length; i++) {
  if (a[i] >= 0) {
    police+= a[i];
  } else {
    if (police > 0) {
      police--;
    } else {
      n++;
    }
  }
}
print(n);

var n=parseInt(readline());
var array=readline().split(' ').map(Number);

un=0
per=0;

for(var i=0;i<array.length;i++){
  if(array[i]==-1){
    if(per>0){
      per=per+array[i]
    }else{
      un=un+1;
    }
  }else{
    per=per+array[i]
  }
}
print(un);

readline();
var recruits = readline().split(' ').map(Number);
var sum=0;
var index=0
for (i = recruits.length-1; i>=0; i--) {
  if (recruits[i]<0)
      sum+=recruits[i];
  else{
    sum=recruits[i]+sum;
    if(sum>=1)
    sum=0;

  }

}
print(Math.abs(sum))

var n = readline();
var p = readline().split(" ");
var stack = [];
var u = 0;
var min = 0;
var push = function(n,stack){
	if(stack.length != 0)
		n+=stack.pop();
	stack.push(n);
	min = (n < min) ? n : min;
}

for (var i = 0; i < p.length; i++)
	push(parseInt(p[i]),stack);
print(min*-1);

n=+readline()
x=0
print(readline().split(' ').map(Number).reduce((s,a)=>s+((x=a>0?Math.max(a,x+a):x-1)<0?1:0),0))

var n = readline();

var line = readline().split(' ');

var police = 0;
var crimes = 0;
var unsolved = 0;

for(i=0;i<n;i++){
    if(parseInt(line[i])>0){
	police+=parseInt(line[i]);
    } else{
	crimes+=1;
	if(crimes>police){
	    unsolved+=1;
	    crimes=0;
	    continue;
	}else{
	    police-=1;
	    crimes-=1;
	}
    }
}

print(unsolved);

"use strict";

var main = function() {
    var n = +rd();
    var A = rdAr();

    wr(A.reduce((a, v) => [Math.max(0, a[0] + v), a[1] + (v === -1 && a[0] <= 0)], [0, 0])[1]);
};

var rd = readline;
var wr = write;
var pr = print;
var rdAr = () => rd().split(' ').map(v => +v);
var cmpLt = (a, b) => a - b;
var cmpGt = (a, b) => b - a;

main();

readline()
T=readline().split(' ').map(Number)
print(T.reduce((a,c) => {
    if (c > 0) {
        a.p += c;
    } else {
        if (a.p) {
            a.p--;
        } else {
            a.a++;
        }
    }
    return a;
}, { a: 0, p: 0 }).a)

// '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() {
  const events_count = parseInt(readline(), 10);
  const events = readline().trim().split(' ').map(string => parseInt(string, 10));
  var crimes_untreated = 0;
  var free_police_forces = 0;

  events.forEach(event => {
    if (event === -1) {
      if (free_police_forces > 0) {
        free_police_forces--;
      } else {
        crimes_untreated++;
      }
    } else {
      free_police_forces += event;
    }
  });

  print(crimes_untreated);
}

main();

(function (){
    var Ret = 0;
    var K = 0;
    var C = readline();
    var Arr = readline().split(" ");
    for (var i in Arr) {
        var N = parseInt(Arr[i]);
        //console.log(i,N);
        if (N > 0) {
            K += N;
        } else {
            if (K > 0) {
                K--;
            } else {
                Ret++;
            }
        }
    }
    print(Ret);
})();

'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() {
    const events =   parseInt(readline());
    const values = readline().split(' ').map(x => parseInt(x));
    let availableOfficer = 0 ;
    let crimes = 0 ;
    for (let i = 0 ; i < events ; i++){
        if (values[i] > 0){
            availableOfficer += values[i];
        }else {
            let crime = Math.abs(values[i]);
           let isCrime = availableOfficer - crime
            availableOfficer = (isCrime < 0 ) ? 0 : isCrime
            if (isCrime < 0) crimes += crime;
        }
    }
    console.log(crimes);
}

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let numOfEvents;
let events;
let crimeCounter = 0;
let recruitersCounter = 0;
rl.on("line", (input) => {
    if (!numOfEvents) {
        numOfEvents = parseInt(input.split(" "))
    } else {
        events = input.split(" ").map(Number)
        events.forEach(element => {
            if (element === -1) {
                if (recruitersCounter > 0) {
                    recruitersCounter = recruitersCounter - 1
                }
                else{
                    crimeCounter++
                }
            } else {
                recruitersCounter += element
            }

        });
        console.log(crimeCounter)
        rl.close()
    }
})

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let numOfEvents;
let events;
let crimeCounter = 0;
let recruitersCounter = 0;
rl.on("line", (input) => {
    if (!numOfEvents) {
        numOfEvents = parseInt(input.split(" "))
    } else {
        events = input.split(" ").map(Number)
        events.forEach(element => {
            if (element === -1) {
                crimeCounter++
            } else {
                recruitersCounter += element
            }
            if (crimeCounter <= recruitersCounter) {
                recruitersCounter = recruitersCounter - crimeCounter
                crimeCounter = 0
            }
        });
        console.log(crimeCounter)
        rl.close()
    }
})

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
let numOfEvents;
let events;
let crimeCounter = 0;
let recruitersCounter = 0;
rl.on("line", (input) => {
    if (!numOfEvents) {
        numOfEvents = parseInt(input.split(" "))
    } else {
        events = input.split(" ").map(Number)
        events.forEach(element => {
            if (crimeCounter <= recruitersCounter) {
                recruitersCounter = recruitersCounter - crimeCounter
                crimeCounter = 0
            }
            if (element === -1) {
                crimeCounter++
            } else {
                recruitersCounter += element
            }

        });
        console.log(crimeCounter)
        rl.close()
    }
})

(function() {
    var n = parseInt(readline());
    var hired = 0, untreated = 0;
    readline().split(' ').forEach(function (v){
        if ( v[0] === "1" ){
            ++hired;
        }else{
            if ( hired > 0 ){
                --hired;
            }else{
                ++untreated;
            }
        }
    });
    print(untreated);
})();

var hired = 0, arr, events, numOfCrims = 0;

events = readline('Enter Num of Events');
arr = readline().split(' ').map(Number);

for (var i = 0; i < arr.length; i++) {
    if (arr[i] < 0) {
        if (hired === 0)
            numOfCrims++;
        else
            hired--;
    }
    else
        hired = arr[i];

}

print(numOfCrims);

readline();
var recruits = readline().split(' ').map(Number);
var sum=0;
var index=0
for (i = recruits.length-1; i>=0; i--) {
  if (recruits[i]<0)
      sum+=recruits[i];
  else{
    sum=recruits[i]+sum;
    if(sum>=1)
    sum=0;

  }
  print(Math.abs(sum))

}
print(Math.abs(sum))

n=+readline()
x=0
print(readline().split(' ').map(Number).reduce((s,a)=>s+((x=a>0?a:x-1)<0?1:0),0))

var n = readline();

var line = readline().split(' ');

var police = 0;
var crimes = 0;
var unsolved = 0;

for(i=0;i<n;i++){
    if(parseInt(line[i])>0){
	police+=1;
    } else{
	crimes+=1;
	if(crimes>police){
	    unsolved+=1;
	    crimes=0;
	    continue;
	}else{
	    police-=1;
	    crimes-=1;
	}
    }
}

print(unsolved);

// '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() {
  const events_count = parseInt(readline(), 10);
  const events = readline().trim().split(' ').map(string => {
    return parseInt(string, 10);
  });
  var crimes_untreated = 0;
  var free_police_forces = 0;

  events.forEach(event => {
    if (event === -1) {
      if (free_police_forces > 0) {
        free_police_forces--;
      } else {
        crimes_untreated++;
      }
    } else {
      free_police_forces += event;
    }
  });

  print(crimes_untreated);
}

(function() {
    var n = parseInt(readline());
    var hired = 0, untreated = 0;
    readline().split(' ').forEach(function (v){
        if ( v[0] == '1' ){
            ++hired;
        }else{
            if ( hired > 0 ){
                --hired;
            }else{
                ++untreated;
            }
        }
    });
    print(untreated);
})();

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

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

  const arr = d.split(' ').map(Number);
  let ans = 0;
  let cops = 0;

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 1) {
      cops++;
    }
    else {
      if (cops === 0) {
        ans++;
      }
      else {
        cops = Math.max(0, --cops);
      }
    }
  }

  console.log(ans);

  c++;
});

// Sample code to perform I/O:

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

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let untreatedCrime = 0;
    let cases = inputs[1].split(' ');
    for (let index = 0; index < cases.length - 1; index++) {
        const element = cases[index];
        if (cases[index] < 0) {
            untreatedCrime++;
            if ((index - 1) >= 0 && cases[index - 1] > 0) {
                untreatedCrime -= 1;
            }

        }

    }
    return untreatedCrime.toString();

}

// Sample code to perform I/O:

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

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
    main(stdin_input);
});

function main(input) {
    let output = nameLookUp(input);
    process.stdout.write(output);       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail

// Write your code here
function nameLookUp(str) {

    let inputs = str.trim().split('\n');
    let positive = 0;
    let untreatedCrime = 0;
    let cases = inputs[1].split(' ');
    for (let index = 0; index < cases.length; index++) {
        const element = cases[index];
        if (cases[index] < 0) {
            untreatedCrime++;
            if (positive > 0) {
                untreatedCrime -= positive;
                positive = 0;
            }
        }
        else {
            positive += +cases[index];
        }

    }
    return untreatedCrime.toString();

}


(function () {
	var n = parseInt(readline());
	var line = readline().split(' ');
	var m = {};
	var prefix = 0;
	var ans = n - 1;
	//print(n);
	for(var idx in line){
		prefix += parseInt(line[idx]);
		//print(prefix);
		if(!m[prefix]) {
			m[prefix] = 1;
		} else {
			++m[prefix];
		}
		ans = n - m[prefix] > ans? ans: n - m[prefix];
	}
	print(ans);
})();

(function () {
	var n = parseInt(readline());
	var line = readline().split(' ');
	var m = {};
	var prefix = 0;
	var ans = n - 1;
	//print(n);
	for(var idx in line){
		prefix += parseInt(line[idx]);
		//print(prefix);
		if(!m[''+prefix]) {
			m[''+prefix] = 1;
		} else {
			++m[''+prefix];
		}
		ans = n - m[''+prefix] > ans? ans: n - m[''+prefix];
	}
	print(ans);
})();


'use strict';

var readline = require('readline');

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

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, a) {
  const res = new Array(11).fill(-1);
  for (let [b, d] of a) {
    res[d] = Math.max(res[d], b);
  }
  let sum = 0;
  for (let i = 1; i < 11; i++) {
    if (res[i] === -1) {
      console.log('MOREPROBLEMS');
      return;
    }
    sum += res[i];
  }
  console.log(sum);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const n = Number(await read());
    const a = [];
    let tmp = n;
    while (tmp--) {
      a.push((await read()).split(' ').map(Number));
    }
    solve(n, a);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

let buf='';

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

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    let cnt=0;
    for(let _=1;_<=t;_++)
    {
        let n=parseInt(line[++cnt]);
        let a=new Array(11);
        for(let i=0;i<=10;i++) a[i]=0;
        for(let i=1;i<=n;i++)
        {
            let [x,y]=line[++cnt].split(' ').map(x=>{return parseInt(x)});
            a[y]=Math.max(a[y],x);
        }
        let ans=0;
        flag=false;
        for(let i=1;i<=10;i++)
        {
            if(!a[i]) flag=true;
            ans+=a[i];
        }
        if(flag) console.log('MOREPROBLEMS');
        else console.log(ans);
    }
})

let buf='';

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

process.stdin.on('end',function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    let cnt=0;
    for(let _=1;_<=t;_++)
    {
        let n=parseInt(line[++cnt]);
        let a=new Array(11);
        for(let i=0;i<=10;i++) a[i]=0;
        for(let i=1;i<=n;i++)
        {
            let [x,y]=line[++cnt].split(' ').map(x=>{return parseInt(x)});
            // console.log('z->',x,y);
            a[y]=Math.max(a[y],x);
        }
        // for(let i=1;i<=n;i++) console.log(a[i]);
        let ans=0;
        flag=false;
        for(let i=1;i<=10;i++)
        {
            if(!a[i]) flag=true;
            ans+=a[i];
        }
        if(flag) console.log('MOREPROBLEMS');
        else console.log(ans);
    }
})


const readline = require('readline')

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

function solve(n, arr) {
    const gs = arr.reduce((o, x) => {
        o[x] = (o[x] || 0) + 1
        return o
    }, {})
    const sorted = Object.keys(gs).map(Number)
        .sort((a, b) => b - a)
// console.log(gs, sorted)
    const all = fac(n)
    if (sorted.length < 2) return all

    const a = sorted[0]
    const b = sorted[1]
    if (gs[a] > 1) return all
    if (a > b + 1) return 0

    let ca = gs[a]
    let cb = gs[b]
    let cc = n - ca - cb

    let invalid = mul(fac(ca), fac(cb))
    for (let i = 1; i <= cc; i++) {
        invalid = mul(invalid, ca + cb + i)
    }
    let ans = add(all, -invalid)
    return add(ans, 998244353)
}

function add(a, b) {
    return (a + b) % 998244353
}
function mul(a, b) {
    const str = b.toString(2)
    let r = 0
    let base = a
    for (let i = str.length - 1; i >= 0; i--) {
        if (str[i] === '1') {
            r = add(r, base)
        }
        base = add(base, base)
    }
    return r
}
function fac(n) {
    let ans = 1
    for (let i = 2; i <= n; i++) {
        ans = mul(ans, i)
    }
    return ans
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const MOD = 998244353;

const B = n => BigInt(n);
const N = n => Number(n);

function fact (n) {
	let res = 1;
	for (let i = 1; i <= n; i++) res = res * i % MOD;
	return res;
}

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		a.sort((x, y) => x - y);

		let ans = 0;
		if (a[n-1] - a[n-2] == 0) {
			ans = fact(n);
		}
		if (a[n-1] - a[n-2] == 1) {
			let cnt = 0;
			for (let i = 0; i < n; i++) cnt += a[i] == a[n-2];
			let ways = 1;
			let juries = n - (cnt + 1);
			let spots = 1 + (cnt + 1);
			while (juries--) {
				ways = ways * spots % MOD, spots++;
			}
			ans = fact(n) - N(B(fact(cnt)) * B(ways) % B(MOD));
			ans = (MOD + ans) % MOD;
		}

		console.log(ans);
	}
}

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

const MOD = 998244353;

const B = n => BigInt(n);
const N = n => Number(n);

function fact (n) {
	let res = 1;
	for (let i = 1; i <= n; i++) res = res * i % MOD;
	return res;
}

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const a = rna();

		a.sort((x, y) => x - y);

		let ans = 0;
		if (a[n-1] - a[n-2] == 0) {
			ans = fact(n);
		}
		if (a[n-1] - a[n-2] == 1) {
			let cnt = 0;
			for (let i = 0; i < n; i++) cnt += a[i] == a[n-2];
			let ways = 1;
			let juries = n - (cnt + 1);
			let spots = 1 + (cnt + 1);
			while (juries--) {
				ways = ways * spots % MOD, spots++;
			}
			ans = fact(n) - N(B(fact(cnt)) * B(ways) % B(MOD));
		}

		console.log(ans);
	}
}

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

const MOD = 998244353;

function fact (n) {
	let ans = 1;
	for (let i = 1; i <= n; i++)
		ans = ans * i % MOD;
	return ans;
}

function main () {
	let T = rn();
	while (T--) {
		let n = rn();
		let a = rna();

		a.sort((x, y) => y - x);

		let ans = 2;
		if (a[0] - a[1] == 0) ans = fact(n);
		if (a[0] - a[1] == 1) {

			let k = 0;
			for (const vl of a) {
				k += vl == a[1];
			}

			for (let x = n - 1; x >= k; x--) {
				let prd = 1;
				for (let i = 0; i < k; i++) {
					prd = prd * (x - i) % MOD;
				}
				ans += prd * fact(n-k-1);
				ans %= MOD;
			}
			ans = (fact(n) - ans + MOD) % MOD;
		}

		console.log(ans);
	}
}

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

const MOD = 998244353;

function fact (n) {
	let ans = 1;
	while (n) ans = (ans * n--) % MOD;
	return ans;
}

function main () {
	let T = rn();
	while (T--) {
		let n = rn();
		let a = rna();

		a.sort((x, y) => x - y);

		let k = 0;
		for (const x of a) k += x == a[n-2];

		let ans = 0;
		if (a[n-1] == a[n-2]) ans = fact(n);
		if (a[n-1] == a[n-2] + 1) {
			let x = n - 1;
			while (x >= k) {
				let prd = 1;
				for (let j = 0; j < k; j++) {
					prd = prd * (x - j) % MOD;
				}

				ans = (ans + prd * fact(n-k-1)) % MOD;
				x--;
			}
			ans = (fact(n) - ans) % MOD;
		}

		console.log(ans);
	}
}

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

const MOD = 998244353;

function fact (n) {
	let ans = 1;
	while (n) ans = (ans * n--) % MOD;
	return ans;
}

function main () {
	let T = rn();
	while (T--) {
		let n = rn();
		let a = rna();

		a.sort((x, y) => x - y);

		let k = 0;
		for (const x of a) k += x == a[n-2];

		let ans = 0;
		if (a[n-1] == a[n-2]) ans = fact(n);
		if (a[n-1] == a[n-2] + 1) {
			let x = n - 1;
			while (x >= k) {
				ans = (ans + fact(x)/fact(x-k) * fact(n-k-1)) % MOD;
				x--;
			}
			ans = (fact(n) - ans) % MOD;
		}

		console.log(ans);
	}
}

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

const MOD = 998244353;

function fact (n) {
	let ans = 1;
	while (n) ans = (ans * n--) % MOD;
	return ans;
}

function main () {
	let T = rn();
	while (T--) {
		let n = rn();
		let a = rna();

		a.sort((x, y) => x - y);

		let cnt = 0;
		for (const x of a) cnt += x == a[n-2];

		let ans = 0;
		if (a[n-1] == a[n-2]) ans = fact(n);
		if (a[n-1] == a[n-2] + 1) ans = fact(n) * cnt / (cnt + 1) % MOD;

		console.log(ans);
	}
}

const readline = require('readline')

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

function solve(n, arr) {
    const gs = arr.reduce((o, x) => {
        o[x] = (o[x] || 0) + 1
        return o
    }, {})
    const sorted = Object.keys(gs).map(Number)
        .sort((a, b) => b - a)

    const all = fac(n)
    if (sorted.length < 2) return all

    const a = sorted[0]
    const b = sorted[1]
    if (a > b + 1) return 0

    let ca = gs[a]
    let cb = gs[b]
    let cc = n - ca - cb

    let invalid = mul(fac(ca), fac(cb))
    for (let i = 1; i <= cc; i++) {
        invalid = mul(invalid, ca + cb + i)
    }
    let ans = add(all, -invalid)
    return add(ans, 998244353)
}

function add(a, b) {
    return (a + b) % 998244353
}
function mul(a, b) {
    const str = b.toString(2)
    let r = 0
    let base = a
    for (let i = str.length - 1; i >= 0; i--) {
        if (str[i] === '1') {
            r = add(r, base)
        }
        base = add(base, base)
    }
    return r
}
function fac(n) {
    let ans = 1
    for (let i = 2; i <= n; i++) {
        ans = mul(ans, i)
    }
    return ans
}


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 => string.trim());

    main();
});

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

const s2i = s => parseInt(s, 10);

function main() {
  const T = s2i(readLine());
  for(let i = 0; i < T; i++) {
    let [a, b, n] = readLine().split(' ').map(s2i);

    if (a > b) [a, b] = [b, a];

    let ops = 0;

    while (b <= n) {
      [a, b] = [b, a + b];
      ops++;
    }

    console.log(ops);
  }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (inputStd) => {
  inputString += inputStd;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  while (t--) {
    let [a, b, target] = readLine()
      .split(" ")
      .map((n) => parseInt(n));
    let count = 0;
    let i = 0;
    while (a <= target || b <= target) {
      if (a > b) {
        b += a;
      } else {
        a += b;
      }
      count++;
      i++;
    }
    console.log(count - 1);
  }
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
  	var input = nextIntArray();
  	var N = input[2];
  	var min = Math.min(input[0], input[1]);
  	var max = Math.max(input[0], input[1]);
  	var count = 0;
  	while(N >= max){
  		min += max;
  		var tmp = max;
  		max = min;
  		min = tmp;
  		count++;
  	}
  	output[i] = count;
  }
  myout(myconv(output, 9));
}

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

let stdinInput = '';

process.stdin.on('data', input => {
  stdinInput += input;
})

process.stdin.on('end', () => {
  main(stdinInput);
})

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 1;
    let i = 1;
    while (i <= testCases) {
        const int = data[i].split(' ');
        let a = int[0] * 1;
        let b = int[1] * 1;
        const n = int[2] * 1;
        let count = 0;
        while (true) {
            if (a > n || b > n) {
                console.log(count);
                break;
            }
            a > b ? b += a : a += b;
            count += 1;
        }
        i += 1;
    }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
var input = '';
process.stdin.on('data', function (line) {
    input += line;
});
process.stdin.on('end', function () {
    var _a, _b;
    var lines = input.split('\n');
    var tests = parseInt(lines.shift(), 10);
    while (tests--) {
        var a = void 0, b = void 0, n = void 0;
        _a = lineToNumArray(lines.shift()), a = _a[0], b = _a[1], n = _a[2];
        var steps = 0;
        while (Math.max(a, b) <= n) {
            _b = [a + b, Math.max(a, b)], a = _b[0], b = _b[1];
            steps++;
        }
        console.log(steps);
    }
});
// input helper
function lineToNumArray(line) {
    return line.split(' ').map(function (element) { return parseInt(element, 10); });
}

const process = require('process')
let input = ''
process.stdin.on('data', data => input += data)
process.stdin.on('end', () => main(input))

function main(input) {
    let lines = input.trim().split('\n')
    let n = +lines[0]
    for(let i = 0; i < n; i++) {
        let [a, b, n] = lines[1 + i].split(' ')
        console.log(solution(+a, +b, +n))
    }
}

function solution(a, b, n) {
    if (a < b) return solution(b, a, n)
    // a >= b
    let i = 0
    for (; a <= n; i++) {
        let c = a + b
        b = a
        a = c
    }
    return i
}

var t = parseInt(readline());
for (var tc = 0; tc < t; tc++) {
  var inp = readline()
    .split(" ")
    .map((val) => parseInt(val));
  var a = inp[0],
    b = inp[1],
    n = inp[2];
  var count = 0;
  while (Math.max(a, b) <= n) {
    if (a < b) {
      var temp = a;
      a = b;
      b = temp;
    }
    b += a;
    count++;
  }
  print(count);
}

"use strict";

//readline().split(' ').map(Number);

function sec(){
    var arr = readline().split(' ').map(Number);
    var a = Math.min(arr[0],arr[1]);
    var b = Math.max(arr[0],arr[1]);
    var aa = 1, bb = 1;
    var c = 1;
    while(aa * a + bb * b <= arr[2]){
        c++;
        bb = aa+bb;
        aa = bb-aa;
    }
    print(c);
}

function main(){
    var t = readline();
    while(t--){
        sec();
    }
}

main();

function solve() {
   var T = Number(read());
   for (var t = 0; t < T; ++t) {
      var abn = read().split(' ').map(Number);
      var a = abn[0], b = abn[1], n = abn[2];
      var count = 0;
      while (a <= n && b <= n) {
         if (a < b) {
            a += b;
         } else {
            b += a;
         }
         count++;
      }
      write(count);
   }
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         solve();
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

      RL.on('line', (line) => {
         MEMORY.push(line);
      });

      RL.on('close', solve);
   }
} else {
   solve();
}

function write(value) {
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

var count = +readline();

for(var index = 0; index < count; ++index) {
    var content = readline()
    var content = content.split(' ');
    var a = +content[0];
    var b = +content[1];
    var n = +content[2];

    var rounds = 0;

    if(a > n || b > n) {
        print("0");
    } else {
        while(a <= n && b <= n) {
            ++rounds;

            if(a + b > n) {
                a += b;
            } else {
                if(a < b) {
                    a += b;
                } else {
                    b += a;
                }
            }
        }
    }

    print('' + rounds + '\n');
}

'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++];
}
/**
3 4
##..
##..
...#

**/

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

function main() {
    // let n = Number(readline());

    // let string = 'codeforces';

    // let s = 's'.repeat(BigInt.asIntN(n-1));

    // console.log(string + s);

    let n = parseInt(readline());

    for(let i=0;i<n;i++) {
        solve();
    }

}

function solve() {
    let [a, b, n] = readline().split(" ").map(Number);

    let x = Math.min(a, b);
    let y = Math.max(a, b);

    let count = 0;
    let sum = 0;

    while( sum <= n) {
        sum = x + y;

        if(count % 2 === 0) {
            x = sum;
        } else {
            y = sum;
        }

        count++;
    }

    console.log(count);
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

const s2i = s => parseInt(s, 10);

function main() {
  const T = s2i(readLine());
  for(let i = 0; i < T; i++) {
    let [a, b, n] = readLine().split(' ').map(s2i);

    if (a < b) {
      const temp = a;
      a = b;
      b = temp;
    }

    let ops = 0;

    while (b <= n) {
      ops++;
      const sum = a + b;
      a = b;
      b = sum;
    }

    console.log(ops);
  }
}

'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++];
}
/**
3 4
##..
##..
...#

**/

function gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

function main() {
    // let n = Number(readline());

    // let string = 'codeforces';

    // let s = 's'.repeat(BigInt.asIntN(n-1));

    // console.log(string + s);

    let n = parseInt(readline());

    for(let i=0;i<n;i++) {
        solve();
    }

}

function solve() {
    let [a, b, n] = readline().split(" ").map(Number);

    a = Math.min(a, b);
    b = Math.max(a, b);

    let count = 0;
    let sum = 0;

    while( sum <= n) {
        sum = a + b;

        if(count % 2 === 0) {
            a = sum;
        } else {
            b = sum;
        }

        count++;
    }

    console.log(count);
}

'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 gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

function main() {
    // let n = Number(readline());

    // let string = 'codeforces';

    // let s = 's'.repeat(BigInt.asIntN(n-1));

    // console.log(string + s);

    let n = parseInt(readline());

    for(let i=0;i<n;i++) {
        solve();
    }

}

function solve() {
    let [a, b, n] = readline().split(" ").map(Number);

    a = Math.min(a, b);
    b = Math.max(a, b);

    let count = 0;
    let sum = 0;

    while( b <= n || a <= n) {
        sum = a + b;

        if(a > b) {
            b = sum;
        } else {
            a = sum;
        }

        count++;
    }

    console.log(count - 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 gcd(a, b) {
    if (!b) {
        return a;
    }

    return gcd(b, a % b);
};

function main() {
    // let n = Number(readline());

    // let string = 'codeforces';

    // let s = 's'.repeat(BigInt.asIntN(n-1));

    // console.log(string + s);

    let n = parseInt(readline());

    for(let i=0;i<n;i++) {
        solve();
    }

}

function solve() {
    let [a, b, n] = readline().split(" ").map(Number);

    a = Math.min(a, b);
    b = Math.max(a, b);

    let count = 0;
    let sum = 0;

    while( sum <= n) {
        sum = a + b;

        if(a > b) {
            b = sum;
        } else {
            a = sum;
        }

        count++;
    }

    console.log(count);
}

var count = +readline();

for(var index = 0; index < count; ++index) {
var content = readline()
var content = content.split(' ');
var a = +content[0];
var b = +content[1];
var n = +content[2];

var rounds = 0;

if(a > n || b > n) {
    print("0");
} else {
    while(a < n && b < n) {
        ++rounds;

        if(a + b > n) {
            a += b;
        } else {
            if(a < b) {
                a += b;
            } else {
                b += a;
            }
        }
    }
}

print('' + rounds + '\n');
}

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

var rounds = 0;

if(a > n || b > n) {
    print("0");
} else {
    while(a < n && b < n) {
        ++round;

        if(a + b > n) {
            a += b;
        } else {
            if(a < b) {
                a += b;
            } else {
                b += a;
            }
        }
    }
}

print('' + rounds);


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

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

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

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

var n = parseInt(readline());

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

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

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

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

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

let inputString = "";
let currentLine = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

let buf='';

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

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

'use strict';

var fs = require('fs');

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

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

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

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

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

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

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

var n = parseInt(readline());

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

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

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

var n = parseInt(readline());

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

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

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

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

let inputString = "";
let currentLine = 0;

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

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

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

let inputString = "";
let currentLine = 0;

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

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

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

let inputString = "";
let currentLine = 0;

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

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

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

let inputString = "";
let currentLine = 0;

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

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

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

let inputString = "";
let currentLine = 0;

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

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

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

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

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

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

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

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

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

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

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

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


const readline = require('readline')

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

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

var t = readline();

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

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

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

    ans = Math.max(ans, good30);

    print(ans);
}

var t = parseInt(readline());

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

    var ans = 0;

    var rest = 0;
    var div = 0;

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

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

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

    print(ans);
}

const readline = require('readline')

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

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