The little girl loves the problems on array queries very much.One day she came across a rather well-known problem: you've got an array of $$$n$$$ elements (the elements of the array are indexed starting from 1); also, there are $$$q$$$ queries, each one is defined by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \le l_i \le r_i \le n)$$$. You need to find for each query the sum of elements of the array with indexes from $$$l_i$$$ to $$$r_i$$$, inclusive.The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.

The first line contains two space-separated integers $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) and $$$q$$$ ($$$1 \le q \le 2\cdot10^5$$$) — the number of elements in the array and the number of queries, correspondingly. The next line contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$1 \le a_i \le 2\cdot10^5$$$) — the array elements. Each of the following $$$q$$$ lines contains two space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the $$$i$$$-th query.

In a single line print, a single integer — the maximum sum of query replies after the array elements are reordered. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

print(function(n, q) {
	var a = ('0 ' + readline()).split(' ').map(Number).sort(function(a, b) {
		return a - b;
	});
	var b = new Int32Array(n + 1);

	for (var i = 0; i < q; i++) {
		var l = readline().split(' ');
		b[l[0]]++;
		b[+l[1] + 1]--;
	}

	var x = 0;
	for (var i = 1; i <= n; i++) {
		b[i] = (x += b[i]);
	}

	Array.prototype.sort.call(b, function(a, b) {
		return a - b;
	});

	var ans = 0;
	for (var i = 1; i <= n; i++) {
		ans += a[i] * b[i];
	}
	return ans;
}.apply(0, readline().split(' ').map(Number)));

var tree = new Uint32Array(2e5 + 1);

function update(i, v, n) {
	while (i <= n) {
		tree[i] += v;
		i += (i & -i);
	}
}

function read(i) {
	var sum = 0;
	while (i > 0) {
		sum += tree[i];
		i -= (i & -i);
	}
	return sum;
}

print(function(n, q) {
	var a = readline().split(' ').map(Number).sort(function(a, b) {
		return a - b;
	});

	while (q--) {
		readline().split(' ').map(Number).reduce(function(x, y) {
			update(x, 1, n);
			update(y + 1, -1, n);
		});
	}
	var c = new Uint32Array(n);
	for (var i = 1; i <= n; i++) {
		c[i-1] = read(i);
	}
	Array.prototype.sort.call(c, function(a, b) {
		return a - b;
	});

	var ans = 0;
	for (var i = 0; i < n; i++) {
		ans += a[i] * c[i];
	}
	return ans;
}.apply(0, readline().split(' ').map(Number)));

print(function(n, q) {
	var a = new Int32Array(n + 1);
	var b = new Int32Array(n + 1);

	var i = 1;
	readline().replace(/\d+/g, function(x) {
		a[i++] = +x;
	});

	for (var i = 0; i < q; i++) {
		var l = readline().split(' ');
		b[l[0]]++;
		b[+l[1] + 1]--;
	}

	var x = 0;
	for (var i = 1; i <= n; i++) {
		b[i] = (x += b[i]);
	}

	Array.prototype.sort.call(b, function(a, b) {
		return a - b;
	});
	Array.prototype.sort.call(a, function(a, b) {
		return a - b;
	});

	var ans = 0;
	for (var i = 1; i <= n; i++) {
		ans += a[i] * b[i];
	}
	return ans;
}.apply(0, readline().split(' ').map(Number)));

print(function(n, q) {
	var a = readline().split(' ').map(Number);
	var b = [];
	for (var i = 0; i <= n; i++) {
		b[i] = 0;
	}

	var c=[]
	for (var i = 0; i < q; i++) {
		c.push(readline());
	}
	c.forEach(function(v){
		v.split(' ').reduce(function(l, r) {
			b[l - 1]++;
			b[r]--;
		});
	});

	var x = 0;
	for (var i = 0; i < n; i++) {
		b[i] = (x += b[i]);
	}
	b.pop();
	b.sort(function(a, b) {
		return a - b;
	});
	a.sort(function(a, b) {
		return a - b;
	});

	var ans = 0;
	for (var i = 0; i < n; i++) {
		ans += a[i] * b[i];
	}
	return ans;
}.apply(0, readline().split(' ').map(Number)));

print(function(n, q) {
	var a= readline().split(' ').map(Number);
	var b = new Int32Array(n);

	for (var i = 0; i < q; i++) {
		readline().split(' ').reduce(function(l, r){
			b[l-1]++;
			if( r<n )
				b[r]--;
		});
	}

	var x = 0;
	for (var i = 0; i < n; i++) {
		b[i] = (x += b[i]);
	}

	Array.prototype.sort.call(b, function(a, b) {
		return a - b;
	});
	Array.prototype.sort.call(a, function(a, b) {
		return a - b;
	});

	var ans = 0;
	for (var i = 0; i < n; i++) {
		ans += a[i] * b[i];
	}
	return ans;
}.apply(0, readline().split(' ').map(Number)));

print(function(n, q) {
	var a = new Int32Array(n + 1);
	var b = new Int32Array(n + 1);

	var i = 1;
	readline().split(' ').forEach(function(x) {
		a[i++] = +x;
	});

	for (var i = 0; i < q; i++) {
		var l = readline().split(' ');
		b[l[0]]++;
		b[+l[1] + 1]--;
	}

	var x = 0;
	for (var i = 1; i <= n; i++) {
		b[i] = (x += b[i]);
	}

	Array.prototype.sort.call(b, function(a, b) {
		return a - b;
	});
	Array.prototype.sort.call(a, function(a, b) {
		return a - b;
	});

	var ans = 0;
	for (var i = 1; i <= n; i++) {
		ans += a[i] * b[i];
	}
	return ans;
}.apply(0, readline().split(' ').map(Number)));

print(function(n, q) {
	var a = ('0 '+readline()).split(' ').map(Number).sort(function(a, b) {
		return a-b;
	});

	// n=n+1;

	var b = new Int32Array(n+1);
	for (var i = 0; i < q; i++) {
		readline().split(' ').map(Number).reduce(function(l, r) {
			b[l]++;
			b[r+1]--;
		});
	}

	var x = 0;
	var t = new Uint32Array(n+1);
	for (var i = 1; i <= n; i++) {
		x += b[i];
		t[i] = x;
	}

	Array.prototype.sort.call(t, function(a, b) {
		return a-b;
	});

	var ans = 0;
	for (var i = 1; i <= n; i++) {
		ans += a[i] * t[i];
	}
	return ans;
}.apply(0, readline().split(' ').map(Number)));

print(function(n, q) {
	var a = readline().split(' ').map(Number).sort(function(a, b) {
		return b - a;
	});
	var b = new Uint32Array(q);
	var c = new Uint32Array(q);

	for (var i = 0; i < q; i++) {
		readline().split(' ').map(Number).reduce(function(l, r) {
			b[i] = l;
			c[i] = r + 1;
		});
	}
	Array.prototype.sort.call(b, function(a, b) {
		return a - b;
	});
	Array.prototype.sort.call(c, function(a, b) {
		return a - b;
	});

	var x = 0;
	var j = 0;
	var k = 0;
	var t = new Uint32Array(n);
	for (var i = 1; i <= n; i++) {
		while (i == b[j]) x++, j++;
		while (i == c[k]) x--, k++;
		t[i-1]=x;
	}
	Array.prototype.sort.call(t, function(a, b) {
		return b-a;
	});

	var ans = 0;
	for (var i = 0; i < n; i++) {
		ans += a[i] * t[i];
	}
	return ans;
}.apply(0, readline().split(' ').map(Number)));

var first = readline().split(' ').map(f);
var n = first[0];
var q = first[1];

var a = readline().split(' ').map(f);
a.sort((x, y) => x - y);
a.reverse();
var pref = [];

var i, li, ri;

for(i = 0; i <= n + 1; i++){
    pref.push(0);
}

for(i = 0; i < q; i++){
    var query = readline().split(' ').map(f);
    li = query[0];
    ri = query[1];
    pref[li]++;
    pref[ri + 1]--;
}

for(i = 1; i <= n; i++){
    pref[i] = pref[i] + pref[i - 1];
}

pref.sort((x, y) => x - y);
pref.reverse();

var ans = 0;
for(i = 0; i < n; i++){
    ans = ans + pref[i] * a[i];
}

print(ans);

function f(x){
    return parseInt(x);
}

print(function(n, q) {
	var a = readline().split(' ').map(Number);
	var b = [];
	for (var i = 0; i <= n; i++) {
		b[i] = 0;
	}

	for (var i = 0; i < q; i++) {
		readline().split(' ').reduce(function(l, r) {
			b[l - 1]++;

			b[r]--;
		});
	}

	var x = 0;
	for (var i = 0; i < n; i++) {
		b[i] = (x += b[i]);
	}
	b.pop();
	b.sort(function(a, b) {
		return a - b;
	});
	a.sort(function(a, b) {
		return a - b;
	});

	var ans = 0;
	for (var i = 0; i < n; i++) {
		ans += a[i] * b[i];
	}
	return ans;
}.apply(0, readline().split(' ').map(Number)));

print(function(n, q) {
	var a = readline().split(' ').map(Number);
	var b = [];
	for (var i = 0; i < n; i++) {
		b[i] = 0;
	}

	for (var i = 0; i < q; i++) {
		readline().split(' ').reduce(function(l, r) {
			b[l - 1]++;
			if (r < n)
				b[r]--;
		});
	}

	var x = 0;
	for (var i = 0; i < n; i++) {
		b[i] = (x += b[i]);
	}

	b.sort(function(a, b) {
		return a - b;
	});
	a.sort(function(a, b) {
		return a - b;
	});

	var ans = 0;
	for (var i = 0; i < n; i++) {
		ans += a[i] * b[i];
	}
	return ans;
}.apply(0, readline().split(' ').map(Number)));

