import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto l = RD;
		auto r = RD;
		auto k = RD;
		auto a = RDA;

		a.sort;
		foreach (i; 0..n)
		{
			if (a[i] < l || a[i] > r) continue;
			if (k < a[i]) break;
			k -= a[i];
			++ans[ti];
		}
	}

	foreach (e; ans)
		writeln(e);
	stdout.flush;
	debug readln;
}

// Cheese-Cracker: cheese-cracker.github.io

void solve(){
    long n = scan;
    long l = scan;
    long r = scan;
    long k = scan;
    auto arr = scanArray;
    arr.sort;
    long cnt = 0;
    for(int i = 0; i < n; ++i){
        if(arr[i] >= l && arr[i] <= r){
            if(k >= arr[i]){
                ++cnt;
                k -= arr[i];
            }
        }
    }
    writeln(cnt);
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/**************    *****    That's All Folks!    *****    **************/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math;
string[] tk; T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long, tup = Tuple!(long, "x",  long, "y");

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto l = readInt!int;
	auto r = readInt!int;
	auto k = readInt!int;
	auto a = ma(n, readInt!int);
	a = a.filter!(ai => ai >= l && ai <= r).array;
	sort(a);
	debug writeln("after filter ", a);
	int count = 0;
	while (!a.empty && k >= a.front)
	{
		count++;
		k -= a.front;
		a.popFront;
	}
	count.writeln;
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
	{
		popChar;
	}
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}


//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.format;

void test (string s) {
  if (s.all!"a=='0'" || s.all!"a == '1'") {
    writeln (s);
    return;
  }
  foreach (i; 0 .. s.length) {
    write ("01");
  }
  writeln;
}

void main() {
  auto s = readln;
  int nt;
  formattedRead (s, " %d", nt);
  foreach (tid; 0 .. nt) {
    s = readln.stripRight;
    test (s);
  }
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto T = RD!int;
	auto ans = new string[](T);
	foreach (ti; 0..T)
	{
		auto t = RD!string;
		bool[char] set;
		foreach (c; t)
		{
			set[c] = true;
		}
		if (set.keys.length == 1)
		{
			ans[ti] = t;
		}
		else
		{
			char last;
			foreach (i; 0..t.length)
			{
				if (t[i] == last)
				{
					if (t[i] == '0')
						ans[ti] ~= "10";
					else
						ans[ti] ~= "01";
				}
				else
				{
					ans[ti] ~= t[i];
				}
				last = t[i];
			}
		}
	}

	foreach (e; ans)
		writeln(e);
	stdout.flush;
	debug readln;
}

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm, std.array, std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
int inz(long t){ return to!int(t); }
static string[] tempstr;
T rd(T = long)() { while(!tempstr.length) tempstr = readln.chomp.split; string res = tempstr[0]; tempstr.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void play(){
    char[] s;
    s = rd!(char[]);
    int[] nums;
    int[int] seen;
    seen[0] = 0; seen[1] = 0;
    foreach(cr; s){
        nums ~= cr - '0';
        ++seen[cr - '0'];
    }
    if(!(seen[0] && seen[1])){
        writeln(s);
    }else{
        int[] res;
        res ~= nums[0];
        foreach(i; 1..nums.length){
            if(nums[i] == nums[i-1]){
                res ~= !nums[i];
            }
            res ~= nums[i];
        }
        foreach(cr; res){
            write(cr);
        }
        writeln;
    }
}

int main(){
    ll t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto t = readln.chomp;
        int o, z;
        foreach (c; t) {
            if (c == '0') ++z;
            if (c == '1') ++o;
        }
        if (o == 0 || z == 0) {
            writeln(t);
            continue;
        }

        char[] s;
        foreach (i; 0..t.length-1) {
            s ~= t[i];
            if (t[i] == t[i+1]) {
                if (t[i] == '0') {
                    s ~= '1';
                } else {
                    s ~= '0';
                }
            }
        }
        s ~= t[$-1];
        writeln(s);
    }
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		auto n = s.length;
		string res;
		foreach (char part; "01")
		{
			if (s.canFind (part))
			{
				res ~= part;
			}
		}
		writeln (res.repeat (n).joiner);
	}
}


import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

bool read(T...)(T ptrs) if (ptrs.length > 0) {
    return readf(' ' ~ replicate("%s ", ptrs.length), ptrs) == ptrs.length;
}

int n, k;
char[ ] s;

int solve(char c) {
    int a = 0, b = 0;
    int left = k;
    for (; b < n; b++)
        if (s[b] != c && !left--)
            break;
    int result = b - a;
    while (b < n) {
        while (a != b && s[a] == c)
            a++;
        a++;
        while (++b < n)
            if (s[b] != c)
                break;
        result = max(result, b - a);
    }
    return result;
}

void main() {
    static char[100_001] storage;
    while (read(&n, &k)) {
        s = storage[ ];
        readln(s);
        writeln(max(solve('a'), solve('b')));
    }
}

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio, std.bitmanip;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto S = readln.chomp.to!string;

    auto ac = new int[](N+1);
    auto bc = new int[](N+1);
    foreach (i; 1..N+1) {
        ac[i] = ac[i-1] + (S[i-1] == 'a');
        bc[i] = bc[i-1] + (S[i-1] == 'b');
    }

    int ans = 0;
    int r = 0;
    foreach (l; 0..N) {
        while (r < N-1 && bc[r+2] - bc[l] <= K)
            r++;
        ans = max(ans, r-l+1);
    }
    r = 0;
    foreach (l; 0..N) {
        while (r < N-1 && ac[r+2] - ac[l] <= K)
            r++;
        ans = max(ans, r-l+1);
    }

    writeln(ans);
}


import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int a, b;
		readf !(" %s %s") (a, b);
		int res = int.max;
		for (int step = 0; step <= 100; step++)
		{
			int num = step;
			int c = a;
			int d = b + step;
			if (d == 1)
			{
				continue;
			}
			while (c > 0)
			{
				c /= d;
				num += 1;
			}
			res = min (res, num);
		}
		writeln (res);
	}
}

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric, std.container, std.range;

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T);
    while (T--) {
        int a, b; get(a, b);
        int base;
        if (b == 1) {
            b = 2;
            base = 1;
        }

        auto r = int.max;
        for (;;) {
            int res = base;
            auto aa = a;
            while (aa) {
                aa /= b;
                res += 1;
            }
            if (res <= r) {
                r = res;
                b += 1;
                base += 1;
            } else {
                break;
            }
        }
        writeln(r);
    }
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto a = RD;
		auto b = RD;

		long bb;
		if (b == 1)
		{
			++bb;
		}

		ans[ti] = long.max;
		while (true)
		{
			long tmp;
			auto x = a;
			auto y = b + bb;
			while (x)
			{
				x /= y;
				++tmp;
			}
			tmp += bb;
			if (tmp <= ans[ti])
				ans[ti] = tmp;
			else
				break;
			++bb;
		}
	}

	foreach (e; ans)
		writeln(e);
	stdout.flush;
	debug readln;
}


