import std;

T
read (alias T, string end = "") () {
    T x;
    readf!("%s" ~ end)(x);
    return x;
}

void main () {
    immutable tests = read!(uint, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        string s = readln.chomp;
        assert(s.length == 6);

        if (
            s.find('r').find('R').empty() == false &&
            s.find('g').find('G').empty() == false &&
            s.find('b').find('B').empty() == false
        )
            writeln("YES");
        else
            writeln("NO");
    }
}
// ""

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto S = scan;

      const ub = 'a' - 'A';
      return YESNO["RGB".all!(c => S.countUntil(c) > S.countUntil(c + ub))];
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "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; }
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) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto r = RD!int;
	auto n = RD!int;
	auto rbt = new RedBlackTree!(int[], "a[0] > b[0]", true);
	rbt.insert([0, 0, 1, 1, 0]);
	foreach (i; 0..n)
	{
		auto t = RD!int;
		auto x = RD!int;
		auto y = RD!int;

		foreach (e; rbt[])
		{
			auto dist = abs(e[2]-x) + abs(e[3]-y);
			auto dt = t - e[1];
			//debug writeln("dist:", dist, " dt:", dt);
			if (dist <= dt)
			{
				rbt.insert([e[0]+1, t, x, y, i+1]);
				break;
			}
		}
	}
	debug writeln(rbt);

	auto ans = rbt.front;
	writeln(ans[0]);
	stdout.flush;
	debug readln;
}

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

// NEVER USE INBUILT MAX IN DLANG ~ 0.2 sec delay