var first = readline().split(' ').map(f);
var n = first[0];
var q = first[1];

var a = readline().split(' ').map(f);
a.sort();
var pref = [];

var i, li, ri;

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

for(i = 0; i < q; i++){
    var query = readline().split(' ').map(f);
    li = query[0];
    ri = query[1];
    pref[li]++;
    pref[ri + 1]--;
}

for(i = 1; i <= n; i++){
    pref[i] = pref[i] + pref[i - 1];
}

pref.sort();

var ans = 0;
for(i = 1; i <= n; i++){
    ans = ans + pref[i] * a[i - 1];
}

print(ans);

function f(x){
    return parseInt(x);
}


In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.

The first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k).

Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.

NoteIn the first example the ranks will be raised in the following manner:1 2 2 3  →  2 2 3 4  →  2 3 4 4  →  3 4 4 4  →  4 4 4 4Thus totals to 4 training sessions that require 4 golden coins.

function getLine(){
    return readline().split(' ').map(function(x){
       return parseInt(x);
    });
}

var L = getLine();
var n = L[0];
var k = L[1];
var p = getLine();
var r = 0;
while(true){
    if(p.every(function(x){
        return x == k;
    })){
        break;
    }
    p = p.map(function(x, ind, self){
        if(ind === self.indexOf(x) && x < k){
            x++;
        }
        return x;
    });
    r++;
}
print(r);

'use strict'

const {EOL} = require('os')

let ipt = ''
process.stdin.on('data', s => ipt += s)
process.stdin.on('end', () => {
  let [nk, zs] = ipt.split(EOL)
  const [n, k] = nk.split(' ')
  zs = zs.split(' ').map(v => +v)
  let g = 0
  while (zs.some(z => z < k)) {
    g++
    let cz = 0
    for (let i = 0; i < zs.length; i++) {
      const z = zs[i]
      if (z == k) break
      if (cz < z) {
        zs[i]++
        cz = z
      }
    }
    zs = zs.sort((a, b) => a - b)
  }

  console.log(g)
})


Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9, a_i \ne 0$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of $$$a$$$.

NoteIn the first test case of the example, one of the possible answers is $$$[1, 2, \underline{3}, \underline{-1}, -2]$$$.In the second test case of the example, one of the possible answers is $$$[-1, -2, \underline{-1}, -3]$$$.In the third test case of the example, one of the possible answers is $$$[\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}]$$$.In the fourth test case of the example, one of the possible answers is $$$[\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]$$$.

//Alternating Subsequence

const {EOL} = require('os');

let inp = '';

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

process.stdin.on('end', () => {
    let lines = inp.split(EOL);

    let t = +lines[0];

    let sgn = (x) => (x > 0) ? 1 : -1;

    let f = (arr) => {
    	let sign = sgn(arr[0]);
    	let minmax = arr[0];
    	let sum = 0;
    	for(let i = 0; i < arr.length; i++)  {
    		if(sgn(arr[i]) == sign)  {
    			if(arr[i] > minmax)  {
    				minmax = arr[i];
    			}
    		}  else  {
    			sum += minmax;
    			sign = -sign;
    			minmax = arr[i];
    		}
    	}
		sum += minmax;
		return sum;
    }

    for(let i = 0; i < t; i++)  {
    	// let n = +lines[2 * i + 1];
    	let arr = lines[2 * i + 2].split(' ').map(c => +c);
    	process.stdout.write(f(arr) + EOL);
    }

    return;
});

'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 solve(n, a) {
  let last = a[0];
  let sum = last;
  for (let j = 1; j < n; j++) {
    if (last * a[j] > 0) {
      if (a[j] > last) {
        sum = sum - last + a[j];
        last = a[j];
      }
    } else {
      last = a[j];
      sum += a[j];
    }
  }
  return sum;
}

function main() {
  const t = parseInt(readLine());
  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let a = readLine().split(' ').map((val) => parseInt(val));
    let res = solve(n, a);
    console.log(res);
  }
  //process.stdout.write("hello: ");
}

'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 solve(n, a) {
  let countN = 0;
  let firstN = -1;
  for (let i = 0; i < n; i++) {
    if (a[i] < 0) {
      firstN = i;
      countN++;
      break;
    }
  }
  let sumN = Number.MIN_SAFE_INTEGER;
  if (countN > 0) {
    let last = a[firstN];
    sumN = last;
    for (let j = firstN + 1; j < n; j++) {
      if (last * a[j] > 0) {
        if (a[j] > last) {
          sumN = sumN - last + a[j];
          last = a[j];
        }
      } else {
        last = a[j];
        sumN += a[j];
        countN++;
      }
    }
  }
  let countP = 0;
  let firstP = -1;
  for (let i = 0; i < n; i++) {
    if (a[i] > 0) {
      firstP = i;
      countP++;
      break;
    }
  }
  let sumP = Number.MIN_SAFE_INTEGER;
  if (countP > 0) {
    let last = a[firstP];
    sumP = last;
    for (let j = firstP + 1; j < n; j++) {
      if (last * a[j] > 0) {
        if (a[j] > last) {
          sumP = sumP - last + a[j];
          last = a[j];
        }
      } else {
        last = a[j];
        sumP += a[j];
        countP++;
      }
    }
  }
  let sum = countP > countN ? sumP : countN > countP ? sumN : Math.max(sumN, sumP);
  return sum;
}

function main() {
  const t = parseInt(readLine());
  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let a = readLine().split(' ').map((val) => parseInt(val));
    let res = solve(n, a);
    console.log(res);
  }
  //process.stdout.write("hello: ");
}

'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() {
  //let [n, industry] = readline().split(" ").map(e => parseInt(e));

    let cases = parseInt(readline(), 10);
    for (var i = 0; i < cases; i++) {
      readline();
      const numbers = readline().split(" ").map(e => parseInt(e));

      let sum = 0;
      while (numbers.length > 0) {
        let sub = [numbers.pop()];
        let sign = Math.sign(sub[0]);

        while (numbers.length > 0 && Math.sign(numbers[numbers.length-1]) === sign) {
          sub.push(numbers.pop());
        }

        sum += Math.max.apply(null, sub);
      }

      console.log(sum);

    }

}

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
//atcoderのサンプルは最後に改行入れること
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
    var t = nextInt();
	var output = [];
	for(var i = 0; i < t; i++){
		var n = nextInt();
		var list = nextIntArray();
		var isPlus = true;
		var sum = 0;
		if(list[0] < 0){
			isPlus = false;
		}
		var plusList = [];
		var minusList = [];
		var tmpPlusList = [];
		var tmpMinusList = [];
		for(var j = 0; j < n; j++){
			if(isPlus){
				if(list[j] > 0){
					tmpPlusList.push(list[j]);
				}else{
					plusList.push(tmpPlusList);
					tmpPlusList = [];
					tmpMinusList.push(list[j]);
					isPlus = false;
				}
			}else{
				if(list[j] < 0){
					tmpMinusList.push(list[j]);
				}else{
					minusList.push(tmpMinusList);
					tmpMinusList = [];
					tmpPlusList.push(list[j]);
					isPlus = true;
				}
			}
			if(j == n - 1){
				if(tmpMinusList.length > 0){
					minusList.push(tmpMinusList);
				}
				if(tmpPlusList.length > 0){
					plusList.push(tmpPlusList);
				}
			}
		}
		//myerr("p:" + plusList);
		//myerr("m:" + minusList);
		for(var j = 0; j < plusList.length; j++){
			//myerr(plusList[j]);
			sum += Math.max.apply(null,plusList[j]);
		}
		for(var j = 0; j < minusList.length; j++){
			//myerr(minusList[j]);
			sum += Math.max.apply(null,minusList[j]);
		}
		output[i] = sum;
	}
	myout(myconv(output,9));
}

var t = parseInt(readline());

function mapper(s) { return +s; }

for(var qq = 0; qq < t; qq++) {
    var n = parseInt(readline());
    var a = readline().split(' ').map(mapper);
    var al = a.length;

    var sum = 0;

    var curMax = a[0];
    var onPos = a[0] > 0;

    for(var i = 1; i < al; i++) {
        if (onPos) {
            if (a[i] > 0) {
                if (a[i] > curMax) {
                    curMax = a[i];
                }
            } else {
                sum += curMax;
                onPos = false;
                curMax = a[i];
            }
        } else {
            if (a[i] < 0) {
                if (a[i] > curMax) {
                    curMax = a[i];
                }
            } else {
                sum += curMax;
                onPos = true;
                curMax = a[i];
            }
        }
    }
    sum += curMax;

    print(sum);
}

var range = readline();

for(var i=0;i<range;i++) {
    var input = parseInt(readline());
    var numbers = readline().split(" ").map((x) => parseInt(x));
    var sums = [];
    var max = [];
    var min = [];

    for(var j=0;j<numbers.length;j++) {
        if(numbers[j] < 0) {
            if(max.length) {
                var value = Math.max.apply(null, max);
                sums.push(value);

                max.length = 0;
            }
            min.push(numbers[j]);
        } else if(numbers[j] > 0) {
            if(min.length) {
                var value = Math.max.apply(null, min);
                sums.push(value);
                min.length = 0;
            }
            max.push(numbers[j]);
        }
    }

    if(max.length) {
        sums.push(Math.max.apply(null, max));
    }

    if(min.length) {
        sums.push(Math.max.apply(null, min));
    }

    if(sums.length === 0) {
        print(Math.max.apply(null, numbers));
    } else {
        var sum = sums.reduce((a, b) => a + b, 0);
        print(sum);
    }

}