import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.string;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    A.sort();
    long ans = 0;

    for (int i = 0, j = 0; i < N; ++i) {
        if (j < i) j = i;
        while (j < N && A[j] - A[i] <= 5) ++j;
        ans = max(ans, j - i);
    }

    ans.writeln;
}

import std.algorithm;
import std.container;
import std.conv;
import std.format;
import std.range;
import std.stdio;
import std.string;

void main() {
    int n;
    readf!" %s"(n);

    int[] a = new int[](n);
    foreach (i; 0 .. n) {
        readf!" %s"(a[i]);
    }

    a.sort;

    debug {
        writeln(a);
    }

    int ans = 0;
    int l = 0, r = 0;
    for (; l < n; l++) {
        while (r < n && a[r] - a[l] <= 5) {
            r++;
        }
        ans = max(ans, r - l);
    }

    writeln(ans);
}

import std.functional,
       std.algorithm,
       std.container,
       std.typetuple,
       std.typecons,
       std.bigint,
       std.string,
       std.traits,
       std.array,
       std.range,
       std.stdio,
       std.conv;

bool chmax(t)(ref t a, t b) {
  if (a < b) {
    a = b;
    return true;
  } else {
    return false;
  }
}

void main() {
  int n = readln.chomp.to!int;
  int[] ns = readln.chomp.split.to!(int[]);
  sort!"a>b"(ns);
  int[int] hs;

  foreach (e; ns) {
    if (e in hs) {
      hs[e]++;
    } else {
      hs[e] = 1;
    }
  }

  int ans = 0;
  int len;

  foreach (e; ns) {
    foreach (i; 0..6) {
      if ((e - i) in hs) {
        len += hs[e - i];
      }
    }

    chmax(ans, len);
    len = 0;
  }

  writeln(ans);
}


//prewritten code: https://github.com/antma/algo
module Solution;
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.typecons;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

//Kadane's algorithm
long maximumSubArraySum(R) (R range) if (isInputRange!R && isIntegral!(ElementType!R)) {
  alias T = ElementType!R;
  alias S = Tuple! (long, "best", long, "cur");
  S next (in S s, in T x) {
    S t;
    t.cur = s.cur + x;
    t.best = max (s.best, t.cur);
    if (t.cur < 0) t.cur = 0;
    return t;
  }
  return reduce!next (tuple!("best", "cur") (long.min, 0L), range).best;
}

bool test (in long[] a) {
  long y = sum (a);
  long b = max (maximumSubArraySum (a[1 .. $]), maximumSubArraySum (a[0 .. $ - 1]));
  return y > b;
}

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint ();
    auto a = r.nextA!(long)(n);
    debug stderr.writeln (a);
    auto b = a.dup;
    b.reverse ();
    writeln ((test (a) && test (b)) ? "YES" : "NO");
  }
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.typecons;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

//Kadane's algorithm
long maximumSubArraySum(R) (R range) if (isInputRange!R && isIntegral!(ElementType!R)) {
  alias T = ElementType!R;
  alias S = Tuple! (long, "best", long, "cur");
  S next (in S s, in T x) {
    S t;
    t.cur = s.cur + x;
    t.best = max (s.best, t.cur);
    if (t.cur < 0) t.cur = 0;
    return t;
  }
  return reduce!next (tuple!("best", "cur") (long.min, 0L), range).best;
}

bool test (in long[] a) {
  long y = sum (a);
  long best = y;
  long cur = 0;
  int l = 0;
  foreach (x; a) {
    cur += x;
    ++l;
    if (best <= cur && l < a.length) {
      return false;
    }
    if (cur < 0) {
      cur = 0;
      l = 0;
    }
  }
  return true;
}

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint ();
    auto a = r.nextA!(long)(n);
    debug stderr.writeln (a);
    auto b = a.dup;
    b.reverse ();
    writeln ((test (a) && test (b)) ? "YES" : "NO");
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	foreach(_; 0 .. rint){
		int n = rint;
		long[] as = rlong(n);

		long inf = 1_00000_000_000_000 + 999;

		long x = as.sum;
		long y = -inf;
		long tmp;
		foreach(a; as[0 .. $ - 1]){
			if(tmp + a > 0) tmp += a, y.chmax(tmp);
			else tmp = 0;
		}
		tmp = 0;
		foreach(a; as[1 .. $]){
			if(tmp + a > 0) tmp += a, y.chmax(tmp);
			else tmp = 0;
		}
		foreach(a; as) y.chmax(a);
		log("x:", x, "y:", y);

		if(x > y) "YES".writeln;
		else "NO".writeln;

	}

}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value = E.init)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

void main()
{
  int t;
  read(t);
  foreach(tc; 0 .. t)
    {
      long n;
      read(n);
      auto a = makeArray!long(n, next!long);
      long bestsum = 0;
      long totalbest = long.min;
      foreach(i; 0 .. n - 1)
        {
          bestsum = max(a[i.ind] + bestsum, a[i.ind]);
          totalbest = max(bestsum, totalbest);
        }
      long suffixsum = 0;
      long maxsuffixsum = long.min;
      foreach_reverse(i; 1 .. n)
        {
          suffixsum += a[i.ind];
          totalbest = max(suffixsum, totalbest);
        }
      writeln(a[].sum > totalbest? "YES" : "NO");
    }
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto x = a.sum;
		auto b = new long[](n+1);
		foreach (i; 0..n)
		{
			b[i+1] = b[i] + a[i];
		}
		long y = long.min;
		int l;
		foreach (r; 1..n+1)
		{
			if (l == 0 && r == n)
			{
				foreach (i; 2..n+1)
					y.chmax(b[i] - b[1]);
				break;
			}
			auto tmp = b[r] - b[l];
			if (tmp <= 0)
			{
				l = r;
			}
			y.chmax(tmp);
		}
		ans[ti] = x > y;
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush;
	debug readln;
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.typecons;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

//Kadane's algorithm
long maximumSubArraySum(R) (R range) if (isInputRange!R && isIntegral!(ElementType!R)) {
  alias T = ElementType!R;
  alias S = Tuple! (long, "best", long, "cur");
  S next (in S s, in T x) {
    S t;
    t.cur = s.cur + x;
    t.best = max (s.best, t.cur);
    if (t.cur < 0) t.cur = 0;
    return t;
  }
  return reduce!next (tuple!("best", "cur") (long.min, 0L), range).best;
}

bool test (in long[] a) {
  long y = sum (a);
  long best = y;
  long cur = 0;
  int l = 0;
  foreach (x; a) {
    cur += x;
    ++l;
    if (best <= cur && l < a.length) {
      return false;
    }
    if (cur < 0) {
      cur = 0;
      l = 0;
    }
  }
  return true;
}

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint ();
    auto a = r.nextA!(long)(n);
    debug stderr.writeln (a);
    writeln (test (a) ? "YES" : "NO");
  }
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value = E.init)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