void play(){
    int n, r;
    r = rd!int;
    n = rd!int;
    auto dp = new ll[](n+1);
    auto maxable = new ll[](n+1);
    tup[] flash;
    flash ~= tup(0, 1, 1);
    foreach(i; 0..n){
        flash ~= tup(rd, rd, rd);
    }
    ll maxold = 0, maxel = 0;
    foreach(i;0..n+1){
        // Dist > 499*2
        maxold = max(maxold, maxable[i]);

        // Add if not present
        dp[i] = max(maxold, dp[i]);

        ll xmax = max(flash[i][1], r - flash[i][1]);
        ll ymax = max(flash[i][2], r - flash[i][2]);

        // Reachable by 1, 1, 0 only!
        if(i > 0 && !dp[i]){ continue; }

        foreach(j; i+1..n+1){
            // Above 1000 set max at that position
            if(flash[j][0] >= flash[i][0] + xmax + ymax){
                maxable[j] = max(maxable[j], dp[i] + 1);
                break;
            }
            ll dt = flash[j][0] - flash[i][0];
            ll dist = abs(flash[j][1] - flash[i][1]) + abs(flash[j][2] - flash[i][2]);
            if(dist <= dt){
                dp[j] = max(dp[j], dp[i] + 1);
            }
        }
        maxel = max(dp[i], maxel);
    }
    show(dp);
    writeln(maxel);
}

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

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
alias ll = long;
alias rbt = redBlackTree;
alias sr = SortedRange;
alias tup = Tuple!(long, long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
T max(T = long)(T a, T b){ return (a > b) ? a : b;}
T min(T = long)(T a, T b){ return (a < b) ? a : b;}

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

void main ()
{
	int r, n;
	while (readf !(" %s %s") (r, n) > 0)
	{
		alias Record = Tuple !(int, q{t}, int, q{x}, int, q{y});
		auto z = new Record [n + 1];
		z[0] = Record (0, 1, 1);
		foreach (ref c; z[1..$])
		{
			readf !(" %s %s %s") (c.t, c.x, c.y);
		}
		auto f = new int [n + 1];
		f[1..$] = int.min;
		auto g = new int [n + 1];
		foreach (i; 1..n + 1)
		{
			for (auto j = i - 1; j >= 0; j--)
			{
				auto d = abs (z[i].x - z[j].x) +
				    abs (z[i].y - z[j].y);
				if (d <= z[i].t - z[j].t)
				{
					f[i] = max (f[i], f[j] + 1);
				}
				if (z[i].t - z[j].t > (r - 1) * 2)
				{
					f[i] = max (f[i], g[j] + 1);
					break;
				}
			}
			g[i] = max (g[i - 1], f[i]);
		}
		writeln (f.maxElement);
	}
}

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

// NEVER USE INBUILT MAX IN DLANG ~ 0.2 sec delay

void play(){
    int n, r;
    r = rd!int;
    n = rd!int;
    auto dp = new ll[](n+1);
    auto maxable = new ll[](n+1);
    tup[] flash;
    flash ~= tup(1, 1, 0);
    foreach(i; 0..n){
        flash ~= tup(rd, rd, rd);
    }
    ll maxold = 0, maxel;
    foreach(i;0..n+1){
        // Dist > 499*2
        maxold = max(maxold, maxable[i]);

        // Add if not present
        dp[i] = max(maxold, dp[i]);

        ll xmax = max(flash[i][1], r - flash[i][1]);
        ll ymax = max(flash[i][2], r - flash[i][2]);

        // Reachable by 1, 1, 0 only!
        if(i > 0 && !dp[i]){ continue; }

        foreach(j; i+1..n+1){
            // Above 1000 set max at that position
            if(flash[j][0] >= flash[i][0] + xmax + ymax){
                maxable[j] = max(maxable[j], dp[i] + 1);
                break;
            }
            ll dt = flash[j][0] - flash[i][0];
            ll dist = abs(flash[j][1] - flash[i][1]) + abs(flash[j][2] - flash[i][2]);
            if(dist <= dt){
                dp[j] = max(dp[j], dp[i] + 1);
            }
        }
        maxel = max(dp[i], maxel);
    }
    writeln(maxel);
}

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

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
alias ll = long;
alias rbt = redBlackTree;
alias sr = SortedRange;
alias tup = Tuple!(long, long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
T max(T = long)(T a, T b){ return (a > b) ? a : b;}
T min(T = long)(T a, T b){ return (a < b) ? a : b;}

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

bool check_dist(tup p1, tup p2){
    ll dt = abs(p2[0] - p1[0]);
    return (dt >= abs(p1[1] - p2[1]) + abs(p1[2] - p2[2]));
}

void play(){
    int n, r;
    r = rd!int;
    n = rd!int;
    auto dp = new ll[](n+1);
    dp[] = 0;
    tup[] flash;
    ll ti, xi, yi;
    flash ~= tup(0, 1, 1);
    foreach(i; 0..n){
        flash ~= tup(rd, rd, rd);
    }

    ll maxold = 0;
    ll[long] maxable;
    foreach(i;0..n+1){
        int crange = flash[i][0].to!int/1000;

        // Reachable by 1, 1, 0 only!
        if(i > 0 && crange == 0 && !dp[i]){ continue; }

        maxold += maxold + maxable.get(i, 0);
        // Add if not present
        if(crange > 0 && dp[i] < maxold){
            dp[i] = maxold;
        }

        foreach(j; i+1..n+1){
            // Above 1000 set max at that position
            if(flash[j][0] > flash[i][0] + 1000){
                maxable[j] = max(maxable.get(j, 0), dp[i] + 1);
                break;
            }
            if(check_dist(flash[j], flash[i])){
                dp[j] = max(dp[j], dp[i] + 1);
            }
        }
    }
    show(dp);
    writeln(maxElement(dp));
}

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

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
alias ll = long;
alias rbt = redBlackTree;
alias sr = SortedRange;
alias tup = Tuple!(long, long, long);
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }

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

void main ()
{
	int r, n;
	while (readf !(" %s %s") (r, n) > 0)
	{
		alias Record = Tuple !(int, q{t}, int, q{x}, int, q{y});
		auto z = new Record [n + 1];
		z[0] = Record (0, 1, 1);
		foreach (ref c; z[1..$])
		{
			readf !(" %s %s %s") (c.t, c.x, c.y);
		}
		auto f = new int [n + 1];
		f[1..$] = int.min;
		foreach (i; 1..n + 1)
		{
			for (auto j = i - 1; j >= 0; j--)
			{
				auto d = abs (z[i].x - z[j].x) +
				    abs (z[i].y - z[j].y);
				if (d <= z[i].t - z[j].t)
				{
					f[i] = max (f[i], f[j] + 1);
				}
				if (z[i].t - z[j].t > (r - 1) * 2)
				{
					break;
				}
			}
		}
		writeln (f.maxElement);
	}
}

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

void main ()
{
	int r, n;
	while (readf !(" %s %s") (r, n) > 0)
	{
		alias Record = Tuple !(int, q{t}, int, q{x}, int, q{y});
		auto z = new Record [n + 1];
		z[0] = Record (0, 1, 1);
		foreach (ref c; z[1..$])
		{
			readf !(" %s %s %s") (c.t, c.x, c.y);
		}
		auto f = new int [n + 1];
		f[1..$] = int.min;
		auto g = new int [n + 1];
		foreach (i; 1..n + 1)
		{
			for (auto j = i - 1; j >= 0; j--)
			{
				auto d = abs (z[i].x - z[j].x) +
				    abs (z[i].y - z[j].y);
				if (d <= z[i].t - z[j].t)
				{
					f[i] = max (f[i], f[j] + 1);
				}
				if (z[i].t - z[j].t > (r - 1) * 2)
				{
					f[i] = max (f[i], g[j]);
					break;
				}
			}
			g[i] = max (g[i - 1], f[i]);
		}
		writeln (f.maxElement);
	}
}


import std.stdio;
import std.exception;
import std.algorithm;
import std.range;

void main() { while (solve()) {} }

bool solve() {
	int n;
	if (!readf(" %s", &n)) return false;
	auto a = new long[n];
	long prev = 0;
	foreach (ref x; a) {
		enforce(readf(" %s", &x));
		x += prev;
		prev = x;
	}
	int m;
	enforce(readf(" %s", &m));
	foreach (_; 0..m) {
		long x;
		enforce(readf(" %s", &x));
		auto ans = a.assumeSorted.lowerBound(x).length + 1;
		writeln(ans);
	}
	return true;
}

// https://codeforces.com/problemset/problem/474/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

void main() {
    int n = readln.chomp.to!int;
    int[] a = readln.split.map!(x => x.to!int).array;
    int m = readln.chomp.to!int;
    int[] q = readln.split.map!(x => x.to!int).array;

    int[] worms;
    worms ~= a[0];

    // cumulative sum
    for(int i = 1; i < n; i++)
        worms ~= worms[i-1] + a[i];

    foreach(query; q) {
            int right = n-1;
            int left = 0;
            int middle;
        while(left <= right) {
            middle = (right+left)/2;
            if(worms[middle] >= query) {
                right = middle-1;
            } else {
                left = middle+1;
            }
        }
        left++;
        left.writeln;
    }
}

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

void main() {
    int n = readln.chomp.to!int;
    int[] a = [0] ~ readln.chomp.split.map!(to!int).array;
    int m = readln.chomp.to!int;
    auto q = readln.chomp.split.map!(to!int);

    foreach (i; 1..a.length) {
        a[i] += a[i - 1];
    }

    auto r = assumeSorted(a);
    foreach (e; q) {
        r.lowerBound(e).length.writeln;
    }
}


import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.complex, std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///int length
		int sz(T)(ref const T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int n, a, b;
	read(n, a, b);
	auto s = readln.strip.split('*');
	int ans;
	foreach (x; s)
	{
		if (a > b)
			swap(a, b);
		if (x.length & 1)
		{
			int m = min(x.length / 2, a);
			ans += m;
			a -= m;
			ans += min(b, x.length / 2 + 1);
			b -= min(b, x.length / 2 + 1);
		}
		else
		{
			int m = min(x.length / 2, a);
			ans += m;
			a -= m;
			ans += min(b, x.length / 2);
			b -= min(b, x.length / 2);
		}
	}
	writeln(ans);
}

import std.algorithm.comparison : min;
import std.algorithm.iteration;
import std.algorithm.sorting;
import std.range;
import std.stdio;
import std.string;

void main()
{
  int a, b, n, m; // total seats, num type a, num type b
  readf!"%d %d %d\n"(n, a, b);

  auto l = readln
    .stripRight
    .group
    .filter!(a => a[0] == '.')
    .map!"a[1]"
    .array
    .sort!"a > b";

  // answer
  auto s = 0;

  foreach (g; l) {
    auto x = min(g / 2 + (a > b ? (g % 2) : 0), a);
    auto y = min(g / 2 + (a > b ? 0 : (g % 2)), b);

    s += x + y;
    a -= x;
    b -= y;
  }

  writeln(s);
}

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.complex, std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///int length
		int sz(T)(ref const T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int n, a, b;
	read(n, a, b);
	auto s = readln.strip.split('*');
	int ans;
	foreach (x; s)
	{
		if (a > b)
			swap(a, b);
		if (x.length & 1)
		{

			int m = min(x.length / 2, a);
			ans += m;
			a -= m;
			ans += min(b, m + 1);
			b -= min(b, m + 1);
		}
		else
		{
			int m = min(x.length / 2, a);
			ans += m;
			a -= m;
			ans += min(b, m);
			b -= min(b, m);
		}
	}
	writeln(ans);
}


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; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } 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 = 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 main()
{
	auto n = RD;
	auto m = RD;
	auto q = RD!int;
	auto g = gcd(n, m);
	auto l1 = n / g;
	auto l2 = m / g;
	auto ans = new bool[](q);
	foreach (i; 0..q)
	{
		auto sx = RD;
		auto sy = RD-1;
		auto ex = RD;
		auto ey = RD-1;
		long pos1, pos2;
		if (sx == 1)
			pos1 = sy / l1;
		else
			pos1 = sy / l2;
		if (ex == 1)
			pos2 = ey / l1;
		else
			pos2 = ey / l2;
		ans[i] = pos1 == pos2;
	}

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

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()
{
    long n, m, q;
    readf("%s %s %s", &n, &m, &q);
    readln;

    auto g = gcd(n, m);

    debug { g.writeln; }

    n /= g;
    m /= g;

    while (q--) {
        int s1, e1;
        long s2, e2;
        readf("%s %s %s %s", &s1, &s2, &e1, &e2);
        readln;

        long normalize(int p, long x) {
            if (p == 1) { return (x-1) / n; }
            else { return (x-1) / m; }
        }

        s2 = normalize(s1, s2);
        e2 = normalize(e1, e2);

        writeln(s2 == e2 ? "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 read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	long n = read.to!long;
	long m = read.to!long;
	int q = read.to!int;

	long g = gcd(n, m);
	long a = n / g;
	long b = m / g;
	log("g:", g, "a:", a, "b:", b);

	foreach(_; 0 .. q){
		int sx = read.to!int;
		long sy = read.to!long - 1;
		int ex = read.to!int;
		long ey = read.to!long - 1;
		log("sx:", sx, "sy:", sy, "ex:", ex, "ey:", ey);

		long s = sy / (sx == 1? a: b);
		long e = ey / (ex == 1? a: b);
		log("s:", s, "e:", e);

		if(s == e) "YES".writeln;
		else "NO".writeln;
	}

}

long gcd(long a, long b){
	if(a < b) return gcd(b, a);
	if(a % b == 0) return b;
	return gcd(b, a % b);
}


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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n;
  @Dim("n") long[] w;

  void solve(long tc = -1)
  {
    long[101] cnt = 0;
    auto forbidden = new RedBlackTree!long[cast(size_t) n];
    foreach(ref f; forbidden)
      f = redBlackTree!long();
    foreach(i; 0 .. n)
      {
        foreach(j; i + 1 .. n)
          {
            if (!(w.at(j) in forbidden.at(i)) && !(w.at(i) in forbidden.at(j)))
              {
                forbidden.at(j).insert(w.at(i));
                forbidden.at(i).insert(w.at(j));
                cnt.at(w.at(i) + w.at(j))++;
                debug writeln("from ", i, " to ", j, " ", w.at(i) + w.at(j), " cnt = "
                              , cnt.at(w.at(i) + w.at(j)));
              }
          }
      }
    writeln(cnt[].fold!max);
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(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);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(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)
{
  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;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

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) { 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 w = RDA!int;

		auto cnt = new int[](n+1);
		foreach (i; 0..n)
		{
			++cnt[w[i]];
		}

		foreach (i; 2..n*2+1)
		{
			long tmp;
			foreach (j; 1..min(i, n+1))
			{
				auto k = i - j;
				if (k < j || k > n) continue;
				if (j == k)
				{
					tmp += cnt[k] / 2;
				}
				else
				{
					tmp += min(cnt[j], cnt[k]);
				}
				debug writeln("j:", j, " k:", k, " tmp:", tmp);
			}
			debug writeln("i:", i, " tmp:", tmp);
			ans[ti].chmax(tmp);
		}
	}

	foreach (e; ans)
		writeln(e);
	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; }
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) { 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 w = RDA!int;

		auto cnt = new int[](n+1);
		foreach (i; 0..n)
		{
			++cnt[w[i]];
		}

		foreach (i; 2..n*2+1)
		{
			long tmp;
			foreach (j; 1..min(i, n))
			{
				auto k = i - j;
				if (k < j || k > n) continue;
				if (j == k)
				{
					tmp += cnt[k] / 2;
				}
				else
				{
					tmp += min(cnt[j], cnt[k]);
				}
				debug writeln("j:", j, " k:", k, " tmp:", tmp);
			}
			debug writeln("i:", i, " tmp:", tmp);
			ans[ti].chmax(tmp);
		}
	}

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


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

struct ModInt(uint M_) {
  import std.conv : to;
  alias M = M_;
  uint x;
  this(ModInt a) { x = a.x; }
  this(uint x_) { x = x_ % M; }
  this(ulong x_) { x = cast(uint)(x_ % M); }
  this(int x_) { x = ((x_ %= cast(int)(M)) < 0) ? (x_ + cast(int)(M)) : x_; }
  this(long x_) { x = cast(uint)(((x_ %= cast(long)(M)) < 0) ? (x_ + cast(long)(M)) : x_); }
  ref ModInt opAssign(T)(inout(T) a) if (is(T == uint) || is(T == ulong) || is(T == int) || is(T == long)) { return this = ModInt(a); }
  ref ModInt opOpAssign(string op, T)(T a) {
    static if (is(T == ModInt)) {
      static if (op == "+") { x = ((x += a.x) >= M) ? (x - M) : x; }
      else static if (op == "-") { x = ((x -= a.x) >= M) ? (x + M) : x; }
      else static if (op == "*") { x = cast(uint)((cast(ulong)(x) * a.x) % M); }
      else static if (op == "/") { this *= a.inv(); }
      else static assert(false);
      return this;
    } else static if (op == "^^") {
      if (a < 0) return this = inv()^^(-a);
      ModInt b = this, c = 1U;
      for (long e = a; e; e >>= 1) { if (e & 1) c *= b; b *= b; }
      return this = c;
    } else {
      return mixin("this " ~ op ~ "= ModInt(a)");
    }
  }
  ModInt inv() const {
    uint a = M, b = x; int y = 0, z = 1;
    for (; b; ) { const q = a / b; const c = a - q * b; a = b; b = c; const w = y - cast(int)(q) * z; y = z; z = w; }
    assert(a == 1); return ModInt(y);
  }
  ModInt opUnary(string op)() const {
    static if (op == "+") { return this; }
    else static if (op == "-") { ModInt a; a.x = x ? (M - x) : 0U; return a; }
    else static assert(false);
  }
  ModInt opBinary(string op, T)(T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op, T)(T a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  bool opCast(T: bool)() const { return (x != 0U); }
  string toString() const { return x.to!string; }
}

enum MO = 998244353;
alias Mint = ModInt!MO;

enum LIM_INV = 2 * 10^^5 + 10;
Mint[] inv, fac, invFac;
void prepare() {
  inv = new Mint[LIM_INV];
  fac = new Mint[LIM_INV];
  invFac = new Mint[LIM_INV];
  inv[1] = 1;
  foreach (i; 2 .. LIM_INV) {
    inv[i] = -((Mint.M / i) * inv[cast(size_t)(Mint.M % i)]);
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM_INV) {
    fac[i] = fac[i - 1] * i;
    invFac[i] = invFac[i - 1] * inv[i];
  }
}
Mint binom(long n, long k) {
  if (n < 0) {
    if (k >= 0) {
      return (-1)^^(k & 1) * binom(-n + k - 1, k);
    } else if (n - k >= 0) {
      return (-1)^^((n - k) & 1) * binom(-k - 1, n - k);
    } else {
      return Mint(0);
    }
  } else {
    if (0 <= k && k <= n) {
      assert(n < LIM_INV);
      return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] * invFac[cast(size_t)(n - k)];
    } else {
      return Mint(0);
    }
  }
}

void main() {
  prepare;

  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        auto A = new long[N];
        foreach (i; 0 .. N) {
          A[i] = readLong;
        }

        auto ASum = new long[N + 1];
        foreach (i; 0 .. N) {
          ASum[i + 1] = ASum[i] + A[i];
        }
        debug {
          writeln("ASum = ", ASum);
        }

        Mint ans = 1;
        for (int i = 1, j = N - 1; i <= j; ) {
          const val = min(ASum[i], ASum[N] - ASum[j]);
          int cntI, cntJ;
          for (; i <= j && ASum[i] == val; ++i) ++cntI;
          for (; i <= j && ASum[N] - ASum[j] == val; --j) ++cntJ;
          debug {
            writeln(val, " ", cntI, " ", cntJ);
          }
          if (val == ASum[N] - val) {
            ans *= Mint(2)^^(cntI + cntJ);
          } else {
            Mint sum;
            foreach (k; 0 .. min(cntI, cntJ) + 1) {
              sum += binom(cntI, k) * binom(cntJ, k);
            }
            ans *= sum;
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

immutable int mod   = 998_244_353;
immutable int limit =     100_005;

int [] f;
int [] fi;

int powMod (int a, int p)
{
	int res = 1;
	for ( ; p > 0; p >>= 1)
	{
		if (p & 1)
		{
			res = (res * 1L * a) % mod;
		}
		a = (a * 1L * a) % mod;
	}
	return res;
}

int invMod (int a)
{
	return powMod (a, mod - 2);
}

void prepare (int limit)
{
	f = [1];
	foreach (i; 1..limit)
	{
		f ~= (f.back * 1L * i) % mod;
	}
	fi = f.map !(invMod).array;
}

long choose (int n, int k)
{
	if (!(0 <= k && k <= n))
	{
		return 0;
	}
	long res = f[n];
	res = (res * 1L * invMod (f[n - k])) % mod;
	res = (res * 1L * invMod (f[k])) % mod;
	return res;
}

void main ()
{
	prepare (limit);

	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;

		int lo = 0;
		int hi = n;
		long x = 0;
		long y = 0;
		long res = 1;
		while (lo < hi)
		{
			while (x < y && lo < hi)
			{
				x += a[lo];
				lo += 1;
			}
			while (y < x && lo < hi)
			{
				hi -= 1;
				y += a[hi];
			}
			if (x == y)
			{
				int lo2 = lo;
				int hi2 = hi;
				while (lo2 < hi2 && a[lo2] == 0)
				{
					lo2 += 1;
				}
				while (lo2 < hi2 && a[hi2 - 1] == 0)
				{
					hi2 -= 1;
				}
				bool inner = (hi - lo < n);
				long cur = 1;
				if (lo2 == hi2)
				{
					int len = lo2 - lo;
					len = len + inner - !inner;
					for (int i = 1; i <= len; i += 1)
					{
						long temp =
						    choose (len, i);
						cur = (cur + temp) % mod;
					}
				}
				else
				{
					int lenLo = lo2 - lo + inner;
					int lenHi = hi - hi2 + inner;
					for (int i = 1; i <= lenLo &&
					    i <= lenHi; i++)
					{
						long temp =
						    choose (lenLo, i);
						temp *=
						    choose (lenHi, i);
						cur = (cur + temp) % mod;
					}
				}
				res = (res * 1L * cur) % mod;
				if (lo2 < n)
				{
					x += a[lo2];
				}
				lo = lo2 + 1;
				hi = hi2;
			}
		}
		writeln (res);
	}
}


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;

immutable long MOD = 998244353;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    foreach (i; 0..N-1) (A[i+1] += A[i]) %= MOD;

    long a = 1;
    long b = 0;
    long ans = 0;

    foreach_reverse (i; 0..N) {
        (ans += A[i] * a % MOD) %= MOD;
        a = a * 2 % MOD;
        if (b > 0) a += powmod(2, b-1, MOD);
        a %= MOD;
        b += 1;
    }

    ans.writeln;
}

long powmod(long a, long x, long m) {
    long ret = 1;
    while (x) {
        if (x % 2) ret = ret * a % m;
        a = a * a % m;
        x /= 2;
    }
    return ret;
}

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

void main()
{
    immutable int MOD = 998244353;

    int mulmod(int a, int b) {
        return cast(long)a * b % MOD;
    }

    int addmod(int a, int b) {
        int c = a + b;
        if (c > MOD) c -= MOD;
        return c;
    }

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

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

    auto pws = recurrence!((a, n) => mulmod(a[n-1], 2))(1).take(n).array.retro.array;

    pws ~= 0;

    debug { pws.writeln; }

    auto ans = 0;
    foreach (i, e; arr) {
        auto opts = cast(int)(n-1 - i);
        auto cur = addmod(pws[i], mulmod(opts, pws[i+1]));
        cur = mulmod(cur, e);
        ans = addmod(ans, cur);
    }

    ans.writeln;
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;
import std.traits;
import std.variant;
import std.concurrency;

const mod = 998244353;

void main(string[] args)
{
  auto n = next!int;
  auto a = next!long(n);
  foreach(ref ai; a) ai %= mod;
  long leaves = 1;
  long sumA = 0;
  long sumB = 0;
  long res = 0;
  foreach(i; 0 .. n)
    {
      sumA = (2 * sumA + a[i]) % mod;
      res = (sumA + sumB) % mod;
      sumB += res;
    }
  res.writeln;
  return;
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}

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;

immutable long MOD = 998244353;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    foreach (i; 0..N-1) (A[i+1] += A[i]) %= MOD;

    long a = 1;
    long b = 0;
    long ans = 0;

    foreach_reverse (i; 0..N) {
        (ans += A[i] * a % MOD) %= MOD;
        long c = 2 * a + b;
        b = a;
        a = c;
    }

    ans.writeln;
}


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[] P;
int[][] G;

int[] sz;

void dfs0(int u, int p) {
  sz[u] = 1;
  foreach (v; G[u]) {
    if (v != p) {
      dfs0(v, u);
      sz[u] += sz[v];
    }
  }
}

int[] ans;

void dfs1(int u, int p) {
  foreach (v; G[u]) {
    if (v != p) {
      if (sz[v] % 2 == 0) {
        dfs1(v, u);
      }
    }
  }
  ans ~= u;
  foreach (v; G[u]) {
    if (v != p) {
      if (sz[v] % 2 != 0) {
        dfs1(v, u);
      }
    }
  }
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      P = new int[N];
      foreach (u; 0 .. N) {
        P[u] = readInt() - 1;
      }

      if (N % 2 == 0) {
        writeln("NO");
      } else {
        G = new int[][N];
        foreach (u; 0 .. N) {
          if (P[u] != -1) {
            G[u] ~= P[u];
            G[P[u]] ~= u;
          }
        }
        sz = new int[N];
        dfs0(0, -1);
        ans = [];
        dfs1(0, -1);
        writeln("YES");
        foreach (u; ans) {
          writeln(u + 1);
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n; readV(n);
  int[] p; readA(n, p); p[] -= 1;

  if (n%2 == 0) {
    writeln("NO");
    return;
  }

  auto g = Graph!int(n);
  foreach (int i, pi; p)
    if (pi != -1) g.addEdgeB(i, pi);
  auto t = g.makeTree.rootify(0);

  auto c = new int[](n), qu = DList!int([0]), st = SList!int();
  while (!qu.empty) {
    auto u = qu.front; qu.removeFront();
    st.insertFront(u);
    foreach (v; t.children(u)) qu.insertBack(v);
  }
  while (!st.empty) {
    auto u = st.front; st.removeFront();
    c[u] = 1;
    foreach (v; t.children(u)) c[u] += c[v];
  }

  writeln("YES");

  st.insertFront(0);
  while (!st.empty) {
    auto u = st.front; st.removeFront();
    if (u >= n) {
      writeln(u-n+1);
      continue;
    }
    foreach (v; t.children(u).filter!(v => c[v]%2 == 1))
      st.insertFront(v);
    st.insertFront(u+n);
    foreach (v; t.children(u).filter!(v => c[v]%2 == 0))
      st.insertFront(v);
  }
}

struct Graph(N = int)
{
  alias Node = N;
  Node n;
  Node[][] g;
  alias g this;
  this(Node n) { this.n = n; g = new Node[][](n); }
  void addEdge(Node u, Node v) { g[u] ~= v; }
  void addEdgeB(Node u, Node v) { g[u] ~= v; g[v] ~= u; }
}

struct Tree(Graph)
{
  import std.algorithm, std.container;
  alias Node = Graph.Node;
  Graph g;
  alias g this;
  Node root;
  Node[] parent;
  int[] size, depth;

  this(ref Graph g) { this.g = g; this.n = g.n; }

  ref auto rootify(Node r)
  {
    this.root = r;

    parent = new Node[](g.n);
    depth = new int[](g.n);
    depth[] = -1;

    struct UP { Node u, p; }
    auto st1 = SList!UP(UP(r, r));
    auto st2 = SList!UP();
    while (!st1.empty) {
      auto up = st1.front, u = up.u, p = up.p; st1.removeFront();

      parent[u] = p;
      depth[u] = depth[p] + 1;

      foreach (v; g[u])
        if (v != p) {
          st1.insertFront(UP(v, u));
          st2.insertFront(UP(v, u));
        }
    }

    size = new int[](g.n);
    size[] = 1;

    while (!st2.empty) {
      auto up = st2.front, u = up.u, p = up.p; st2.removeFront();
      size[p] += size[u];
    }

    return this;
  }

  auto children(Node u) { return g[u].filter!(v => v != parent[u]); }
}
ref auto makeTree(Graph)(ref Graph g) { return Tree!Graph(g); }

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n; readV(n);
  int[] p; readA(n, p); p[] -= 1;

  auto g = new bool[int][](n);
  foreach (int i, pi; p)
    if (pi != -1) g[i][pi] = g[pi][i] = true;

  auto c = new bool[int][](3);

  auto degType(int u)
  {
    auto deg = g[u].length;
    if (deg == 0)        return 0;
    else if (deg%2 == 0) return 1;
    else                 return 2;

  }

  foreach (i; 0..n) c[degType(i)][i] = true;

  while (c[1].length) {
    auto u = c[1].keys.front;
    c[1].remove(u);
    foreach (v; g[u].byKey) {
      c[degType(v)].remove(v);
      g[v].remove(u);
      c[degType(v)][v] = true;
    }
  }

  writeln(c[1].length ? "NO" : "YES");
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n; readV(n);
  int[] p; readA(n, p); p[] -= 1;

  auto g = new bool[int][](n);
  foreach (int i, pi; p)
    if (pi != -1) g[i][pi] = g[pi][i] = true;

  auto c = new bool[int][](3);

  auto degType(int u)
  {
    auto deg = g[u].length;
    if (deg == 0)        return 0;
    else if (deg%2 == 0) return 1;
    else                 return 2;

  }

  foreach (i; 0..n) c[degType(i)][i] = true;

  while (c[1].length) {
    auto u = c[1].keys.front;
    writeln(u);
    c[1].remove(u);
    foreach (v; g[u].byKey) {
      c[degType(v)].remove(v);
      g[v].remove(u);
      c[degType(v)][v] = true;
    }
  }

  writeln(c[1].length ? "NO" : "YES");
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n; readV(n);
  int[] p; readA(n, p); p[] -= 1;

  auto g = new bool[int][](n);
  foreach (int i, pi; p)
    if (pi != -1) g[i][pi] = g[pi][i] = true;

  auto c = new bool[int][](3);

  auto degType(int u)
  {
    auto deg = g[u].length;
    if (deg == 0)        return 0;
    else if (deg%2 == 0) return 1;
    else                 return 2;

  }

  foreach (i; 0..n) c[degType(i)][i] = true;

  int[] r;
  while (c[1].length) {
    auto u = c[1].keys.front;
    r ~= u;
    c[1].remove(u);
    foreach (v; g[u].byKey) {
      c[degType(v)].remove(v);
      g[v].remove(u);
      c[degType(v)][v] = true;
    }
  }

  if (c[2].length) {
    writeln("NO");
  } else {
    writeln("YES");
    foreach (ri; r) writeln(ri+1);
    foreach (u; c[0].byKey) writeln(u+1);
  }
}


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;

void main() {
    auto T = readln.chomp.to!int;
    while (T--) {
        auto S = readln.chomp;
        auto N = S.length.to!int;
        auto U = S.count('U').to!int;
        auto D = S.count('D').to!int;
        auto L = S.count('L').to!int;
        auto R = S.count('R').to!int;
        auto x = min(U, D);
        auto y = min(L, R);
        auto ans = new dchar[](x + y + x + y);
        if (x == 0 && y == 0) {
            0.writeln;
            writeln;
        } else if (x == 0) {
            2.writeln;
            "LR".writeln;
        } else if (y == 0) {
            2.writeln;
            "UD".writeln;
        } else {
            foreach (i; 0..x+x+y+y) {
                if (i < x) ans[i] = 'U';
                else if (i < x + y) ans[i] = 'L';
                else if (i < 2 * x + y) ans[i] = 'D';
                else ans[i] = 'R';
            }
            ans.length.writeln;
            ans.writeln;
        }
    }
}

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
void main()
{
  int q; get(q);
  while(q--)
    {
      int[4] count = 0;
      string str; get(str);
      foreach(c; str)
	{
	  switch(c)
	    {
	    case 'L':
	      count[0]++;
	      break;
	    case 'R':
	      count[1]++;
	      break;
	    case 'U':
	      count[2]++;
	      break;
	    case 'D':
	      count[3]++;
	      break;
	    default:
	      assert(0);
	    }
	}
      int l = min(count[0], count[1]);
      int r = min(count[2], count[3]);
      if(l == 0 && r > 1)
	{
	  r = 1;
	}
      if(l > 1 && r == 0)
	{
	  l = 1;
	}
      wr(2 * (l + r));
      foreach(i; 0 .. r)
	write('U');
      foreach(i; 0 .. l)
	write('R');
      foreach(i; 0 .. r)
	write('D');
      foreach(i; 0 .. l)
	write('L');
      if(l + r)
	writeln;
    }
}

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(){
	int q = rint;
	foreach(_; 0 .. q){
		string s = rstring;
		int[char] cnt = ['L': 0, 'R': 0, 'U': 0, 'D': 0];
		foreach(c; s) cnt[c] += 1;

		int x = min(cnt['L'], cnt['R']), y = min(cnt['U'], cnt['D']);
		if(x == 0 && y >= 2) y = 1;
		if(y == 0 && x >= 2) x = 1;
		(x + x + y + y).writeln;
		foreach(i; 0 .. x) "L".write;
		foreach(j; 0 .. y) "U".write;
		foreach(i; 0 .. x) "R".write;
		foreach(j; 0 .. y) "D".write;
		writeln;

	}
}

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 main()
{
	auto q = RD!int;
	auto ans = new string[](q);
	foreach (i; 0..q)
	{
		auto s = RD!string;
		long cnt_u, cnt_d, cnt_l, cnt_r;
		foreach (c; s)
		{
			if (c == 'U')
				++cnt_u;
			else if (c == 'D')
				++cnt_d;
			else if (c == 'L')
				++cnt_l;
			else
				++cnt_r;
		}
		auto y = min(cnt_u, cnt_d);
		auto x = min(cnt_l, cnt_r);
		if (y == 0)
			x.chmin(1);
		else if (x == 0)
			y.chmin(1);
		foreach (_; 0..y)
			ans[i] ~= 'U';
		foreach (_; 0..x)
			ans[i] ~= 'R';
		foreach (_; 0..y)
			ans[i] ~= 'D';
		foreach (_; 0..x)
			ans[i] ~= 'L';
	}

	foreach (e; ans)
	{
		writeln(e.length);
		writeln(e);
	}
	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 main()
{
	auto q = RD!int;
	auto ans = new string[](q);
	foreach (i; 0..q)
	{
		auto s = RD!string;
		long cnt_u, cnt_d, cnt_l, cnt_r;
		foreach (c; s)
		{
			if (c == 'U')
				++cnt_u;
			else if (c == 'D')
				++cnt_d;
			else if (c == 'L')
				++cnt_l;
			else
				++cnt_r;
		}
		auto y = min(cnt_u, cnt_d);
		auto x = min(cnt_l, cnt_r);
		if (y == 0)
			x.chmin(1);
		else if (x == 1)
			y.chmin(1);
		foreach (_; 0..y)
			ans[i] ~= 'U';
		foreach (_; 0..x)
			ans[i] ~= 'R';
		foreach (_; 0..y)
			ans[i] ~= 'D';
		foreach (_; 0..x)
			ans[i] ~= 'L';
	}

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


import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    int N, K; scanf("%d %d\n", &N, &K);
    auto xs = readln.chomp.split(" ").map!(to!int).array;

    K--;

    int a = xs[K];
    bool check() {
        foreach (x; xs[K .. $]) {
            if (a != x) return false;
        }
        return true;
    }
    if (!check()) {
        writeln(-1); return;
    }

    auto ys = xs[0 .. K];
    int c = 0;
    for (int i = K - 1; i >= 0; i--) {
        if (ys[i] == a) c++;
        else break;
    }
    /*
    writeln([c]);
    writeln([N, K]);
    writeln(xs);
    writeln(ys);
    */
    writeln(K - c);

}


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

void main()
{
    auto N = readln.chomp.to!int;
    auto CS = readln.split.to!(int[]);
    int[][] T;
    T.length = N;
    foreach (_; 0..N-1) {
        auto ab = readln.split.to!(int[]);
        auto a = ab[0]-1;
        auto b = ab[1]-1;
        T[a] ~= b;
        T[b] ~= a;
    }

    auto MD = new int[](N);
    int paint(int i, int p) {
        auto d = CS[i] ? 1 : -1;
        foreach (j; T[i]) if (j != p) d += max(0, paint(j, i));
        MD[i] = d;
        return d;
    }
    paint(0, -1);
    void solve(int i, int p) {
        if (p >= 0) {
            if (CS[i]) {
                MD[i] = max(MD[i], MD[p]);
            } else if (MD[i] <= 0) {
                MD[i] = max(MD[i], MD[p] + MD[i]);
            } else {
                MD[i] = max(MD[i], MD[p]);
            }
        }
        foreach (j; T[i]) if (j != p) solve(j, i);
    }
    solve(0, -1);

    writeln(MD.to!(string[]).join(" "));
}

import std.array;
import std.stdio;
import std.string;
import std.range;
import std.conv;
import std.algorithm.iteration;
import std.algorithm.comparison;

void main(string[] args)
{
  auto inf = cast(int) float.infinity;
  const int n = to!int(readln().chomp());
  auto white = stdin.readln().split().map!(to!int);
  auto score = array((-inf).repeat(n+1));
  score[0] = 0;
  int[][] adj;
  adj.length = n+1;

  int u, v;
  for (int i=1; i<n; i++) {
    stdin.readf!"%d %d\n"(u, v);
    adj[u] ~= v;
    adj[v] ~= u;
  }

  void dfs(int i, int parent) {
    score[i] = white[i-1] ? 1 : -1;
    foreach (child; adj[i])
    {
      if (child == parent) continue;
      dfs(child, i);
      score[i] = max(score[i], score[i] + score[child]);
    }
  }
  dfs(1, 0);

  void dfs2(int i, int parent) {
    score[i] = max(score[i], score[parent] + min(0, score[i]));
    foreach (child; adj[i])
    {
      if (child == parent) continue;
      dfs2(child, i);
    }
  }
  dfs2(1, 0);

  writeln(score[1..$].map!(to!string).joiner(" "));
}

import std.array;
import std.stdio;
import std.string;
import std.range;
import std.conv;
import std.algorithm.iteration;
import std.algorithm.comparison;

void main(string[] args)
{
  auto inf = cast(int) float.infinity;
  const int n = to!int(readln().chomp());
  auto white = stdin.readln().split().map!(to!int);
  auto score = array((-inf).repeat(n+1));
  score[0] = 0;
  int[][] adj;
  adj.length = n+1;

  int u, v;
  for (int i=1; i<n; i++) {
    stdin.readf!"%d %d\n"(u, v);
    adj[u] ~= v;
    adj[v] ~= u;
  }
  writeln(adj);

  void dfs(int i, int parent) {
    score[i] = white[i-1] ? 1 : -1;
    foreach (child; adj[i])
    {
      if (child == parent) continue;
      dfs(child, i);
      score[i] = max(score[i], score[i] + score[child]);
    }
  }
  dfs(1, 0);
  writeln(score);

  void dfs2(int i, int parent) {
    score[i] = max(score[i], score[parent] + min(0, score[i]));
    foreach (child; adj[i])
    {
      if (child == parent) continue;
      dfs2(child, i);
    }
  }
  dfs2(1, 0);

  writeln(score[1..$].map!(to!string).joiner(" "));
}

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

void main()
{
    auto N = readln.chomp.to!int;
    auto CS = readln.split.to!(int[]);
    int[][] T;
    T.length = N;
    foreach (_; 0..N-1) {
        auto ab = readln.split.to!(int[]);
        auto a = ab[0]-1;
        auto b = ab[1]-1;
        T[a] ~= b;
        T[b] ~= a;
    }

    auto MD = new int[](N);
    int paint(int i, int p) {
        int d = CS[i] ? 1 : -1;
        foreach (j; T[i]) if (j != p) d += max(0, paint(j, i));
        MD[i] = d;
        return d;
    }
    paint(0, -1);
    void solve(int i, int p) {
        if (p >= 0) {
            if (CS[i]) {
                MD[i] = max(MD[i], MD[p]);
            } else {
                MD[i] += MD[p];
            }
        }
        foreach (j; T[i]) if (j != p) solve(j, i);
    }
    solve(0, -1);

    writeln(MD.to!(string[]).join(" "));
}


import std.stdio;
import std.array : appender, array;
import std.algorithm : min;
import std.algorithm.iteration : cumulativeFold;
import std.algorithm.sorting : sort;
import std.range : chain, only;

void main()
{
  int n, k;
  readf!"%d %d\n"(n, k);

  auto books_ab = appender!(long[]);
  auto books_a = appender!(long[]);
  auto books_b = appender!(long[]);

  books_ab.reserve(n);
  books_a.reserve(n);
  books_b.reserve(n);

  foreach (i; 0..n) {
    int ti, a, b;
    readf!"%d %d %d\n"(ti, a, b);

    if (a == 1 && b == 1) {
      books_ab.put(ti);
    } else if (a == 1) {
      books_a.put(ti);
    } else if (b == 1) {
      books_b.put(ti);
    }
  }

  // maximum number of non-shared books we can use
  auto mk = min(k, books_a[].length, books_b[].length);

  if (mk + books_ab[].length < k) {
    writeln(-1);
    return;
  }

  // prefix sums
  auto ab = chain(only(0L), books_ab[].sort.cumulativeFold!"a + b").array;
  auto sa = chain(only(0L), books_a[].sort.cumulativeFold!"a + b").array;
  auto sb = chain(only(0L), books_b[].sort.cumulativeFold!"a + b").array;

  // initial value: take mk from each A and B (no shared)
  long t = -1;

  // loop over number to take from shared list
  foreach (i; k - mk..min(k, books_ab[].length) + 1) {
    long s = ab[i] + sa[k-i] + sb[k-i];

    if (t == -1) t = s;
    t = min(s, t);
  }

  writeln(t);
}

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

immutable int infinity = int.max / 2;

void main ()
{
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		auto v = new int [] [4];
		foreach (i; 0..n)
		{
			int t, a, b;
			readf !(" %s %s %s") (t, a, b);
			v[a * 2 + b] ~= t;
		}
		foreach (j; 0..4)
		{
			sort (v[j]);
			v[j] ~= infinity;
		}
		int res = 0;
		bool ok = true;
		foreach (r; 0..k)
		{
			auto x = v[3].front;
			auto y = v[1].front + v[2].front;
			if (x >= infinity && y >= infinity)
			{
				ok = false;
			}
			else if (x < y)
			{
				res += x;
				v[3].popFront ();
			}
			else
			{
				res += y;
				v[1].popFront ();
				v[2].popFront ();
			}
		}
		writeln (ok ? res : -1);
	}
}

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

alias type = single;
struct TestCase
{
  mixin prettyPrinting;

  long n, k;
  @Dim("n") Tuple!(long, long, long)[] books;

  void solve(long tc = -1)
  {
    long[] as, bs, abs;
    foreach(book; books)
      {
        if (book[1] && book[2])
          abs ~= book[0];
        else if (book[1])
          as ~= book[0];
        else if (book[2])
          bs ~= book[0];
      }
    if (min(as.length, bs.length) + abs.length < cast(size_t) k)
      {
        writeln(-1);
        return;
      }
    sort(as); sort(bs); sort(abs);
    long[] acca = new long[as.length + 1]
      , accb = new long[bs.length + 1]
      , accab = new long[abs.length + 1];
    foreach(i, v; as) acca[i + 1] = acca[i] + as[i];
    foreach(i, v; bs) accb[i + 1] = accb[i] + bs[i];
    foreach(i, v; abs) accab[i + 1] = accab[i] + abs[i];
    long m = long.max;
    foreach(i, v; accab)
      {
        if (i > k)
          break;
        if (min(as.length, bs.length) >= k - i)
          {
            m = min(m, v + acca.at(k - i) + accb.at(k - i));
          }
      }
    writeln(m);
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(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);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(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)
{
  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;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

import std.stdio;
import std.array : appender, array;
import std.algorithm : min;
import std.algorithm.iteration : cumulativeFold;
import std.algorithm.sorting : sort;
import std.range : chain, only;

void main()
{
  int n, k;
  readf!"%d %d\n"(n, k);

  auto books_ab = appender!(long[]);
  auto books_a = appender!(long[]);
  auto books_b = appender!(long[]);

  books_ab.reserve(n);
  books_a.reserve(n);
  books_b.reserve(n);

  foreach (i; 0..n) {
    int ti, a, b;
    readf!"%d %d %d\n"(ti, a, b);

    if (a == 1 && b == 1) {
      books_ab.put(ti);
    } else if (a == 1) {
      books_a.put(ti);
    } else if (b == 1) {
      books_b.put(ti);
    }
  }

  // maximum number of non-shared books we can use
  auto mk = min(k, books_a[].length, books_b[].length);

  // prefix sums
  auto ab = chain(only(0L), books_ab[].sort.cumulativeFold!"a + b").array;
  auto sa = chain(only(0L), books_a[].sort.cumulativeFold!"a + b").array;
  auto sb = chain(only(0L), books_b[].sort.cumulativeFold!"a + b").array;

  // initial value: take mk from each A and B (no shared)
  long t = -1;

  // loop over number to take from shared list
  foreach (i; k - mk..min(k, books_ab[].length) + 1) {
    long s = ab[i] + sa[k-i] + sb[k-i];

    if (t == -1) t = s;
    t = min(s, t);
  }

  writeln(t);
}


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)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto next = int.max;
		bool ok = true;
		int res = 0;
		foreach_reverse (ref c; a)
		{
			while (c > 0 && c >= next)
			{
				res += 1;
				c /= 2;
			}
			if (c >= next)
			{
				ok = false;
			}
			next = c;
		}
		writeln (ok ? res : -1);
	}
}

// cheese-cracker [2022-05-05]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    long res = 0;
    for(int i = n-2; i >= 0; --i){
        long prev = arr[i+1];
        while(arr[i] > 0 && arr[i] >= prev){
            arr[i] /= 2;
            ++res;
        }
        if(arr[i] >= prev){
            writeln(-1);
            return;
        }
    }
    writeln(res);
}

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

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm;
import std.container, std.math, std.numeric, std.functional;
string[] tk; alias tup = Tuple!(long, long);
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; } }


import std.stdio;
import std.algorithm;

void main(string[] args)
{
    //stdin = File("input.txt", "r");

    auto T = readln().strip('\n');
    auto S = readln().strip('\n');

    int count = 0;
    for (int i = 0; i + S.length <= T.length; ++i) {
        if (T[i..i+S.length] == S) {
            ++count;
            i = cast(int)(i + S.length - 1);
        }
    }
    writeln(count);
}

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

bool isPrefixOf(string x, string y){
    if (x.length > y.length) return false;
    bool res = true;
    for(int i;i<x.length;i++){
        res = res && x[i] == y[i];
    }
    return res;
}

void main(){
    string x = readln.chomp;
    string y = readln.chomp;

    int res = 0;

    for(int i=0; i < x.length;){
        if (isPrefixOf(y,x[i..$])){
            res++;
            i += y.length;
        } else {
            i++;
        }
    }

    writeln(res);
}

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

bool isPrefixOf(string x, string y){
    if (x.length > y.length) return false;
    bool res = true;
    for(int i;i<x.length;i++){
        res = res && x[i] == y[i];
    }
    return res;
}

void main(){
    string x = readln.chomp;
    string y = readln.chomp;

    int res = 0;

    for(int i=0; i < x.length; i++){
        if (isPrefixOf(y,x[i..$])){
            res++;
        }
    }

    writeln(res);
}

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

void main(){
    string x = readln.chomp;
    string y = readln.chomp;

    int res = 0;

    for(int i=0; i < x.length-y.length;){
        bool acc = true;
        int k = i;
        for(int j=0; j < y.length; j++, k++){
            acc = acc && x[k] == y[j];
        }
        if (acc){
            i = k;
            res++;
        } else {
            i++;
        }
    }

    writeln(res);
}

import std.stdio;
import std.algorithm;

void main(string[] args)
{
    //stdin = File("input.txt", "r");

    auto T = readln().strip('\n');
    auto S = readln().strip('\n');
    writeln(T);
    writeln(S);

    int count = 0;
    for (int i = 0; i <= T.length - S.length; ++i) {
        if (T[i..i+S.length] == S) {
            ++count;
            i = cast(int)(i + S.length - 1);
        }
    }
    writeln(count);
}