'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 solve(n, a) {
  let sum = Number.MIN_SAFE_INTEGER;
  let countN = 0;
  let countP = 0;
  let firstN = -1;
  let firstP = -1;
  for (let i = 0; i < n; i++) {
    if (firstN !== -1 && firstP !== -1) break;
    if (firstN === -1 && a[i] < 0) {
      firstN = i;
      countN++;
    }
    if (firstP === -1 && a[i] > 0) {
      firstP = i;
      countP++;
    }
  }
  if (countN > 0) {
    for (let i = firstN; i < n; i++) {
      if (a[i] > 0) break;
      let last = a[i];
      let curSum = a[i];
      countN = 1;
      for (let j = i + 1; j < n; j++) {
        if (last * a[j] > 0) {
          if (curSum - last + a[j] > curSum) {
            last = a[j];
            curSum = curSum - last + a[j];
          }
        } else {
          last = a[j];
          curSum += a[j];
          countN++;
        }
      }
      sum = Math.max(sum, curSum);
    }
  }
  if (countP > 0) {
    for (let i = firstP; i < n; i++) {
      if (a[i] < 0) break;
      let last = a[i];
      let curSum = a[i];
      countP = 1;
      for (let j = i + 1; j < n; j++) {
        if (last * a[j] > 0) {
          if (curSum - last + a[j] > curSum) {
            last = a[j];
            curSum = curSum - last + a[j];
          }
        } else {
          last = a[j];
          curSum += a[j];
          countP++;
        }
      }
      if (countP >= countN) sum = Math.max(sum, curSum);
    }
  }
  return sum;
}

function main() {
  const t = parseInt(readLine());
  for (let i = 0; i < t; i++) {
    let n = parseInt(readLine());
    let a = readLine().split(' ').map((val) => parseInt(val));
    let res = solve(n, a);
    console.log(res);
  }
  //process.stdout.write("hello: ");
}

var range = readline();

for(var i=0;i<range;i++) {
    var input = parseInt(readline());
    var numbers = readline().split(" ").map((x) => parseInt(x));
    var sums = [];

    for(var j=0;j<numbers.length;j++) {
        if(numbers[j] < 0 && numbers[j+1] > 0) {
            sums.push(numbers[j]);
            sums.push(numbers[j+1]);
            j++;
        } else if(numbers[j] > 0 && numbers[j+1] <0) {
            sums.push(numbers[j]);
            sums.push(numbers[j+1]);
            j++;
        }
    }

    if(sums.length === 0) {
        print(Math.max.apply(null, numbers));
    } else {
        var sum = sums.reduce((a, b) => a + b, 0);
        print(sum);
    }

}


Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x > 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a ≥ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?

First line of input consists of single integer t (1 ≤ t ≤ 1 000 000) denoting number of games soldiers play. Then follow t lines, each contains pair of integers a and b (1 ≤ b ≤ a ≤ 5 000 000) defining the value of n for a game.

For each game output a maximum score that the second soldier can get.


There are $$$n$$$ railway stations in Berland. They are connected to each other by $$$n-1$$$ railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the $$$n-1$$$ sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from $$$1$$$ to $$$10^6$$$ inclusive.You asked $$$m$$$ passengers some questions: the $$$j$$$-th one told you three values:  his departure station $$$a_j$$$;  his arrival station $$$b_j$$$;  minimum scenery beauty along the path from $$$a_j$$$ to $$$b_j$$$ (the train is moving along the shortest path from $$$a_j$$$ to $$$b_j$$$). You are planning to update the map and set some value $$$f_i$$$ on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values $$$f_1, f_2, \dots, f_{n-1}$$$, which the passengers' answer is consistent with or report that it doesn't exist.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 5000$$$) — the number of railway stations in Berland. The next $$$n-1$$$ lines contain descriptions of the railway sections: the $$$i$$$-th section description is two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \ne y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are the indices of the stations which are connected by the $$$i$$$-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 5000$$$) — the number of passengers which were asked questions. Then $$$m$$$ lines follow, the $$$j$$$-th line contains three integers $$$a_j$$$, $$$b_j$$$ and $$$g_j$$$ ($$$1 \le a_j, b_j \le n$$$; $$$a_j \ne b_j$$$; $$$1 \le g_j \le 10^6$$$) — the departure station, the arrival station and the minimum scenery beauty along his path.

If there is no answer then print a single integer -1. Otherwise, print $$$n-1$$$ integers $$$f_1, f_2, \dots, f_{n-1}$$$ ($$$1 \le f_i \le 10^6$$$), where $$$f_i$$$ is some valid scenery beauty along the $$$i$$$-th railway section. If there are multiple answers, you can print any of them.

'use strict'

const n = +readline();
const edges = Array.from({ length: n - 1 }, () => readline().split(' ').map(i => +i - 1));
const passengers = Array.from({ length: +readline() }, () => readline().split(' ').map(i => +i)).map(p => [ p[0] - 1, p[1] - 1, p[2] ]);

const rootTree = (graph, n) => {
    // Do a DFS to (arbitrarily) root the tree and record depths
    const parent = Array(n).fill(null); parent[0] = Infinity;
    const parentEdge = Array(n).fill(null); parentEdge[0] = Infinity;
    const depth = Array(n).fill(null); depth[0] = 0;
    const stack = [ 0 ];
    while (stack.length) {
        const node = stack.pop();
        Object.keys(graph[node]).forEach((k) => {
            const edgeId = graph[node][k];
            if (parent[k] !== null) return;
            parent[k] = +node;
            parentEdge[k] = edgeId;
            depth[k] = depth[node] + 1;
            stack.unshift(k);
        });
    }
    return { parent, parentEdge, depth };
}

function* getLCAEdges(parent, parentEdge, depth, source, dest) {
    // Find shortest path by walking both nodes up till their LCA
    // Returns the edge ids in arbitrary order!
    let A = source, B = dest;

    // Start them at the same depth first
    let dA = depth[A], dB = depth[B];
    const r = [];
    while (dA > dB) {
        yield parentEdge[A];
        A = parent[A];
        dA -= 1;
    }
    while (dA < dB) {
        yield parentEdge[B];
        B = parent[B];
        dB -= 1;
    }
    // Walk up both paths until find lca
    while (A !== B) {
        yield parentEdge[A];
        A = parent[A];
        yield parentEdge[B];
        B = parent[B];
    }
    return r;
}

const problem = (n, edges, passengers) => {
    const graph = {};

    edges.forEach((a, i) => {
        const x = a[0], y = a[1];
        if (!graph[x]) graph[x] = {};
        if (!graph[y]) graph[y] = {};
        graph[x][y] = i;
        graph[y][x] = i;
    })

    const rt = rootTree(graph, n)
    const parent = rt.parent;
    const parentEdge = rt.parentEdge;
    const depth = rt.depth;
    // Sort by score, high to low
    passengers.sort((a, b) => b[2] - a[2]);
    // For each passenger, set any unset edges in their path to their min score
    const scores = Array(n - 1).fill(null);

    for (let i = 0; i < passengers.length; i++) {
        const p = passengers[i];
        const a = p[0];
        const b = p[1];
        const score = p[2];
        let numEdges = 0;

        for (let edgeId of getLCAEdges(parent, parentEdge, depth, a, b)) {
            if (scores[edgeId] === null) {
                numEdges += 1;
                scores[edgeId] = score;
            } else {
                // Since sorted any existing scores must higher or equal
                // Can't overwrite lower because will lower the previous's min score
                if (scores[edgeId] === score) numEdges += 1
            }
        }
        // Need to set at least one edge
        if (numEdges == 0) return -1;
    }

    return scores.map(i => i || 1).join(' ');
}

print(problem(n, edges, passengers));

'use strict'

const n = +readline();
const edges = Array.from({ length: n - 1 }, () => readline().split(' ').map(i => +i - 1));
const passengers = Array.from({ length: +readline() }, () => readline().split(' ').map(i => +i)).map(p => [ p[0] - 1, p[1] - 1, p[2] ]);

const rootTree = (graph, n) => {
    // Do a DFS to (arbitrarily) root the tree and record depths
    const parent = Array(n).fill(null); parent[0] = Infinity;
    const parentEdge = Array(n).fill(null); parentEdge[0] = Infinity;
    const depth = Array(n).fill(null); depth[0] = 0;
    const stack = [ 0 ];
    while (stack.length) {
        const node = stack.pop();
        Object.keys(graph[node]).forEach((k) => {
            const edgeId = graph[node][k];
            if (parent[k] !== null) return;
            parent[k] = node;
            parentEdge[k] = edgeId;
            depth[k] = depth[node] + 1;
            stack.unshift(k);
        });
    }
    return { parent, parentEdge, depth };
}

const getLCAEdges = (parent, parentEdge, depth, source, dest) => {
    // Find shortest path by walking both nodes up till their LCA
    // Returns the edge ids in arbitrary order!
    let A = source, B = dest;

    // Start them at the same depth first
    let dA = depth[A], dB = depth[B];
    const r = [];
    while (dA > dB) {
        r.push(parentEdge[A]);
        A = parent[A];
        dA -= 1;
    }
    while (dA < dB) {
        r.push(parentEdge[B]);
        B = parent[B];
        dB -= 1;
    }
    // Walk up both paths until find lca
    while (A !== B) {
        r.push(parentEdge[A]);
        A = parent[A];
        r.push(parentEdge[B]);
        B = parent[B];
    }
    return r;
}