void main()
{
  int t;
  read(t);
  foreach(tc; 0 .. t)
    {
      int n;
      read(n);
      auto a = makeArray!int(n, next!int);
      int bestsum = 0;
      int totalbest = int.min;
      int totalbesti = -1;
      foreach(i; 0 .. n - 1)
        {
          bestsum = max(a[i] + bestsum, a[i]);
          if (bestsum > totalbest)
            {
              totalbest = bestsum;
            }
        }
      int suffixsum = 0;
      int maxsuffixsum = int.min;
      foreach_reverse(i; 1 .. n)
        {
          suffixsum += a[i];
          maxsuffixsum = max(suffixsum, maxsuffixsum);
        }
      totalbest = max(totalbest, maxsuffixsum);
      writeln(a[].sum > totalbest? "YES" : "NO");
    }
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;

DList!string _words;

void read(T...)(ref T t)
{
  void singleRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  static foreach(i; 0 .. T.length)
    {
      static if (is(typeof({foreach(ref e; t[i]){}})) && !is(T[i] == string))
        {
          foreach(ref element; t[i])
            read(element);
        }
      else
        {
          singleRead(t[i]);
        }
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value = E.init)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

void main()
{
  int t;
  read(t);
  foreach(tc; 0 .. t)
    {
      int n;
      read(n);
      auto a = makeArray!int(n, next!int);
      int bestsum = 0;
      int totalbest = int.min;
      foreach(i; 0 .. n - 1)
        {
          bestsum = max(a[i] + bestsum, a[i]);
          totalbest = max(bestsum, totalbest);
        }
      int suffixsum = 0;
      int maxsuffixsum = int.min;
      foreach_reverse(i; 1 .. n)
        {
          suffixsum += a[i];
          totalbest = max(suffixsum, totalbest);
        }
      writeln(a[].sum > totalbest? "YES" : "NO");
    }
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto x = a.sum;
		auto b = new long[](n+1);
		foreach (i; 0..n)
		{
			b[i+1] = b[i] + a[i];
		}
		long y;
		int l;
		foreach (r; 1..n+1)
		{
			if (l == 0 && r == n) break;
			auto tmp = b[r] - b[l];
			if (tmp < 0)
			{
				l = r+1;
			}
			y.chmax(tmp);
		}
		ans[ti] = x > y;
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush;
	debug readln;
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto x = a.sum;
		auto b = new long[](n+1);
		foreach (i; 0..n)
		{
			b[i+1] = b[i] + a[i];
		}
		long y = long.min;
		int l;
		foreach (r; 1..n+1)
		{
			if (l == 0 && r == n) break;
			auto tmp = b[r] - b[l];
			if (tmp < 0)
			{
				l = r+1;
			}
			y.chmax(tmp);
		}
		ans[ti] = x > y;
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush;
	debug readln;
}


import std;

// From: https://rosettacode.org/wiki/Prime_decomposition#D
Unqual!T[] decompose(T)(in T number)
{
    typeof(return) result;
    Unqual!T n = number;

    for (Unqual!T i = 2; n % i == 0; n /= i)
        result ~= i;
    for (Unqual!T i = 3; n >= i * i; i += 2)
        for (; n % i == 0; n /= i)
            result ~= i;

    if (n != 1)
        result ~= n;
    return result;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long n, m;
    readf!" %d %d "(n, m);
    auto tmp = decompose(n);
    auto cnt2 = tmp.count(2);
    auto cnt5 = tmp.count(5);
    long xm = 1;
    if (cnt2 < cnt5) {
      while (cnt2 < cnt5 && xm * 2 <= m) {
        cnt2++;
        xm *= 2;
      }
      while (xm * 10 <= m) {
        xm *= 10;
      }
      if (m / xm > 0)
        xm *= m / xm;
    } else {
      while (cnt5 < cnt2 && xm * 5 <= m) {
        cnt5++;
        xm *= 5;
      }
      while (xm * 10 <= m) {
        xm *= 10;
      }
      if (m / xm > 0)
        xm *= m / xm;
    }
    writeln(xm == 1 ? n * m : n * xm);
  }
}

import std.algorithm;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

int zeroes (long n)
{
	int res = 0;
	while (n % 10 == 0)
	{
		res += 1;
		n /= 10;
	}
	return res;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		long n, m;
		readf !(" %s %s") (n, m);

		foreach (c; [2, 5, 10])
		{
			while (c <= m && zeroes (n) < zeroes (n * c))
			{
				n *= c;
				m /= c;
			}
		}
		writeln (n * m);
	}
}


import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

void main()
{
    int n;
    readf("%s", &n);
    readln;

    immutable int MX = 2750131;
    auto div = new int[] (MX + 1);
    div[] = 1;
    int nxtIdx = 1;
    int[int] prsIdx;

    foreach (i; 2 .. MX + 1) {
        if (div[i] != 1) { continue; }

        foreach (j; (MX+1).iota.drop(i+i).stride(i)) {
            if (div[j] == 1) { div[j] = i; }
        }

        prsIdx[i] = nxtIdx;
        nxtIdx += 1;
    }

    auto arr = readln.chomp.split.map!(to!int).array;

    auto rbt = make!(RedBlackTree!(int, "a > b", true))(arr);

    int[] ans;
    while (!rbt.empty()) {
        auto x = rbt.front();
        rbt.removeFront();

        if (x in prsIdx) {
            auto v = prsIdx[x];
            rbt.removeKey(v);
            ans ~= v;
        } else {
            auto v = x / div[x];
            rbt.removeKey(v);
            ans ~= x;
        }
    }

    ans.map!(to!string).join(" ").writeln;
}

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

void main()
{
    int n;
    readf("%s", &n);
    readln;

    immutable int MX = 2750131;
    auto div = new int[] (MX + 1);
    div[] = 1;
    int[] prs;
    int[int] prsIdx;

    foreach (i; 2 .. MX + 1) {
        if (div[i] != 1) { continue; }

        foreach (j; (MX+1).iota.drop(i+i).stride(i)) {
            if (div[j] == 1) { div[j] = i; }
        }

        prs ~= i;
        prsIdx[i] = prs.length.to!int;
    }

    auto arr = readln.chomp.split.map!(to!int).array;

    auto rbt = make!(RedBlackTree!(int, "a > b", true))(arr);

    int[] ans;
    while (!rbt.empty()) {
        auto x = rbt.front();
        rbt.removeFront();

        if (x in prsIdx) {
            auto v = prsIdx[x];
            rbt.removeKey(v);
            ans ~= v;
        } else {
            auto v = x / div[x];
            rbt.removeKey(v);
            ans ~= x;
        }
    }

    ans.map!(to!string).join(" ").writeln;
}