const problem = (n, edges, passengers) => {
    const graph = {};

    edges.forEach((a, i) => {
        const x = a[0], y = a[1];
        if (!graph[x]) graph[x] = {};
        if (!graph[y]) graph[y] = {};
        graph[x][y] = i;
        graph[y][x] = i;
    })

    const rt = rootTree(graph, n)
    const parent = rt.parent;
    const parentEdge = rt.parentEdge;
    const depth = rt.depth;
    // Sort by score, high to low
    passengers.sort((a, b) => b[2] - a[2]);
    // For each passenger, set any unset edges in their path to their min score
    const scores = Array(n - 1).fill(null);

    for (let i = 0; i < passengers.length; i++) {
        const p = passengers[i];
        const a = p[0];
        const b = p[1];
        const score = p[2];
        let numEdges = 0;
        const lca = getLCAEdges(parent, parentEdge, depth, a, b);
        for (let j = 0; j < lca.length; j++) {
            const edgeId = lca[j];
            if (scores[edgeId] === null) {
                numEdges += 1;
                scores[edgeId] = score;
            } else {
                // Since sorted any existing scores must higher or equal
                // Can't overwrite lower because will lower the previous's min score
                if (scores[edgeId] === score) numEdges += 1
            }
        }
        // Need to set at least one edge
        if (numEdges == 0) return -1;
    }

    return scores.map(i => i || 1).join(' ');
}

print(problem(n, edges, passengers));


Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0, 1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner: where  is equal to 1 if some ai = 1, otherwise it is equal to 0.Nam has a matrix A consisting of m rows and n columns. The rows are numbered from 1 to m, columns are numbered from 1 to n. Element at row i (1 ≤ i ≤ m) and column j (1 ≤ j ≤ n) is denoted as Aij. All elements of A are either 0 or 1. From matrix A, Nam creates another matrix B of the same size using formula:.(Bij is OR of all elements in row i and column j of matrix A)Nam gives you matrix B and challenges you to guess matrix A. Although Nam is smart, he could probably make a mistake while calculating matrix B, since size of A can be large.

The first line contains two integer m and n (1 ≤ m, n ≤ 100), number of rows and number of columns of matrices respectively. The next m lines each contain n integers separated by spaces describing rows of matrix B (each element of B is either 0 or 1).

In the first line, print "NO" if Nam has made a mistake when calculating B, otherwise print "YES". If the first line is "YES", then also print m rows consisting of n integers representing matrix A that can produce given matrix B. If there are several solutions print any one.

var nm = readline().trim().split(' ').map((x)=>parseInt(x));
var n= nm[0];
var m = nm[1];
var b = []
for(var i=0;i<n;i++){
    b.push(readline().trim().split(' ').map((x)=>parseInt(x)));
}

var ans = [];
for (var i = 0; i < n; i++) {
		ans.push([]);
	for (var j = 0; j < m; j++) {
		ans[i].push(-1);
	}
}
var wrong = false;
for (var i = 0; i < n; i++) {
	for (var j = 0; j < m; j++) {
		if(b[i][j]==0){
			for (var k = 0; k < m; k++) {
				if(ans[i][k]==1){
					wrong = true;
					break
				}
				ans[i][k]=0;
			}
			for (var k = 0; k < n; k++) {
				if(ans[k][j]==1){
					wrong = true;
					break
				}
				ans[k][j]=0;
			}
		}
		if(wrong)
			break;
	}

	if(wrong)
		break;
}

if(wrong)
	print('NO');
else{
	for (var i = 0; i < n; i++) {
		for (var j = 0; j < m; j++) {
			if(b[i][j]==1){
				var isOne = false
				for (var k = 0; k < m; k++) {
					if(ans[i][k]!=0){
						isOne = true;
						break
					}
				}
				if(!isOne){
					for (var k = 0; k < n; k++) {
						if(ans[k][j]!=0){
							isOne = true;
							break
						}
					}
				}
				if(!isOne){
					wrong = true;
					break;
				}
			}

		}

		if(wrong)
			break;
	}

	if(wrong)
		print('NO');
	else{
		for (var i = 0; i < n; i++) {
			for (var j = 0; j < m; j++) {
				if(ans[i][j]==-1){
					ans[i][j]=1;
				}
			}
		}
		print('YES');
		for (var i = 0; i < n; i++) {
		    print(ans[i].join(' '));
		}
	}
}

var size = readline().trim().split(' ');
var m = size[0], n = size[1];
var MatrixA = [], MatrixB = [];

for (var i = 0; i < m; i++) {
  MatrixB.push([]);
  MatrixB[i] = readline().trim().split(' ');
  for (var j = 0; j < n; j++) {
    MatrixB[i][j] = parseInt(MatrixB[i][j]);
  }
}
for (var i = 0; i < m; i++) {
  MatrixA.push([]);
  for (var j = 0; j < n; j++) {
    MatrixA[i][j] = 1;
  }
}

function setRowZero(row) {
  for (var i = 0; i < n; i++) {
    MatrixA[row][i] = 0;
  }
}
function setColumnZero(col) {
  for (var i = 0; i < m; i++) {
    MatrixA[i][col] = 0;
  }
}

for (var i = 0; i < m; i++) {
  for (var j = 0; j < n; j++) {
    if (MatrixB[i][j] === 0) {
      setRowZero(i);
      setColumnZero(j);
    }
  }
}

function check() {
  var isOk = true;
  for (var i = 0; i < m; i++) {
    for (var j = 0; j < n; j++) {
      var target = MatrixB[i][j];
      var source = 0;
      for (var k = 0; k < m; k++) {
        if (MatrixA[k][j] === 1) {
          source = 1;
        }
      }
      for (var k = 0; k < n; k++) {
        if (MatrixA[i][k] === 1) {
          source = 1;
        }
      }
      if (target !== source) {
        isOk = false;
      }
    }
  }
  if (isOk) {
    print('YES');
    for (var i = 0; i < m; i++) {
      print(MatrixA[i].join(' '));
    }
  } else {
    print('NO');
  }

}

check();


On a weekend, Qingshan suggests that she and her friend Daniel go hiking. Unfortunately, they are busy high school students, so they can only go hiking on scratch paper.A permutation $$$p$$$ is written from left to right on the paper. First Qingshan chooses an integer index $$$x$$$ ($$$1\le x\le n$$$) and tells it to Daniel. After that, Daniel chooses another integer index $$$y$$$ ($$$1\le y\le n$$$, $$$y \ne x$$$).The game progresses turn by turn and as usual, Qingshan moves first. The rules follow:   If it is Qingshan's turn, Qingshan must change $$$x$$$ to such an index $$$x'$$$ that $$$1\le x'\le n$$$, $$$|x'-x|=1$$$, $$$x'\ne y$$$, and $$$p_{x'}<p_x$$$ at the same time.  If it is Daniel's turn, Daniel must change $$$y$$$ to such an index $$$y'$$$ that $$$1\le y'\le n$$$, $$$|y'-y|=1$$$, $$$y'\ne x$$$, and $$$p_{y'}>p_y$$$ at the same time. The person who can't make her or his move loses, and the other wins. You, as Qingshan's fan, are asked to calculate the number of possible $$$x$$$ to make Qingshan win in the case both players play optimally.

The first line contains a single integer $$$n$$$ ($$$2\le n\le 10^5$$$) — the length of the permutation. The second line contains $$$n$$$ distinct integers $$$p_1,p_2,\dots,p_n$$$ ($$$1\le p_i\le n$$$) — the permutation.

Print the number of possible values of $$$x$$$ that Qingshan can choose to make her win.

NoteIn the first test case, Qingshan can only choose $$$x=3$$$ to win, so the answer is $$$1$$$.In the second test case, if Qingshan will choose $$$x=4$$$, Daniel can choose $$$y=1$$$. In the first turn (Qingshan's) Qingshan chooses $$$x'=3$$$ and changes $$$x$$$ to $$$3$$$. In the second turn (Daniel's) Daniel chooses $$$y'=2$$$ and changes $$$y$$$ to $$$2$$$. Qingshan can't choose $$$x'=2$$$ because $$$y=2$$$ at this time. Then Qingshan loses.

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0;
    var n = +lines[l++]
    var arr = lines[l++].trim().split(' ').map(Number)
    console.log(solve(n, arr))
    // var t = +lines[l++]
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // }
});

function solve(n, arr) {
    const parts = []
    let cur
    for (let i = 1; i < n; i++) {
        if (arr[i] > arr[i - 1]) {
            if (!cur || cur.d !== 1) {
                parts.push(cur)
                cur = {
                    c: 1,
                    d: 1
                }
            }
            cur.c++
        } else {
            if (!cur || cur.d !== -1) {
                parts.push(cur)
                cur = {
                    c: 1,
                    d: -1
                }
            }
            cur.c++
        }
    }
    if (cur.c) parts.push(cur)
    parts.shift()

    const counts = parts.map(x => x.c)
    const max = Math.max(...counts)

    const mps = []
    let mul = false
    parts.forEach((p, i) => {
        if (p.c === max) {
            mps.push([p, i])
            if (mps.length > 2) mul = true
            if (mps.length > 1) {
                if (p.d < 0 && mps[0][1] === i - 1) return;
                mul = true
            }
        }
    })
    if (mul) return 0

    let c = 0
    parts.forEach((p, i) => {
        if (i && p.d < 0) {
            const a = Math.max(parts[i - 1].c, p.c)
            if (a < max) return

            const b = Math.min(parts[i - 1].c, p.c)
            if (a >= Math.ceil(b / 2) * 2) return;
            c++
        }
    })
    return c
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var l = 0;
    var n = +lines[l++]
    var arr = lines[l++].trim().split(' ').map(Number)
    console.log(solve(n, arr))
    // var t = +lines[l++]
    // for (var i = 0; i < t; i++) {
    // var n = +lines[l++]
    // }
});