import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.numeric;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import core.bitop;

immutable int INF = int.max / 2;
immutable int NA = -1;

bool solve (int [] [] a)
{
    int n = a.length;
    foreach (i, c; a)
    {
        foreach (j, x; c)
        {
            if ((x == 0) != (i == j) || x != a[j][i])
            {
                return false;
            }
        }
    }

    auto d = new int [n];
    d[] = INF;
    auto p = new int [n];
    p[] = NA;
    auto b = new bool [n];
    alias edge = Tuple !(int, "v", int, "w");
    auto g = new edge [] [n];
    int cur = 0;
    foreach (k; 1..n)
    {
        b[cur] = true;
        foreach (i; 0..n)
        {
            if (d[i] > a[cur][i])
            {
                d[i] = a[cur][i];
                p[i] = cur;
            }
        }
        int next = cur;
        int w = INF;
        foreach (i; 0..n)
        {
            if (!b[i])
            {
                if (w > d[i])
                {
                    w = d[i];
                    next = i;
                }
            }
        }
        g[next] ~= edge (p[next], w);
        g[p[next]] ~= edge (next, w);
        cur = next;
    }
    debug {writeln (g);}

    foreach (i; 0..n)
    {
        auto e = new long [n];

        void recur (int v, int q, long z)
        {
            e[v] = z;
            foreach (h; g[v])
            {
                if (h.v != q)
                {
                    recur (h.v, v, z + h.w);
                }
            }
        }

        recur (i, NA, 0);
        debug {writeln (e[], ' ', a[i][]);}
        if (e[] != a[i][])
        {
            return false;
        }
    }
    return true;
}

void main ()
{
    int n;
    while (readf (" %s", &n) > 0)
    {
        auto a = new int [] [] (n, n);
        foreach (ref c; a)
        {
            foreach (ref x; c)
            {
                readf (" %s", &x);
            }
        }
        writeln (solve (a) ? "YES" : "NO");
    }
}

import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.numeric;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import core.bitop;

immutable int INF = int.max / 2;
immutable int NA = -1;

bool solve (int [] [] a)
{
	int n = a.length;
	foreach (i, c; a)
	{
		foreach (j, x; c)
		{
			if ((x == 0) != (i == j) || x != a[j][i])
			{
				return false;
			}
		}
	}

	auto d = new int [n];
	d[] = INF;
	auto p = new int [n];
	p[] = NA;
	auto b = new bool [n];
	alias edge = Tuple !(int, "v", int, "w");
	auto g = new edge [] [n];
	int cur = 0;
	foreach (k; 1..n)
	{
		b[cur] = true;
		foreach (i; 0..n)
		{
			if (d[i] > a[cur][i])
			{
				d[i] = a[cur][i];
				p[i] = cur;
			}
		}
		int next = cur;
		int w = INF;
		foreach (i; 0..n)
		{
			if (!b[i])
			{
				if (w > d[i])
				{
					w = d[i];
					next = i;
				}
			}
		}
		g[next] ~= edge (p[next], w);
		g[p[next]] ~= edge (next, w);
		cur = next;
	}
	debug {writeln (g);}

	foreach (i; 0..n)
	{
		auto e = new long [n];

		void recur (int v, int q, long z)
		{
			e[v] = z;
			foreach (h; g[v])
			{
				if (h.v != q)
				{
					recur (h.v, v, z + h.w);
				}
			}
		}

		recur (i, NA, 0);
		debug {writeln (e[], ' ', a[i][]);}
		if (e[] != a[i][])
		{
			return false;
		}
	}
	return true;
}

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto a = new int [] [] (n, n);
		foreach (ref c; a)
		{
			auto r = readln.split ();
			foreach (ref x; c)
			{
				x = to !(int) (r.front);
				r.popFront ();
//				readf (" %s", &x);
			}
		}
		writeln (solve (a) ? "YES" : "NO");
	}
}

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.range, std.regex;

//	Input
class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { tokens = readln.split; if (stdin.eof) throw new EOFException; } auto token = tokens[0]; tokens.popFront; return token; }
int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

//	chmin/chmax
void chmin(T)(ref T t, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int N;
long[][] D;

Pair!(long, Pair!(int, int))[] edges;

void doIt(int[] us) {
debug{
writeln("doIt ",us);
}
	if (us.length <= 1) {
		return;
	}
	int a = us[0];
	int b = -1;
	foreach (u; us[1 .. $]) {
		if (b == -1 || D[a][b] > D[a][u]) {
			b = u;
		}
	}
	edges ~= pair(D[a][b], pair(a, b));
	int[] usA, usB;
	foreach (u; us) {
		if (D[a][u] < D[b][u]) {
			usA ~= u;
		} else {
			usB ~= u;
		}
	}
	if (usA.empty || usB.empty) {
		return;
	}
	usA.doIt;
	usB.doIt;
}

bool solve() {
	foreach (u; 0 .. N) {
		if (D[u][u] != 0) {
			return false;
		}
	}
	foreach (u; 0 .. N) foreach (v; 0 .. N) {
		if (D[u][v] != D[v][u]) {
			return false;
		}
	}

	edges = new Pair!(long, Pair!(int, int))[0];
	int[] us = new int[N];
	foreach (u; 0 .. N) {
		us[u] = u;
	}
	us.doIt;
debug{
writeln(edges);
}
	if (edges.length != N - 1) {
		return false;
	}
	foreach (edge; edges) {
		if (edge.x <= 0) {
			return false;
		}
	}
	auto G = new Pair!(long, int)[][N];
	foreach (edge; edges) {
		G[edge.y.x] ~= pair(edge.x, edge.y.y);
		G[edge.y.y] ~= pair(edge.x, edge.y.x);
	}
	foreach (s; 0 .. N) {
		long[] ds = new long[N];
		void dfs(int u, int p, long d) {
			ds[u] = d;
			foreach (inci; G[u]) {
				const v = inci.y;
				if (v != p) {
					dfs(v, u, d + inci.x);
				}
			}
		}
		dfs(s, -1, 0);
debug{
writeln(s," : ",ds);
}
		foreach (u; 0 .. N) {
			if (D[s][u] != ds[u]) {
				return false;
			}
		}
	}
	return true;
}

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		D = new long[][](N, N);
		foreach (u; 0 .. N) foreach (v; 0 .. N) {
			D[u][v] = readLong;
		}

		writeln(solve ? "YES" : "NO");
	}
	} catch (EOFException) {}
}