function solve(n, arr) {
    const parts = []
    let cur
    for (let i = 1; i < n; i++) {
        if (arr[i] > arr[i - 1]) {
            if (!cur || cur.d !== 1) {
                parts.push(cur)
                cur = {
                    c: 1,
                    d: 1
                }
            }
            cur.c++
        } else {
            if (!cur || cur.d !== -1) {
                parts.push(cur)
                cur = {
                    c: 1,
                    d: -1
                }
            }
            cur.c++
        }
    }
    if (cur.c) parts.push(cur)
    parts.shift()

    let c = 0
    parts.forEach((p, i) => {
        if (i && p.d < 0) {
            const a = Math.max(parts[i - 1].c, p.c)
            const b = Math.min(parts[i - 1].c, p.c)
            if (a >= Math.ceil(b / 2) * 2) return;
            c++
        }
    })
    return c
}


While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.

The first line contains string a, and the second line — string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.

If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.

NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.

function out(a, b){return (a===b)?-1:(a.length > b.length)?a.length:b.length}
print(out(readline(),readline()))

var out = function(a, b){return (a===b)?-1:Math.max(a.length,b.length)}
print(out(readline(),readline()))

var a = readline();
var b = readline();
if(a==b)
    print(-1);
else
    print(Math.max(a.length,b.length));

var x = readline();
var y = readline();

if (x == y) {
  print(-1);
} else {
  print(parseInt(Math.max(x.length,y.length)));
}

s1 = readline();
s2 = readline();
ans = -1;
if(s1 !== s2){
    ans = Math.max(s1.length, s2.length);
}
print(ans);

/* global readline, print */
const a = readline()
const b = readline()

if (a === b) print(-1)
else print(Math.max(a.length, b.length))

var a = readline(),
    b = readline(),
    arr = [],
    res = 0;

if (a.length > b.length) res = a.length;
else if (b.length > a.length) res = b.length;
else if (a === b) res = -1;
else {
    res = a.length;
}

print(res);

var s1 =readline();
var s2 = readline();
var p =function () {if (s1!==s2) {return Math.max(s1.length,s2.length)} else return -1};
print (p());

'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 a = readline();
  const b = readline();
  let l;
  if (a.length !== b.length) {
    l = Math.max(a.length, b.length);
  } else {
    l = a === b ? -1 : a.length;
  }
  print(l);
}

'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 readint() {
    let line = readline().split(' ').map(function(num) {
        return parseInt(num);
    });
    return line;
}

function readfloat() {
    let line = readline().split(' ').map(function(num) {
        return parseFloat(num);
    });
    return line;
}

function print(x) {
    console.log(x);
}

function write(x) {
    process.stdout.write(x);
}

function array2d(r,c) {
    let ans =[];
    for(let i = 0; i < r; i++) {
        let rowElements = [];
        for(let j = 0; j < c; j++) {
            rowElements.push(0);
        }
        ans.push(rowElements);
    }
    return ans;
}
function max(a,b){
    if(a > b) return a;
    else return b;
}
function main() {
    let m = readline();
    let e = readline();
    if(m.length < e.length) {
        [e, m] = [m, e];
    }
    if(m == e) print(-1);
    else print(m.length);
}

const {stdin, exit} = require('process');
let inp = "";
stdin.on('data', chunk => inp += chunk).on('end', () => {
    let [a, b] = inp.split('\n').map(s => s.trim());
    if (a === b) console.log(-1);
    else console.log(Math.max(a.length, b.length));
})

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

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

let nl = nextLine();

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

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

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

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

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

const sol = () => {
	let a = nl.line();
	let b = nl.line();
    console.log((a !== b)?Math.max(a.length, b.length):-1);

};

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

var a = readline();
var b = readline();
if (a == b) {
	print (-1);
} else {
	if (a.length > b.length) {
		print (a.length);
	} else if (a.length < b.length) {
		print (b.length);
	} else if (a.length = b.length) {
		print (a.length);
	}
}

function main() {
    var line1 = readline();
    var line2 = readline();
    if(line1 == line2){
        return print(-1);
    } else {
        print(Math.max(line1.length, line2.length))
    }
}

main()

;(function () {
	var a = readline(),
		b = readline()
	if (a === b) print(-1)
	else print(Math.max(a.length, b.length))
})();

var a = readline();
var b = readline();

if (a === b) {
    print(-1);
} else {
    print(Math.max(a.length , b.length));
}

'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 readint() {
    let line = readline().split(' ').map(function(num) {
        return parseInt(num);
    });
    return line;
}

function readfloat() {
    let line = readline().split(' ').map(function(num) {
        return parseFloat(num);
    });
    return line;
}

function print(x) {
    console.log(x);
}

function write(x) {
    process.stdout.write(x);
}

function array2d(r,c) {
    let ans =[];
    for(let i = 0; i < r; i++) {
        let rowElements = [];
        for(let j = 0; j < c; j++) {
            rowElements.push(0);
        }
        ans.push(rowElements);
    }
    return ans;
}
function max(a,b){
    if(a > b) return a;
    else return b;
}
function main() {
    let m = readline();
    let e = readline();
    if(m.length < e.length) {
        [e, m] = [m, e];
    }
    let dp = array2d(m.length, e.length);
    let i = 0;
    for(const element of e) {
        if(m[0] != element)  dp[0][i] = 1;
        i++;
    }
    i = 0;
    for(const element of m) {
        if(e[0] != element) dp[i][0] = 1;
        i++;
    }
    for(let i = 1; i < m.length; i++) {
        for(let j = 1; j < e.length; j++) {
            if(m[i] != e[j]) {
                dp[i][j] = dp[i-1][j - 1] + 1;
            }
        }
    }
    let ans = dp[m.length - 1][e.length - 1];
    if(ans == e.length) print(m.length);
    else if(ans == 0) print(-1);
    else print(ans);
}

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

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

let nl = nextLine();

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

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

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

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

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

const sol = () => {
	let a = nl.line().split('');
	let b = nl.line().split('');
	let t = '';
	let aa = [];
	for(let c of a){
		if (t.length > 0) {
			if (c >= t.charAt(t.length-1)) {
				t += c;
			} else {
				aa.push(t);
				t = c;
			}

		} else {
			t += c;
		}
	}
	aa.push(t);
	t = '';
	let bb = [];
	for(let c of b){
		if (t.length > 0) {
			if (c >= t.charAt(t.length-1)) {
				t += c;
			} else {
				bb.push(t);
				t = c;
			}

		} else {
			t += c;
		}
	}
	bb.push(t);
	let cc = aa.filter(x => !bb.includes(x)).concat(bb.filter(x => !aa.includes(x)));
	if (cc.length === 0){
		console.log(-1);
	} else {
		console.log(Math.max(...(cc.map(x => x.length))));
	}

};

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

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

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

let nl = nextLine();

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

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

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

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

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

const sol = () => {
	let a = nl.line().split('');
	let b = nl.line().split('');
	let t = '';
	let aa = [];
	for(let c of a){
		if (t.length > 0) {
			if (c > t.charAt(t.length-1)) {
				t += c;
			} else {
				aa.push(t);
				t = c;
			}

		} else {
			t += c;
		}
	}
	aa.push(t);
	t = '';
	let bb = [];
	for(let c of b){
		if (t.length > 0) {
			if (c > t.charAt(t.length-1)) {
				t += c;
			} else {
				bb.push(t);
				t = c;
			}

		} else {
			t += c;
		}
	}
	bb.push(t);
	let cc = aa.filter(x => !bb.includes(x)).concat(bb.filter(x => !aa.includes(x)));
	if (cc.length === 0){
		console.log(-1);
	} else {
		console.log(Math.max(...(cc.map(x => x.length))));
	}

};

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

var a = readline();
var b = readline();
if (a == b) {
	print (-1);
} else {
	if (a.length > b.length) {
		print (a.length);
	} else if (a.length < b.length) {
		print (b.length);
	} else if (a.length = b.length) {
		print (-1);
	}
}

var a = readline();
var b = readline();
if (a == b) {
	print (-1);
} else {
	if (a.length > b.length) {
		print (a.length);
	} else if (a.length < b.length) {
		print (b.length);
	}
}


Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands of m managers. Each of them may reorder the elements in some order. Namely, the i-th manager either sorts first ri numbers in non-descending or non-ascending order and then passes the report to the manager i + 1, or directly to Blake (if this manager has number i = m).Employees of the "Blake Technologies" are preparing the report right now. You know the initial sequence ai of length n and the description of each manager, that is value ri and his favourite order. You are asked to speed up the process and determine how the final report will look like.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of commodities in the report and the number of managers, respectively. The second line contains n integers ai (|ai| ≤ 109) — the initial report before it gets to the first manager. Then follow m lines with the descriptions of the operations managers are going to perform. The i-th of these lines contains two integers ti and ri (, 1 ≤ ri ≤ n), meaning that the i-th manager sorts the first ri numbers either in the non-descending (if ti = 1) or non-ascending (if ti = 2) order.

Print n integers — the final report, which will be passed to Blake by manager number m.

NoteIn the first sample, the initial report looked like: 1 2 3. After the first manager the first two numbers were transposed: 2 1 3. The report got to Blake in this form.In the second sample the original report was like this: 1 2 4 3. After the first manager the report changed to: 4 2 1 3. After the second manager the report changed to: 2 4 1 3. This report was handed over to Blake.

var str = readline().split(" ", 2);
var n = Number(str[0]);
var m = Number(str[1]);

var num = readline().split(" ", n).map(Number);
var key = new Array(m);
for (var i = 0; i < m; ++i) {
	key[i] = readline().split(" ", 2).map(Number);
}