void main() {
  import std.stdio, std.string, std.conv, std.algorithm;

  int n, r;
  rd(n, r);
  auto as = readln.split.to!(int[]);

  auto bs = new int[](n);
  foreach (int i, a; as) {
    if (a) {
      foreach (int j; max(0, i - r + 1) .. min(n, i + r)) {
        bs[j]++;
      }
    }
  }
  if (bs.find(0).length > 0) {
    writeln(-1);
    return;
  }
  int num = reduce!"a+b"(as);
  foreach (int i, b; bs) {
    if (as[i]) {
      if (b >= 2) {
        bool ok = true;
        foreach (int j; max(0, i - r + 1) .. min(n, i + r)) {
          ok &= bs[j] >= 2;
        }
        if (ok) {
          num--;
          foreach (int j; max(0, i - r + 1) .. min(n, i + r)) {
            bs[j]--;
          }
        }
      }
    }
  }
  writeln(num);
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}

import std.stdio, std.string, std.conv;
import std.range, std.algorithm, std.array, std.typecons, std.container;
import std.math, std.numeric, core.bitop;

enum inf = 10^^6;

void main() {
    int n, r;
    scan(n, r);
    auto a = readln.split.to!(int[]);
    a = a ~ repeat(0, r).array;

    int lt = -1;
    auto b = new int[](n + r);
    foreach (i ; 0 .. r) {
        if (a[i]) {
            lt = i;
        }
    }
    foreach (i ; r .. n + r) {
        b[i - r] = lt;
        if (lt == i - r) {
            lt = -1;
        }
        if (a[i]) {
            lt = i;
        }
    }

    auto c = new int[](n);
    c[0] = a[0] ? 0 : inf + 1;
    foreach (i ; 1 .. n) {
        if (a[i] == 1) {
            c[i] = 0;
        }
        else {
            c[i] = c[i-1] + 1;
        }
    }

    debug {
        writeln(b);
        writeln(c);
    }

    int ans;

    for (int pos; pos < n;) {
        ans++;
        if (b[pos] != -1) {
            pos = b[pos] + r;
        }
        else if (c[pos] < r) {
            pos = pos - c[pos] + r;
        }
        else {
            writeln(-1);
            return;
        }
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

void main() {
  import std.stdio, std.string, std.conv, std.algorithm;

  int n, r;
  rd(n, r);
  auto as = readln.split.to!(int[]);

  auto bs = new int[](n);
  int num = 0;
  foreach (int i, b; bs) {
    if (b == 0) {
      num++;
      bool found = false;
      foreach (int j; i .. n) {
        if (as[j]) {
          found = true;
          for (int k = max(0, j - r + 1); k < min(n, j + r - 1); k++) {
            bs[k] = 1;
          }
          break;
        }
      }
      if (!found) {
        writeln(-1);
        return;
      }
    }
  }

  writeln(num);
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}

void main() {
  import std.stdio, std.string, std.conv, std.algorithm;

  int n, r;
  rd(n, r);
  auto as = readln.split.to!(int[]);

  auto bs = new int[](n);
  int num = 0;
  foreach (int i, b; bs) {
    if (b == 0) {
      num++;
      bool found = false;
      int idx;
      foreach (int j; i .. n) {
        if (as[j]) {
          if (i < j - r + 1) {
            break;
          }
          found = true;
          idx = j;
        }
      }
      if (!found) {
        writeln(-1);
        return;
      }
      for (int k = max(0, idx - r + 1); k < min(n, idx + r); k++) {
        bs[k] = 1;
      }
    }
  }

  writeln(num);
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}


import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    int n, k;
    readf("%s %s", &n, &k);
    readln;

    auto g = new int[][] (n+1);
    foreach (_ ; 0 .. n-1) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        g[u] ~= v;
        g[v] ~= u;
    }

    auto d = new int[][] (n+1, k+1);

    long dfs(int v, int fr) {
        long ret = 0;
        foreach (u; g[v]) {
            if (u == fr) continue;

            ret += dfs(u, v);
            foreach (le; 1 .. k) {
                ret += d[v][le].to!long * d[u][k - le - 1];
            }
            foreach (le; 1 .. k+1) {
                d[v][le] += d[u][le-1];
            }
        }

        ret += d[v][k];
        d[v][0] += 1;

        debug { writeln(v, ' ', d[v], ' ', ret); }

        return ret;
    }

    auto ans = dfs(1, -1);

    ans.writeln;
}

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    int n, k;
    readf("%s %s", &n, &k);
    readln;

    auto g = new int[][] (n+1);
    foreach (_ ; 0 .. n-1) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        g[u] ~= v;
        g[v] ~= u;
    }

    auto mxh = new int[] (n+1);
    int dfsmxh(int v, int fr) {
        int h = 0;
        foreach (u; g[v]) {
            if (u == fr) continue;
            h = max(h, dfsmxh(u, v) + 1);
        }

        return mxh[v] = h;
    }

    dfsmxh(1, -1);
    foreach (ref r; g) {
        r = r.sort!((a, b) => mxh[a] < mxh[b]).array;
    }

    long dfs(int v, int fr, int h, ref int[int] cnt) {
        long ret = 0;

        while (! g[v].empty() && g[v].back == fr) { g[v].popBack(); }

        int[int] ncnt;
        if (! g[v].empty()) {
            ret += dfs(g[v].back, v, h+1, cnt);

            foreach (u; g[v][0 .. $-1]) {
                if (u == fr) continue;

                ncnt.clear();
                ret += dfs(u, v, h+1, ncnt);
                foreach (le; 1 .. k) {
                    debug { writeln("mid ", v, ' ' , u,  ' ', cnt, ' ', ncnt, ' ', h); }
                    ret += cnt.get(h + le, 0).to!long * ncnt.get(h + k - le, 0);
                }

                foreach (d; 1 .. k+1) {
                    if (! ncnt.get(h + d, 0) == 0) {
                        cnt[h + d] += ncnt.get(h + d, 0);
                    }
                }
            }

            debug { writeln("start ", v, ' ', h+k,  ' ', cnt.get(h + k, 0)); }
            ret += cnt.get(h + k, 0);
        }

        cnt[h] += 1;

        debug { writeln("ret ", v, ' ', ret); }

        return ret;
    }

    int[int] cnt;
    auto ans = dfs(1, -1, 0, cnt);

    ans.writeln;
}


import std.stdio;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;
import core.bitop;
import core.stdc.stdio : scanf;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

int[][] scc(in int[][] G, in int[][] rG) {
    // calculate scc
    int N = cast(int)(G.length);
    auto used = new bool[N];
    int[] postorder;
    void vis_forward(int v) {
        used[v] = true;
        foreach (u; G[v]) {
            if (used[u]) continue;
            vis_forward(u);
        }
        postorder ~= v;
    }
    for (int v = 0; v < N; v++) {
        if (used[v]) continue;
        vis_forward(v);
    }
    auto cid = new int[N]; cid[] = -1; // i = cid[v]: vertex `v` belongs to the `i`-th component
    void vis_backward(int v, int k) {
        cid[v] = k;
        foreach (u; rG[v]) {
            if (cid[u] >= 0) continue;
            vis_backward(u, k);
        }
    }
    int k = 0;
    foreach_reverse (v; postorder) {
        if (cid[v] >= 0) continue;
        vis_backward(v, k++);
    }
    auto ret = new int[][k];
    foreach (v; 0 .. N) {
        ret[ cid[v] ] ~= v;
    }
    return ret;
}

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