var newk = [], maxv = 0;
for (var i = m - 1; i >= 0; --i) {
	if (key[i][1] > maxv) {
		maxv = key[i][1];
		newk.push(key[i]);
	}
}

var len = newk.length;
var ans = new Array(n);
for (var i = newk[len - 1][1]; i < n; ++i) {
	ans[i] = num[i];
}
num = num.slice(0, newk[len - 1][1]);
num.sort(function (a, b) {return a - b;});

var beg = 0;
for (var i = len - 1; i >= 0; --i) {
	if (newk[i][0] === 1) {
		if (i === 0) {
			for (var j = 0; j < newk[i][1]; ++j) {
				ans[j] = num[beg + j];
			}
		} else {
			for (var j = newk[i - 1][1]; j < newk[i][1]; ++j) {
				ans[j] = num[beg + j];
			}
		}
	} else {
		if (i === 0) {
			for (var j = 0; j < newk[i][1]; ++j) {
				ans[j] = num[beg + newk[i][1] - j - 1];
			}
		} else {
			for (var j = newk[i - 1][1]; j < newk[i][1]; ++j) {
				ans[j] = num[beg + newk[i][1] - j - 1];
			}
			beg += newk[i][1] - newk[i - 1][1];
		}
	}
}

print(ans.join(" "));

var str = readline().split(" ", 2);
var n = Number(str[0]);
var m = Number(str[1]);

var num = readline().split(" ", n).map(Number);
var key = new Array(m);
for (var i = 0; i < m; ++i) {
	key[i] = readline().split(" ", 2).map(Number);
}

var newk = [], maxv = 0;
for (var i = m - 1; i >= 0; --i) {
	if (key[i][1] > maxv) {
		maxv = key[i][1];
		newk.push(key[i]);
	}
}

var len = newk.length;
var ans = new Array(n);
for (var i = newk[len - 1][1]; i < n; ++i) {
	ans[i] = num[i];
}
num = num.slice(0, newk[len - 1][1]);
num.sort(function (a, b) {return a - b;});

for (var i = len - 1; i >= 0; --i) {
	if (newk[i][0] === 1) {
		if (i === 0) {
			for (var j = 0; j < newk[i][1]; ++j) {
				ans[j] = num[j];
			}
		} else {
			for (var j = newk[i - 1][1]; j < newk[i][1]; ++j) {
				ans[j] = num[j];
			}
			num = num.slice(0, newk[i - 1][1]);
		}
	} else {
		if (i === 0) {
			for (var j = 0; j < newk[i][1]; ++j) {
				ans[j] = num[newk[i][1] - j - 1];
			}
		} else {
			for (var j = newk[i - 1][1]; j < newk[i][1]; ++j) {
				ans[j] = num[newk[i - 1][1] + newk[i][1] - j - 1];
			}
			num = num.slice(newk[i][1] - newk[i - 1][1], newk[i][1]);
		}
	}
}

print(ans.join(" "));

var str = readline().split(" ", 2);
var n = Number(str[0]);
var m = Number(str[1]);

var num = readline().split(" ", n).map(Number);
var key = new Array(m);
for (var i = 0; i < m; ++i) {
	key[i] = readline().split(" ", 2).map(Number);
}

var newk = [], maxv = 0;
for (var i = m - 1; i >= 0; --i) {
	if (key[i][1] > maxv) {
		maxv = key[i][1];
		newk.push(key[i]);
	}
}

var len = newk.length;
var ans = new Array(n);
for (var i = newk[len - 1][1]; i < n; ++i) {
	ans[i] = num[i];
}
num = num.slice(0, newk[len - 1][1]);
num.sort(function (a, b) {return a - b;});

for (var i = len - 1; i >= 0; --i) {
	if (newk[i][0] === 1) {
		if (i === 0) {
			for (var j = 0; j < newk[i][1]; ++j) {
				ans[j] = num[j];
			}
		} else {
			for (var j = newk[i - 1][1]; j < newk[i][1]; ++j) {
				ans[j] = num[j];
			}
			num = num.slice(0, newk[i - 1][1]);
		}
	} else {
		if (i === 0) {
			for (var j = 0; j < newk[i][1]; ++j) {
				ans[j] = num[newk[i][1] - j];
			}
		} else {
			for (var j = newk[i - 1][1]; j < newk[i][1]; ++j) {
				ans[j] = num[newk[i][1] - j];
			}
			num = num.slice(newk[i][1] - newk[i - 1][1], newk[i][1]);
		}
	}
}

print(ans.join(" "));

var str = readline().split(" ", 2);
var n = Number(str[0]);
var m = Number(str[1]);

var num = readline().split(" ", n).map(Number);
var key = new Array(m);
for (var i = 0; i < m; ++i) {
	key[i] = readline().split(" ", 2).map(Number);
}

var newk = [], maxv = 0;
for (var i = m - 1; i >= 0; --i) {
	if (key[i][1] > maxv) {
		maxv = key[i][1];
		newk.push(key[i]);
	}
}

var len = newk.length;
var ans = new Array(n);
for (var i = newk[len - 1][1]; i < n; ++i) {
	ans[i] = num[i];
}
num = num.slice(0, newk[len - 1][1]);
num.sort();
var rank = 1;

for (var i = len - 1; i >= 0; --i) {
	if (rank !== newk[i][0]) {
		num.reverse();
		rank = 3 - rank;
	}
	if (i === 0) {
		for (var j = 0; j < newk[i][1]; ++j) {
			ans[j] = num[j];
		}
	} else {
		for (var j = newk[i - 1][1]; j < newk[i][1]; ++j) {
			ans[j] = num[j];
		}
		num = num.slice(0, newk[i - 1][1]);
	}
}

print(ans.join(" "));


In the pet store on sale there are:  $$$a$$$ packs of dog food;  $$$b$$$ packs of cat food;  $$$c$$$ packs of universal food (such food is suitable for both dogs and cats). Polycarp has $$$x$$$ dogs and $$$y$$$ cats. Is it possible that he will be able to buy food for all his animals in the store? Each of his dogs and each of his cats should receive one pack of suitable food for it.

The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ lines are given, each containing a description of one test case. Each description consists of five integers $$$a, b, c, x$$$ and $$$y$$$ ($$$0 \le a,b,c,x,y \le 10^8$$$).

For each test case in a separate line, output:   YES, if suitable food can be bought for each of $$$x$$$ dogs and for each of $$$y$$$ cats;  NO else.  You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).

var t = Number(readline());

for (var i = 0; i < t; i++) {
    var arr = readline().split(" ");
    var a = Number(arr[0]);
    var b = Number(arr[1]);
    var c = Number(arr[2]);
    var x = Number(arr[3]);
    var y = Number(arr[4]);
    if (x <= a + c) {
        c -= Math.max(x - a, 0);
        if (y <= b + c) {
            print("YES");
            continue;
        }
    }
    print("NO");
}

var t = +readline()

for(var i = 0; i< t; i ++) {
    var a = readline().split(' ').map((t) => +t)
    print(Task1(a[0],a[1],a[2],a[3],a[4]));
}

function Task1 (a,b,c,x,y){

  var test1 = a-x;
  var test2 = b-y;

  if (test1 < 0) {
    var just = test1;
    test1 += c;
    c += just;
  }
  if (test2 < 0){
    test2 += c;
  }

  var res = test1 >= 0 && test2 >= 0;
  return res ? 'YES': 'NO'

}

    var t = readline();
    for(var i = 0 ; i < t ; i++){
        var inputs = readline().split(' '),
            a = inputs[0], b = inputs[1], c = inputs[2];
            x = inputs[3], y = inputs[4] , counter = 0;
             if(a - x < 0){
                counter+= Math.abs(a - x);
            }
             if(b - y < 0){
                counter+= Math.abs(b - y);
            }
            if(counter === 0){
                print("YES");
            }
            else if(c - counter >= 0){
                print("YES");
            }
            else{
                print("NO");
            }
    }

//import { readline, print } from '@ip-algorithmics/codeforces-io';
var t = +readline();
for (var _i = 0, _a = Array.from(Array(t).keys()); _i < _a.length; _i++) {
    var i = _a[_i];
    var _b = readline().split(' ').map(function (v) { return +v; }), a = _b[0], b = _b[1], c = _b[2], x = _b[3], y = _b[4];
    print(Math.max(0, x - a) + Math.max(0, y - b) > c ? 'NO' : 'YES');
}

T = readline()
while(T--){
   x = readline().split(' ').map(x => +x)
   forDogs = x[0]
   forCats = x[1]
   forAll = x[2]
   dogs = x[3]
   cats = x[4]

   res = 'NO'

   if (forDogs >= dogs &&forCats  >= cats)
      res = 'YES'
   else if(forDogs < dogs && forCats  >= cats && forAll >= dogs - forDogs)
      res = 'YES'
   else if (forDogs >= dogs && forCats  < cats && forAll >= cats - forCats)
      res = 'YES'
   else if(forDogs < dogs && forCats  < cats && forAll >= (cats - forCats)+ (dogs - forDogs))
      res = 'YES'

   print(res)
}

const readline = require("readline");

var input = [];

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

rl.on("line", function (val) {
  input.push(val);
});