alias Edge = Tuple!(int, "to", int, "cost");

void solve() {
    int N = read!int;
    auto xG = new int[][N];
    auto rG = new int[][N];
    auto G = new Edge[][N];
    foreach (i; 0 .. N) {
        auto rs = readarray!int[1 .. $];
        foreach (r; rs) {
            int j = r - 1;
            xG[i] ~= j;
            rG[j] ~= i;
            if (j < i) {
                G[i] ~= Edge(j, 0);
            } else {
                G[i] ~= Edge(j, 1);
            }
        }
    }
    auto grs = scc(xG, rG);
    if (grs.length == xG.length) {
        // ok. there's no scc
        auto ord = new int[N]; ord[] = -1;
        int f(int v) {
            if (ord[v] >= 0) return ord[v];
            int ret = 0;
            foreach (e; G[v]) {
                int x = e.cost + f(e.to);
                ret.chmax(x);
            }
            return ord[v] = ret;
        }
        int ans = 0;
        for (int v = 0; v < N; v++) {
            ans.chmax(f(v));
        }
        writeln(ans + 1);
    } else {
        writeln(-1);
    }
}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto requires = new int[][](n);
	auto requiredBy = new int[][](n);
	auto requirements = new int[](n);
	auto understandable = redBlackTree!int;
	auto processed = new bool[](n);
	int size = n;
	foreach(i; 0 .. n)
	{
		auto k = readInt!int;
		requires[i] = ma(k, readInt!int - 1);
		requirements[i] = cast(int)requires[i].length;
		foreach(j; requires[i])
			requiredBy[j] ~= i;
		if (requires[i].length == 0)
		{
			understandable.insert(i);
		}
	}
	int passes = 0;
	while (!understandable.empty)
	{
		passes++;
		auto range = understandable.upperBound(-1);
		while (!range.empty)
		{
			auto current = range.front;
			understandable.removeKey(current);
			processed[current] = true;
			foreach(dependents; requiredBy[current])
			{
				requirements[dependents]--;
				assert(requirements[dependents] >= 0);
				if (requirements[dependents] == 0)
				{
					understandable.insert(dependents);
				}
			}
			range = understandable.upperBound(current);
		}
	}
	bool remain = false;
	foreach(ins;processed) if (!ins) remain = true;
	if (remain)
	{
		writeln(-1);
	}
	else
	{
		writeln(passes);
	}
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
	{
		popChar;
	}
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

int N;
int[] K;
int[][] A;

int[] vis;
int[] dp;

bool dfs(int u) {
  vis[u] = 1;
  dp[u] = 1;
  foreach (v; A[u]) {
    if (vis[v] == 0) {
      if (!dfs(v)) {
        return false;
      }
    } else if (vis[v] == 1) {
      return false;
    }
    chmax(dp[u], ((u < v) ? 1 : 0) + dp[v]);
  }
  vis[u] = 2;
  return true;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        N = readInt();
        K = new int[N];
        A = new int[][N];
        foreach (u; 0 .. N) {
          K[u] = readInt();
          A[u] = new int[K[u]];
          foreach (k; 0 .. K[u]) {
            A[u][k] = readInt() - 1;
          }
        }

        vis = new int[N];
        dp = new int[N];
        bool ok = true;
        foreach (u; 0 .. N) {
          if (vis[u] == 0) {
            if (!dfs(u)) {
              ok = false;
              break;
            }
          }
        }

        int ans;
        if (ok) {
          ans = dp.maxElement;
        } else {
          ans = -1;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto requires = new int[][](n);
	auto requiredBy = new int[][](n);
	auto requirements = new int[](n);
	auto understandable = redBlackTree!int;
	auto processed = new bool[](n);
	int size = n;
	foreach(i; 0 .. n)
	{
		auto k = readInt!int;
		requires[i] = ma(k, readInt!int - 1);
		requirements[i] = cast(int)requires[i].length;
		foreach(j; requires[i])
			requiredBy[j] ~= i;
		if (requires[i].length == 0)
		{
			understandable.insert(i);
		}
	}
	int passes = 0;
	while (!understandable.empty)
	{
		passes++;
		auto range = understandable.upperBound(-1);
		while (!range.empty)
		{
			auto current = range.front;
			understandable.removeKey(current);
			processed[current] = true;
			foreach(dependents; requiredBy[current])
			{
				requirements[dependents]--;
				assert(requirements[dependents] >= 0);
				if (requirements[dependents] == 0)
				{
					understandable.insert(dependents);
				}
			}
			range = understandable.upperBound(current);
		}
	}
	if (!all(processed))
	{
		writeln(-1);
	}
	else
	{
		writeln(passes);
	}
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
	{
		popChar;
	}
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

int N;
int[] K;
int[][] A;

int[] vis;
int[] dp;

bool dfs(int u) {
  vis[u] = 1;
  dp[u] = 1;
  foreach (v; A[u]) {
    if (vis[v] == 0) {
      if (!dfs(v)) {
        return false;
      }
      chmax(dp[u], ((u < v) ? 1 : 0) + dp[v]);
    } else if (vis[v] == 1) {
      return false;
    }
  }
  vis[u] = 2;
  return true;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        N = readInt();
        K = new int[N];
        A = new int[][N];
        foreach (u; 0 .. N) {
          K[u] = readInt();
          A[u] = new int[K[u]];
          foreach (k; 0 .. K[u]) {
            A[u][k] = readInt() - 1;
          }
        }

        vis = new int[N];
        dp = new int[N];
        bool ok = true;
        foreach (u; 0 .. N) {
          if (vis[u] == 0) {
            if (!dfs(u)) {
              ok = false;
              break;
            }
          }
        }

        int ans;
        if (ok) {
          ans = dp.maxElement;
        } else {
          ans = -1;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n, s;
	while (readf (" %s %s", &n, &s) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		long res = 0;
		foreach (i; 0..n)
		{
			if (i <= n / 2)
			{
				res += max (0, a[i] - s);
			}
			if (i >= n / 2)
			{
				res += max (0, s - a[i]);
			}
		}
		writeln (res);
	}
}

import core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.datetime;
import std.functional;
import std.math;
import std.numeric;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

void main()
{
    int n, s;
    readf("%s %s", &n, &s);
    readln;

    auto arr = readln.chomp.split.map!(to!int).array;

    arr.sort();

    auto ans = 0L;
    if (arr[n/2] < s) {
        foreach (e; arr[n/2 .. $]) {
            if (e < s) ans += s - e;
        }
    } else if (arr[n/2] > s) {
        foreach (e; arr[0 .. n/2 + 1]) {
            if (e > s) ans += e - s;
        }
    }

    ans.writeln;
}

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, std.bitmanip;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto S = s[1].to!long;
    auto A = readln.split.map!(to!long).array;
    A.sort();

    int i = N / 2;
    long ans = 0;

    if (A[i] > S) {
        while (i >= 0 && A[i] > S) {
            ans += A[i] - S;
            i -= 1;
        }
    } else if (A[i] < S) {
        while (i < N && A[i] < S) {
            ans += S - A[i];
            i += 1;
        }
    }

    ans.writeln;
}


import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

long mod = 10^^9 + 7;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto N = RD!int;
	auto s = RD!string;

	auto m = N - 11 + 1;
	long cnt;
	foreach (i; 0..m)
	{
		if (s[i] == '8')
		{
			++cnt;
		}
	}

	writeln(cnt > m / 2 ? "YES" : "NO");
	stdout.flush();
	debug readln();
}

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.string;

void main() {
    auto N = readln.chomp.to!int;
    auto S = readln.chomp;
    auto used = new bool[](N);

    for (int i = 0, j = 0, t = 0, rest = N; rest > 11; t ^= 1, --rest) {
        if (t == 0) {
            while (i < N && (used[i] || S[i] == '8')) ++i;
            if (i >= N) {
                writeln("YES");
                return;
            }
            used[i] = true;
        } else {
            while (j < N && (used[j] || S[j] != '8')) ++j;
            if (j >= N) {
                writeln("NO");
                return;
            }
            used[j] = true;
        }
    }

    foreach (i; 0..N) {
        if (!used[i]) {
            writeln(S[i] == '8' ? "YES" : "NO");
            return;
        }
    }
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;

void main() {
  auto n = readln.strip.to!int;
  auto s = readln.strip[0 .. n];
  auto psteps = (n - 11) >> 1;
  auto t = s[0 .. n - 10];
  int e;
  foreach (i; 0 .. t.length) {
    if (t[i] == '8') {
      ++e;
    }
  }
  writeln (e > psteps ? "YES" : "NO");
}


//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader;
  auto n = 2 * r.next!int;
  auto a = r.nextA!int(n);
  auto idx = new size_t[n];
  a.sort();
  if (a[0] == a[n-1]) {
    writeln (-1);
  } else {
    writefln ("%(%s %)", a);
  }
}

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.datetime.stopwatch;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

void main()
{
    int n;
    readf("%s", &n);
    readln;

    auto arr = readln.chomp.split.map!(to!int).array;

    arr.sort();

    if (arr.front == arr.back) {
        writeln(-1);
        return;
    }

    arr.writefln!"%(%s %)";
}

import core.stdc.stdio;
import std.stdio;
import std.algorithm;
import std.range;

void main()
{
    uint n;
    scanf("%ud", &n);
    int[] a = new int[2 * n];
    for (int i = 0; i < 2 * n; i++)
    {
        scanf("%d", &a[i]);
    }

    sort(a);

    auto t1 = sum(a[0 .. n]);
    auto t2 = sum(a[n .. 2 * n]);
    if (t1 == t2)
        writeln(-1);
    else
        writefln("%(%d %)", a);
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * y / gcd(x, y); }

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto N = RD!int;
	auto A = RDR.ARR;
	A.sort();
	long sum1, sum2;
	foreach (i; 0..N*2)
	{
		if (i < N)
			sum1 += A[i];
		else
			sum2 += A[i];
	}

	if (sum1 == sum2)
		writeln(-1);
	else
		A.map!(to!string).join(" ").writeln;
	stdout.flush();
	debug readln();
}