rl.on("close", function () {
  for (let i = 1; i <= input[0]; i++) {
    var entities = input[i].split(" ").map(x => parseInt(x))
    var dogFoodEater = (entities[3] - entities[0]) < 0 ? 0 : (entities[3] - entities[0]);
    var catFoodEater = (entities[4] - entities[1]) < 0 ? 0 : (entities[4] - entities[1]);
    if (dogFoodEater + catFoodEater > entities[2]) {
        console.log("NO");
    } else {
        console.log("YES");
    }
  }

  process.exit(0);
});

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const [a,b,c,x,y] = get_ints();

        const res = MY_FUNC(a,b,c,x,y);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function MY_FUNC(a,b,c,x,y){
    let ans = 'NO';
    Math.max(0,x - a) + Math.max(0,(y - b)) <= c ? ans = 'YES': ans;
    return ans;
}

'use-strict'

process.stdin.resume();
process.stdin.setEncoding('utf8');

let data = '';
let currentLine = 0;

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

process.stdin.on('end', () =>{
    data = data.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    let testCases = parseInt(data.shift());

    while(testCases--) {

        const [a,b,c,x,y] = get_ints();

        const res = MY_FUNC(a,b,c,x,y);

        console.log(res)
    }
});

function get_ints() {
    return data.shift().split(' ').map(Number);
}

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

function MY_FUNC(a,b,c,x,y){
    if(x > a){
        if(a + c < x) return 'NO';
        c-= x - a;
    }
    if(y > b){
        if(b + c < y) return 'NO';
    }
    return 'YES';
}

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}
function alpha() {
  var g = []
  var f = 'abcdefghijklmnopqrstuvwxyz';
  for(var x=0;x<f.length;x++) g[f[x]] = x+1;
  return g;
}
function Alpha() {
  var g = []
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  for(var x=0;x<f.length;x++) g[f[x]] = x+1;
  return g;
}
var T = readline();
for(var q=1;q<=T;q++) {
  var [a,b,c,x,y] = readline().split(' ').map((x)=> parseInt(x))
  a -= x;
  b -= y;
  a = Math.min(a, 0);
  b = Math.min(b, 0)
  var ans = 0;
  if(c+(a+b) >= 0) ans = 1;
  else ans = 0;
  console.log(ans? 'YES': 'NO');
  //fs.appendFileSync('output.txt', (ans?'YES':'NO')+'\r\n');
  //os.EOL
}
//fs.writeFileSync('output.txt', f.join(' '));

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

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

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

    for (let test = 0; test < N; test++) {
        let [a,b,c,x,y] = readline().split(' ').map(Number);

        x = Math.max(0, x - a);
        y = Math.max(0, y - b);

        output((x + y) <= c ? 'YES' : 'NO');
    }
}

const rdline = require('readline');
const rl = rdline.createInterface({
    input: process.stdin
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line);
}).on('close', () => {
    // input in lines
    solve();
});

let line = 0;
const readline = () => lines[line++];

solve = () => {
    const t = parseInt(readline());
    for (let i = 0; i < t; i++) {
        var food = readline().split(" ").map(Number);
        var a = food[0];
        var b = food[1];
        var c = food[2];
        var x = food[3];
        var y = food[4];
        if (c >= Math.max(0, x - a) + Math.max(0, y - b)) {
            console.log("YES")
        } else {
            console.log("NO")
        }

    }
}

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

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

// ********** Code Start **********

function main() {
    var t = parseInt(readline());

    for (let i = 0; i < t; i++) {
        var line = readline().split(' ');
        var a = parseInt(line[0]);
        var b = parseInt(line[1]);
        var c = parseInt(line[2]);
        var x = parseInt(line[3]);
        var y = parseInt(line[4]);

        a -= x;
        b -= y;
        if (Math.max(0,-a)+Math.max(0,-b) > c) {
            console.log('NO');
        } else {
            console.log('YES');
        }

    }
}

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    for(i = 1; i <= n; i++){
        var k = lines[i].split(' ').map(Number);
        var a = k[0];
        var b = k[1];
        var c = k[2];
        var x = k[3];
        var y = k[4];
        var s = 0
        x -= a
        y -= b
        if(x > 0){
            c -= x;
        }if(y > 0){
            c -= y;
        }
        if(c >= 0){
            console.log('YES');
        }else{
            console.log('NO');
        }
    }
});

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

function print(x) {
  console.log(x);
}
let inputString = "";
let currentLine = 0;

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

// ********** Code Start **********

function main() {

    let num = Number.parseInt(readline());

    while(num-- > 0){
        let input = readline();
        let inputArr = input.split(' ')
        let dogF = Number.parseInt(inputArr[0])
        let catF = Number.parseInt(inputArr[1])
        let UniversalF = Number.parseInt(inputArr[2])
        let dog = Number.parseInt(inputArr[3])
        let cat = Number.parseInt(inputArr[4])
        let res1 = (dog <= dogF) ? 0 : dog - dogF;
        let res2 = (cat <= catF) ? 0 : cat - catF;
        let res = ((res1 + res2) <= UniversalF) ? 'YES' : 'NO';
        console.log(res)
    }
}

let q = '';
process.stdin.on('data', c => q += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = q.split(EOL);
    var n = lines[0];
    for(i = 1; i <= n; i++){
        var k = lines[i].split(' ').map(Number);
        var a = k[0]; var b = k[1]; var c = k[2]; var x = k[3]; var y = k[4];
        var temp = 0;
        x -= a;
        y -= b;
        if(x > 0){
            c -= x;
        }if(y > 0){
            c -= y;
        }
        if(c >= 0){
            console.log('Yes');
        }else{
            console.log('No');
        }
    }
});

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

rl.on("line", function (line) {
  var input = line.split(" ");
  if (input.length === 5) {
    var [dogsFood, catsFood, univeralFood, xDogs, yCats] = input.map(Number);
    var hungryDogs = xDogs - dogsFood < 0 ? 0 : xDogs - dogsFood;
    var hungryCats = yCats - catsFood < 0 ? 0 : yCats - catsFood;
    if (hungryDogs + hungryCats <= univeralFood) {
      console.log("YES");
    } else {
      console.log("NO");
    }
  }
});

'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([a, b, c, x, y]) {
  x -= a;
  y -= b;
  if (x <= 0 && y <= 0) {
    console.log('yes');
    return;
  }
  if (x > 0) {
    c -= x;
  }
  if (c < 0) {
    console.log('no');
    return;
  }
  if (y > 0) {
    c -= y;
  }
  if (c < 0) {
    console.log('no');
    return;
  }
  console.log('yes');
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const a = (await read()).split(' ').map(Number);
    solve(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);
}();

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 cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (a, b, c, x, y)=>{
    let dog = Math.max(x - a, 0);
    let cat = Math.max(y - b, 0);
    let all = dog + cat - c;
    if (all > 0) return 'NO';
    return 'YES';
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        // let n = +readline();
        let [a, b, c, x, y] = ra();
        console.log(`${calc(a, b, c, x, y)}`);
    }
}

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

function solve(arr) {
    const [a, b, c, d, e] = arr
    const ca = Math.max(0, d - a)
    const cb = Math.max(0, e - b)
    return ca + cb <= c
}

'use strict';
// HEADER:
const print = console.log;
let IS_MULTITEST, testN;
const pcalc = testN=>{
  let res = calc(testN);
  if (Array.isArray(res)){
    pa(res);
  } else if (Number.isFinite(res) || typeof res=='string'){
    print(res);
  }
};