import std.stdio;

immutable int limit = 1 << 20;
int [limit] t;

void add (int v, int delta = 1)
{
	for ( ; v < limit; v += v & -v)
	{
		t[v] += delta;
	}
}

int pop (int k)
{
	int pos = limit >> 1;
	for (int x = limit >> 2; x > 0; x >>= 1)
	{
		if (k > t[pos])
		{
			k -= t[pos];
			pos += x;
		}
		else
		{
			pos -= x;
		}
	}
	pos += (k > t[pos]);
	add (pos, -1);
	return pos;
}

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		t[] = 0;

		foreach (i; 0..n)
		{
			int v;
			readf !(" %s") (v);
			add (v);
		}

		foreach (j; 0..m)
		{
			int k;
			readf !(" %s") (k);
			if (k > 0)
			{
				add (k);
			}
			else
			{
				pop (-k);
			}
		}

		auto res = pop (1);
		writeln (res < limit ? res : 0);
	}
}

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric, std.container;

struct BITree(alias _fun, alias E, T)
if (is(typeof(E) : T))
{
    import std.functional : binaryFun;
    alias OP = binaryFun!_fun;

    ///
    this(size_t n, T[] ts) {
        this.n = n;
        this.tree.length = n+1;
        foreach (ref e; this.tree) e = E;
        foreach (i, t; ts) this.update(i, t);
    }

    void update(size_t i, T e) {
        i += 1;
        while (i <= this.n) {
            this.tree[i] = OP(this.tree[i], e);
            i += i & -i;
        }
    }

    ///
    T query(size_t i) {
        auto r = E;
        while (i > 0) {
            r = OP(r, this.tree[i]);
            i -= i & -i;
        }
        return r;
    }

private:
    size_t n;
    T[] tree;
}

auto bitree(alias fun, alias init, T)(size_t n, T[] ts = [])
{
    return BITree!(fun, init, T)(n, ts);
}

///
auto bitree(alias fun, alias init, T)(T[] ts)
{
    return BITree!(fun, init, T)(ts.length, ts);
}

auto sum_bitree(T)(size_t n, T[] ts = [])
{
    return bitree!("a + b", 0, T)(n, ts);
}

auto sum_bitree(T)(T[] ts)
{
    return sum_bitree!T(ts.length, ts);
}

void main()
{
    auto nq = readln.split.to!(int[]);
    auto N = nq[0];
    auto Q = nq[1];
    auto bit = sum_bitree!int(N+1);
    foreach (_; 0..N) {
        int a;
        readf(" %d", &a);
        bit.update(a, 1);
    }
    foreach (_; 0..Q) {
        int q;
        readf(" %d", &q);
        if (q < 0) {
            q = -q;
            size_t l = 1, r = N+1;
            while (l+1 < r) {
                auto m = (l+r)/2;
                if (bit.query(m) < q) {
                    l = m;
                } else {
                    r = m;
                }
            }
            bit.update(l, -1);
        } else {
            bit.update(q, 1);
        }
    }
    foreach (i; 1..N+1) if (bit.query(i+1) > 0) {
        writeln(i);
        return;
    }
    writeln(0);
}