const main = ()=>{
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(T);
  } else
   pcalc();
};

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;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`Test #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

// SOLUTION:
IS_MULTITEST = 1;

const calc = ()=>{
  // READING:
  let [a, b, c, x, y] = ra();
  LT({a, b, c, x, y});

  // PROCESSING:
  x -= a;
  y -= b;
  if (Math.max(x, 0)+Math.max(y, 0)<=c)
    return 'YES';
  return 'NO'
};

var t = Number(readline());

for(var i = 0; i < t; i++){
    var arr = readline().split(' ');

    print('NO');
}

var t = Number(readline());
var str = readline().split('');
var arr = [];
str.forEach((cur, i) => {
    arr.push(str.slice(i,i+2).join(''));
});
var obj= {}, maxEl, maxCount = 0;
arr.forEach((cur, i) => {
    if(!obj[cur]){
        obj[cur] = 1;
    }else{
      obj[cur]++;
    }

    if(obj[cur] > maxCount){
        maxCount = obj[cur];
        maxEl = cur;
    }
});

print(maxEl);

var t = +readline()

for(var i = 0; i< t; i ++) {
    var a = readline().split(' ').map((t) => +t)
    print(Task1(a[0],a[1],a[2],a[3],a[4]));
}

function Task1 (a,b,c,x,y){

  var test1 = a-x;
  var test2 = b-y;

  if (test1 < 0) {
    var just = test1;
    test1 += c;
    c += just;
  }
  if (test2 < 0){
    test2 += c;
  }

  return test1 >= 0 && test2 >= 0;

}

const readline = require("readline");

var input = [];

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

rl.on("line", function (val) {
  input.push(val);
});

rl.on("close", function () {
  for (let i = 1; i <= input[0]; i++) {
    var entities = input[i].split(" ").map(x => parseInt(x))
    var dogFoodEater = entities[0] - entities[3];
    var catFoodEater = entities[1] - entities[4];
    if (dogFoodEater + catFoodEater > entities[2]) {
        console.log("NO");
    } else {
        console.log("YES");
    }
  }

  process.exit(0);
});

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}
function alpha() {
  var g = []
  var f = 'abcdefghijklmnopqrstuvwxyz';
  for(var x=0;x<f.length;x++) g[f[x]] = x+1;
  return g;
}
function Alpha() {
  var g = []
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  for(var x=0;x<f.length;x++) g[f[x]] = x+1;
  return g;
}
var T = readline();
for(var q=1;q<=T;q++) {
  var [a,b,c,x,y] = readline().split(' ').map((x)=> parseInt(x))
  a -= x;
  b -= y;
  a = Math.min(a, 0);
  b = Math.min(b, 0)
  var ans = 0;
  if(c+(a+b) >= 0) ans = 1;
  else ans = 0;
  console.log(ans);
  //fs.appendFileSync('output.txt', (ans?'YES':'NO')+'\r\n');
  //os.EOL
}
//fs.writeFileSync('output.txt', f.join(' '));


Ashish has a binary string $$$s$$$ of length $$$n$$$ that he wants to sort in non-decreasing order.He can perform the following operation:   Choose a subsequence of any length such that its elements are in non-increasing order. Formally, choose any $$$k$$$ such that $$$1 \leq k \leq n$$$ and any sequence of $$$k$$$ indices $$$1 \le i_1 \lt i_2 \lt \ldots \lt i_k \le n$$$ such that $$$s_{i_1} \ge s_{i_2} \ge \ldots \ge s_{i_k}$$$.  Reverse this subsequence in-place. Formally, swap $$$s_{i_1}$$$ with $$$s_{i_k}$$$, swap $$$s_{i_2}$$$ with $$$s_{i_{k-1}}$$$, $$$\ldots$$$ and swap $$$s_{i_{\lfloor k/2 \rfloor}}$$$ with $$$s_{i_{\lceil k/2 \rceil + 1}}$$$ (Here $$$\lfloor x \rfloor$$$ denotes the largest integer not exceeding $$$x$$$, and $$$\lceil x \rceil$$$ denotes the smallest integer not less than $$$x$$$) Find the minimum number of operations required to sort the string in non-decreasing order. It can be proven that it is always possible to sort the given binary string in at most $$$n$$$ operations.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 1000)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 1000)$$$  — the length of the binary string $$$s$$$. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ containing only $$$0$$$s and $$$1$$$s. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.

For each test case output the following:   The minimum number of operations $$$m$$$ in the first line ($$$0 \le m \le n$$$).  Each of the following $$$m$$$ lines should be of the form: $$$k$$$ $$$i_1$$$ $$$i_2$$$ ... $$$i_{k}$$$, where $$$k$$$ is the length and $$$i_1 \lt i_2 \lt ... \lt i_{k}$$$ are the indices of the chosen subsequence. For them the conditions from the statement must hold.

NoteIn the first test case, the binary string is already sorted in non-decreasing order.In the second test case, we can perform the following operation:   $$$k = 4:$$$ choose the indices $$$\{1, 3, 4, 5\}$$$$$$\underline{1}$$$ $$$0$$$ $$$\underline{1}$$$ $$$\underline{0}$$$ $$$\underline{0}$$$ $$$\rightarrow $$$ $$$\underline{0}$$$ $$$0$$$ $$$\underline{0}$$$ $$$\underline{1}$$$ $$$\underline{1}$$$ In the third test case, we can perform the following operation:  $$$k = 3:$$$ choose the indices $$$\{3, 5, 6\}$$$$$$0$$$ $$$0$$$ $$$\underline{1}$$$ $$$0$$$ $$$\underline{0}$$$ $$$\underline{0}$$$ $$$\rightarrow $$$ $$$0$$$ $$$0$$$ $$$\underline{0}$$$ $$$0$$$ $$$\underline{0}$$$ $$$\underline{1}$$$

const solve = (n,arr)=>{
     let res = [];
     for(let i=n-1;i>=0;i--){
          if(arr[i]===0){
               let j = 0,k=0;
               while((!arr[i])&& (i>j)){
                    if(arr[j]){
                         [arr[i],arr[j]] = [arr[j],arr[i]];
                         res.push(i+1);
                         res.push(j+1);
                         i--;
                    }
                    j++;
               }
          }
     }
     if(res.length===0) console.log(0);
     else{
     console.log(1);
     res.sort((a,b)=>a-b);
     console.log(`${res.length} ${res.join(" ")}`);
     }
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr =  readline().trim().split("").map(cur=>parseInt(cur));
       solve(n,arr);
  }
}
main();

//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 s = nextCharArray();
		var output = [];
		for(var i = 0; i < N; i++){
			if(s[i] == "1"){
				for(var j = N - 1; j >= i; j--){
					if(s[j] == "0"){
						output.push(i + 1);
						output.push(j + 1);
						s[i] = "-1";
						s[j] = "-1";
						break;
					}
				}
			}
		}
		if(output.length > 0){
			myout(1);
			output.sort(function(a,b){
				return a - b;
			});
			output.unshift(output.length);
			myout(myconv(output, 8));
		}else{
			myout(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 b = lines[i].split('').map(Number).sort(function(a, b){return a - b});
            var c = '', d = '';
            for(j = 0; j < n; j++){
                c += a[j];
                d += b[j];
            }
            if(c == d){
                console.log(0);
            }else{
                var ans = '';
                console.log(1);
                var v = [];
                for(j = 0; j < n; j++){
                    if(a[j] != b[j]){
                        v.push(j + 1);
                    }
                }
                ans += v.length + ' ';
                for(j = 0; j < v.length; j++){
                    ans += v[j] + ' ';
                }
                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++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const str = lines[l++]
        output[i] = solve(n, str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, str) {
    let c = 0
    for (let i = 0; i < str.length; i++) {
        if (str[i] === '0') c++
    }

    const ans = []
    for (let i = 0; i < str.length; i++) {
        if (i < c) {
            if (str[i] === '1') ans.push(i + 1)
        } else {
            if (str[i] === '0') ans.push(i + 1)
        }
    }
    if (!ans.length) return 0
    return `1\n${ans.length} ${ans.join(' ')}`
}

var t = parseInt(readline());

  function solve() {
    var n = parseInt(readline());
    var s = readline();
    var v = []
    var w = []
    var ans = [];
    var a = 0;
    var b = 0;
    for (var i = 0; i < n; i++) {
      if (s[i] == '1') {
        b++;
        v.push(i);
      } else {
        a++;
        w.push(i);
      }
    }

    for (var i = 0; i < v.length; i++) {
      if (v[i] < n - b) {
        ans.push(v[i]);
      }
    }
    for (var i = 0; i < w.length; i++) {
      if (w[i] > a - 1) {
        ans.push(w[i]);
      }
    }

    if (ans.length == 0)
      return "0";
    else {
      ans.sort((a, b) => {
        if (a > b) {
          return 1;
        } else if (a < b) {
          return -1;
        } else {
          return 0;
        }
      });
      var val1 = "1\n";
      var val2 = ans.length + " ";
      for (var i = 0; i < ans.length; i++) {
        val2 += ans[i] + 1 + " "
      }
      return val1 + val2
    }
  }

  while (t--) {
    print(solve())
  }

var t = parseInt(readline());

  function solve() {
    var n = parseInt(readline());
    var s = readline();
    var m = 0;
    var v = []
    var w = []
    var ans = [];
    var a = 0;
    var b = 0;
    for (var i = 0; i < n; i++) {
      if (s[i] == '1') {
        b++;
        v.push(i);
      }
    }
    for (var i = n - 1; i >= 0; i--) {
      if (s[i] == '0') {
        a++;
        w.push(i);
      }
    }
    for (var i = 0; i < v.length; i++) {
      if (v[i] < n - b) {
        m++;
        ans.push(v[i]);
      }
    }
    for (var i = 0; i < w.length; i++) {
      if (w[i] > a - 1) {
        m++;
        ans.push(w[i]);
      }
    }

    if (ans.length == 0)
      return "0";
    else {
      ans.sort((a, b) => {
        if (a > b) {
          return 1;
        } else if (a < b) {
          return -1;
        } else {
          return 0;
        }
      });
      var val1 = "1\n";
      var val2 = ans.length + " ";
      for (var i = 0; i < ans.length; i++) {
        val2 += ans[i] + 1 + " "
      }
      return val1 + val2
    }
  }

  while (t--) {
    print(solve())
  }

const solve = (n,arr)=>{
     let r = [];
     for(let i=n-1;i>=0;i--){
          if(arr[i]===0){
               let j = 0,res=[],k=0;
               while((!arr[i])&& (i>j)){
                    if(arr[j]){
                         [arr[i],arr[j]] = [arr[j],arr[i]];
                         res.push(i+1);
                         res.push(j+1);
                         i--;
                    }
                    j++;
               }
               if(res.length) {
                    res.sort((a,b)=>a-b);
                    r.push(`${res.length} ${res.join(" ")}`);
               }
          }
     }
     if(r.length===0) console.log(0);
     else{
          console.log(r.length);
          for(let i=0;i<r.length;i++) console.log(r[i]);
     }
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for(let i=0;i<t;i++){
       let n = parseInt(readline());
       let arr =  readline().trim().split("").map(cur=>parseInt(cur));
       solve(n,arr);
  }
}
main();

//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 s = nextCharArray();
		var output = [];
		while(true){
			var zero = [];
			var one = [];
			var change = [];
			for(var i = N - 1; i >= 0; i--){
				if(s[i] == "0" && one.length == 0){
					zero.unshift(i);
					change.unshift(i);
				}else if(s[i] == "1" && zero.length > 0){
					one.unshift(i);
					change.unshift(i);
				}
			}
			if(zero.length > 0 && one.length > 0){
				var size = change.length;
				for(var i = 0; i < Math.floor(change.length / 2); i++){
					var tmp = s[change[i]];
					s[change[i]] = s[change[change.length - 1 - i]];
					s[change[change.length - 1 - i]] = tmp;
				}
				for(var i = 0; i < change.length; i++){
					change[i]++;
				}
				output.push(size + " " + myconv(change, 8));
			}else{
				break;
			}
		}
		myout(output.length);
		if(output.length > 0){
			myout(myconv(output, 9));
		}

	}
}