import std.stdio;

immutable int limit = (1 << 20) + 1;
int [limit] t;

void add (int v, int delta = 1)
{
	for ( ; v < limit; v += v & -v)
	{
		t[v] += delta;
	}
}

int pop (int k)
{
	int pos = limit >> 1;
	for (int x = limit >> 2; x > 0; x >>= 1)
	{
		if (k > t[pos])
		{
			k -= t[pos];
			pos += x;
		}
		else
		{
			pos -= x;
		}
	}
	pos += (k > t[pos]);
	add (pos, -1);
	return pos;
}

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		t[] = 0;

		foreach (i; 0..n)
		{
			int v;
			readf !(" %s") (v);
			add (v);
		}

		foreach (j; 0..m)
		{
			int k;
			readf !(" %s") (k);
			if (k > 0)
			{
				add (k);
			}
			else
			{
				pop (-k);
			}
		}

		auto res = pop (1);
		writeln (t[res] >= 0 ? res : 0);
	}
}

import std.stdio;
immutable int z = 1 << 20;
int [z] t;
void a (int v, int d = 1) {
	for ( ; v < z; v += v & -v) t[v] += d;
}
int p (int k) {
	int v = z >> 1;
	for (int b = z >> 2; b > 0; b >>= 1)
		if (k > t[v]) k -= t[v], v += b;
		else v -= b;
	v += (k > t[v]);
	a (v, -1);
	return v;
}
void main () {
	int n, m, x, r;
	readf !(" %d %d") (n, m);
	foreach (i; 0..n) readf !(" %d") (x), a (x);
	foreach (j; 0..m) {
		readf !(" %d") (x);
		if (x > 0) a (x);
		else p (-x);
	}
	r = p (1);
	writeln (r < z ? r : 0);
}

import std.stdio;

immutable int limit = 1 << 20;
__gshared int [limit] t;

void add (int v, int delta = 1)
{
	for ( ; v < limit; v += v & -v)
	{
		t[v] += delta;
	}
}

int pop (int k)
{
	int pos = limit >> 1;
	for (int x = limit >> 2; x > 0; x >>= 1)
	{
		if (k > t[pos])
		{
			k -= t[pos];
			pos += x;
		}
		else
		{
			pos -= x;
		}
	}
	pos += (k > t[pos]);
	add (pos, -1);
	return pos;
}

void main ()
{
	int n, m, v, k;
	while (readf !(" %s %s") (n, m) > 0)
	{
		t[] = 0;

		foreach (i; 0..n)
		{
			readf !(" %s") (v);
			add (v);
		}

		foreach (j; 0..m)
		{
			readf !(" %s") (k);
			if (k > 0)
			{
				add (k);
			}
			else
			{
				pop (-k);
			}
		}

		auto res = pop (1);
		writeln (res < limit ? res : 0);
	}
}

import std.stdio;

immutable int limit = 1 << 20;
int [limit] t;

void add (int v, int delta = 1) {
	for ( ; v < limit; v += v & -v) t[v] += delta;
}

int pop (int k) {
	int pos = limit >> 1;
	for (int x = limit >> 2; x > 0; x >>= 1)
		if (k > t[pos]) k -= t[pos], pos += x;
		else pos -= x;
	pos += (k > t[pos]);
	add (pos, -1);
	return pos;
}

void main () {
	int n, m, v, k;
	readf !(" %d %d") (n, m);
	foreach (i; 0..n) readf !(" %d") (v), add (v);
	foreach (j; 0..m) {
		readf !(" %d") (k);
		if (k > 0) add (k);
		else pop (-k);
	}

	auto res = pop (1);
	writeln (res < limit ? res : 0);
}

import core.bitop, std.stdio;

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		auto z = 1 << bsr (n);
		auto t = new int [z * 2 + 1];

		void add (int v, int delta = 1)
		{
			for ( ; v <= z * 2; v += v & -v)
			{
				t[v] += delta;
			}
		}

		int pop (int k)
		{
			int pos = z;
			for (int x = z >> 1; x > 0; x >>= 1)
			{
				if (k > t[pos])
				{
					k -= t[pos];
					pos += x;
				}
				else
				{
					pos -= x;
				}
			}
			pos += (k > t[pos]);
			add (pos, -1);
			return pos;
		}

		foreach (i; 0..n)
		{
			int v;
			readf !(" %s") (v);
			add (v);
		}

		foreach (j; 0..m)
		{
			int k;
			readf !(" %s") (k);
			if (k > 0)
			{
				add (k);
			}
			else
			{
				pop (-k);
			}
		}

		auto res = pop (1);
		writeln (t[res] >= 0 ? res : 0);
	}
}

import std.stdio;

immutable int limit = 1 << 20;
__gshared int [limit] t;

void add (int v, int delta = 1)
{
	for ( ; v < limit; v += v & -v)
	{
		t[v] += delta;
	}
}

int pop (int k)
{
	int pos = limit >> 1;
	for (int x = limit >> 2; x > 0; x >>= 1)
	{
		if (k > t[pos])
		{
			k -= t[pos];
			pos += x;
		}
		else
		{
			pos -= x;
		}
	}
	pos += (k > t[pos]);
	add (pos, -1);
	return pos;
}

void main ()
{
	int n, m, v, k;
	while (readf !(" %d %d") (n, m) > 0)
	{
		t[] = 0;

		foreach (i; 0..n)
		{
			readf !(" %d") (v);
			add (v);
		}

		foreach (j; 0..m)
		{
			readf !(" %d") (k);
			if (k > 0)
			{
				add (k);
			}
			else
			{
				pop (-k);
			}
		}

		auto res = pop (1);
		writeln (res < limit ? res : 0);
	}
}

import std.stdio;

immutable int limit = 1 << 20;
int [] t;

void add (int v, int delta = 1)
{
	for ( ; v < limit; v += v & -v)
	{
		t[v] += delta;
	}
}

int pop (int k)
{
	int pos = limit >> 1;
	for (int x = limit >> 2; x > 0; x >>= 1)
	{
		if (k > t[pos])
		{
			k -= t[pos];
			pos += x;
		}
		else
		{
			pos -= x;
		}
	}
	pos += (k > t[pos]);
	add (pos, -1);
	return pos;
}

void main ()
{
	t = new int [limit];
	int n, m, v, k;
	while (readf !(" %s %s") (n, m) > 0)
	{
		t[] = 0;

		foreach (i; 0..n)
		{
			readf !(" %s") (v);
			add (v);
		}

		foreach (j; 0..m)
		{
			readf !(" %s") (k);
			if (k > 0)
			{
				add (k);
			}
			else
			{
				pop (-k);
			}
		}

		auto res = pop (1);
		writeln (res < limit ? res : 0);
	}
}