import std.stdio;
import std.bigint;
import std.container;
import std.array;
import std.algorithm;
import std.conv;
import std.bitmanip;
import std.functional;
import std.math;
import std.numeric;
import std.string;
import std.range;
import std.uni;
import std.complex;
import std.typecons;
import core.stdc.stdio:freopen;
import core.bitop;
import std.regex;
import std.complex;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
immutable int mod=1000000007;
pure nothrow @safe X binpow(X,Y)(X base,Y exp)
if(!is(Y==float) && !is(Y==real) && !is(Y==double))
{
	if(exp<0)return X(0);
	X res=X(1);
	while(exp>0)
	{
		if(exp&1)res*=base;
		base*=base;
		exp>>=1;
	}
	return res;
}
pure nothrow @safe auto binpow(X,Y,Z)(X base,Y exp,in Z mm)
if(!is(Y==float) && !is(Y==real) && !is(Y==double))
{
	if(mm==0) return binpow(base,exp);
	if(exp<0)return X(0);
	auto res=X(1)%mm;
	while(exp>0)
	{
		if(exp&1)res=(res*base)%mm;
		base*=base;
		base%=mm;
		exp>>=1;
	}
	return res;
}
@safe @property void putarr(X)(X a,in char ch=' ')
{
	foreach(const ref i;a)write(i,ch);
}
@safe @property void putarr(X)(X[][] a)
{
	foreach(i;0..a.length)
	{
		foreach(j;0..a[i].length)write(a[i][j],' ');
		writeln;
	}
}
void getarr(X)(X a,in int n)
{
	foreach(ref i;a[0..n])input(&i);
}
auto arread(T)()
{
	return readln.split.map!(to!(T)).array;
}
bool input(T...)(T ptrs) if (ptrs.length > 0) {
	return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;
}
struct pair(X,Y)
{
	X fi;
	Y se;
	this(X a_,Y b_){
		fi=a_;
		se=b_;
		}
	this(this){fi=fi;se=se;}
	int opCmp(ref const pair!(X,Y) s_) const pure nothrow
	{
		int cmp=0-(fi<s_.fi)+(fi>s_.fi);
		if(cmp!=0)return cmp;
		else return (0-(se<s_.se)+(se>s_.se));
	}
};
pair!(X,Y) mp(X,Y)(X x_,Y y_) pure nothrow
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
X sqr(X)(X a_) pure nothrow @safe @property @nogc
{
	return a_*a_;
}
X cub(X)(X a_) pure nothrow @safe @property @nogc
{
	return a_*a_*a_;
}
alias pair!(int,int) pii;
alias pair!(long,long) pll;
void inf(in char* name) nothrow @nogc @system
{
	freopen(name,"r",core.stdc.stdio.stdin);
}
void ouf(in char* name) nothrow @nogc @system
{
	freopen(name,"w",core.stdc.stdio.stdout);
}
//split strip readln equalRange upperBound lowerBound string wstring
//dstring ulong wchar dchar array uint foreach_reverse find count false
//nextPermutation isSorted fill reverse swap size_t clear empty insert
//front back remove hypot sqrt round continue swapRanges minPos maxPos
//break goto switch boyerMooreFinder minElement maxElement heapify true
//static multiSort schwartzSort partialSort merge uniq joiner filter
//cumulativeFold fold each sort isAlpha isNumber isWhite isLower isUpper
//toLower toUpper mixin
int[1000][1000] t,a,b;
void main()
{
	int n,m;
	input(&n,&m);
	foreach(i;0..n) foreach(j;0..m){input(&t[i][j]);a[i][j]=b[i][j]=t[i][j];}

	foreach(i;0..n)
	{
		foreach(j;1..m)a[i][j]+=a[i][j-1];
	}
	foreach(i;0..m)
	{
		foreach(j;1..n)b[j][i]+=b[j-1][i];
	}
	int ans=0;
	for(int i=0;i<n;i++)for(int j=0;j<m;j++)
	{
		if(t[i][j]==0)
		{
			if(a[i][j]>0)ans++;
			if(b[i][j]>0)ans++;
			if(a[i][j]<a[i][m-1])ans++;
			if(b[i][j]<b[n-1][j])ans++;
		}

	}
	writeln(ans);
}

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

__gshared:

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

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

int n, m;
bool[1000][1000][2] a;

inout(bool)[ ][3] findTrue(inout(bool)[ ] a) {
    int i = 0, j = cast(int)a.length;
    while (i < a.length && !a[i])
        i++;
    while (j > i && !a[j - 1])
        j--;
    return [a[0 .. i], a[i .. j], a[j .. $]];
}

void main() {
    while (read(&n, &m)) {
        foreach (i, ref row; a[0][0 .. n])
            foreach (j, ref elem; row[0 .. m]) {
                char c;
                read(&c);
                elem = a[1][j][i] = c == '1';
            }
        int result = 0;
        foreach (ref row; a[0][0 .. n]) {
            auto t = findTrue(row[0 .. m]);
            if (!t[1].empty) {
                result += t[0].count(false);
                result += t[1].count(false) << 1;
                result += t[2].count(false);
            }
        }
        foreach (ref row; a[1][0 .. m]) {
            auto t = findTrue(row[0 .. n]);
            if (!t[1].empty) {
                result += t[0].count(false);
                result += t[1].count(false) << 1;
                result += t[2].count(false);
            }
        }
        writeln(result);
    }
}


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

immutable int NA = -1;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		auto a = new int [] [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			a[u] ~= v;
			a[v] ~= u;
		}

		alias Depth = Tuple !(int, q{depth}, int, q{num});
		auto d = new Depth [n];

		alias Record =
		    Tuple !(int, q{depth}, int, q{next}, int, q{num});
		auto c = new Record [] [n];

		void recur1 (int v, int p)
		{
			auto res = Depth (0, v);
			foreach (u; a[v]) if (u != p)
			{
				recur1 (u, v);
				res = max (res,
				    Depth (d[u].depth + 1, d[u].num));
				c[v] ~= Record (d[u].depth + 1, u, d[u].num);
			}
			d[v] = res;
			sort !(q{a > b}) (c[v]);
			c[v] ~= Record (0, NA, NA);
			c[v] ~= Record (0, NA, NA);
			c[v] ~= Record (0, NA, NA);
		}

		recur1 (0, NA);

		int x = NA;
		int y = NA;
		int z = NA;
		int answer = 0;

		void recur2 (int v, int p, Record h)
		{
			int cur = h.depth + c[v][0].depth + c[v][1].depth;
			if (answer < cur)
			{
				answer = cur;
				x = h.num;
				y = c[v][0].num;
				z = c[v][1].num;
			}

			int alt = c[v][0].depth + c[v][1].depth + c[v][2].depth;
			if (answer < alt)
			{
				answer = alt;
				x = c[v][0].num;
				y = c[v][1].num;
				z = c[v][2].num;
			}

			foreach (u; a[v]) if (u != p)
			{
				int i = 0;
				if (c[v][i].next == u)
				{
					i += 1;
				}
				auto t = max (h, c[v][i]);
				t.depth += 1;
				recur2 (u, v, t);
			}
		}

		recur2 (0, NA, Record (0, 0, 0));

		if (x > y) swap (x, y);
		if (y > z) swap (y, z);
		if (x > y) swap (x, y);

		while (y == NA || y == x || y == z)
		{
			y += 1;
		}

		while (x == NA || x == y || x == z)
		{
			x += 1;
		}

		writeln (answer);
		writeln (x + 1, " ", y + 1, " ", z + 1);
	}
}

import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.typecons;
import std.algorithm.mutation;
import std.algorithm.searching;

string[] tokens;
string readToken()
{
    while (tokens.empty)
    {
        tokens = readln.split;
    }
    auto token = tokens.front;
    tokens.popFront;
    return token;
}

int readInt()
{
    return readToken.to!int;
}

const int N = 200000;

int n;
Array!int[N] tree;

int[] bfs(int s)
{
    int[] dist = new int[n];
    fill(dist, -1);
    dist[s] = 0;
    int[] queue = new int[n];
    int rear = 0;
    queue[rear++] = s;
    for (int head = 0; head < rear; ++head)
    {
        int u = queue[head];
        foreach (v; tree[u])
        {
            if (dist[v] == -1)
            {
                dist[v] = dist[u] + 1;
                queue[rear++] = v;
            }
        }
    }
    return dist;
}

int argmax(int[] dist)
{
    return cast(int) dist.enumerate.maxElement!"a.value"[0];
}

auto solve()
{
    int x = argmax(bfs(0));
    int[] dx = bfs(x);
    int y = argmax(dx);
    int diameter = dx[y];
    int[] dy = bfs(y);
    if (diameter == n - 1)
    {
        int z = 0;
        while (z == x || z == y)
        {
            z++;
        }
        return tuple(n - 1, x, y, z);
    }
    int z = n.iota.maxElement!((z) => dx[z] + dy[z]);
    return tuple(dx[z] + dy[z] + diameter >> 1, x, y, z);
}

void main()
{
    n = readInt;
    for (int i = 0; i < n - 1; ++i)
    {
        int a = readInt - 1;
        int b = readInt - 1;
        tree[a].insert(b);
        tree[b].insert(a);
    }
    auto res = solve();
    writeln(res[0]);
    writeln(res[1] + 1, " ", res[2] + 1, " ", res[3] + 1);
}

import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.typecons;
import std.algorithm.mutation;
import std.algorithm.searching;

string[] tokens;
string readToken()
{
    while (tokens.empty)
    {
        tokens = readln.split;
    }
    auto token = tokens.front;
    tokens.popFront;
    return token;
}

int readInt()
{
    return readToken.to!int;
}

const int N = 200000;

int n;
Array!int[N] tree;

int[] bfs(int s)
{
    int[] dist = new int[n];
    fill(dist, -1);
    dist[s] = 0;
    int[] queue = new int[n];
    int rear = 0;
    queue[rear++] = s;
    for (int head = 0; head < rear; ++head)
    {
        int u = queue[head];
        foreach (v; tree[u])
        {
            if (dist[v] == -1)
            {
                dist[v] = dist[u] + 1;
                queue[rear++] = v;
            }
        }
    }
    return dist;
}

int argmax(int[] dist)
{
    return cast(int) dist.enumerate.maxElement!"a.value"[0];
}

auto solve()
{
    int x = argmax(bfs(0));
    int[] dx = bfs(x);
    int y = argmax(dx);
    int diameter = dx[y];
    int[] dy = bfs(y);
    if (diameter == n - 1)
    {
        int z = 0;
        while (z == x || z == y)
        {
            z++;
        }
        return tuple(n - 1, x, y, z);
    }
    int z = n.iota.maxElement!((z) => dx[z] + dy[z]);
    return tuple(dx[z] + dy[z] - diameter, x, y, z);
}

void main()
{
    n = readInt;
    for (int i = 0; i < n - 1; ++i)
    {
        int a = readInt - 1;
        int b = readInt - 1;
        tree[a].insert(b);
        tree[b].insert(a);
    }
    auto res = solve();
    writeln(res[0]);
    writeln(res[1] + 1, " ", res[2] + 1, " ", res[3] + 1);
}


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

void solve(int n)
{
    if (n == 1)
    {
        writeln(0);
        return;
    }
    auto f = new bool[n + 1];
    fill(f, false);
    int[] s;
    foreach (i; 2 .. n + 1)
    {
        if (!f[i])
        {
            for (int j = i; j <= n; j *= i)
            {
                s ~= j;
            }
            for (int j = i * i; j <= n; j += i)
            {
                f[j] = true;
            }
        }
    }
    writeln(s.length);
    foreach (i; 0 .. s.length - 1)
    {
        write(s[i], " ");
    }
    writeln(s[s.length - 1]);
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        solve(n);
    }
    return 0;
}

import std.algorithm;
import std.conv;
import std.numeric;
import std.stdio;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int [] a;
		auto b = new bool [n + 1];
		b[] = true;
		for (int i = 2; i <= n; i++) if (b[i])
		{
			for (int j = i; j <= n; j *= i)
			{
				a ~= j;
			}
			for (int j = i * i; j <= n; j += i)
			{
				b[j] = false;
			}
		}
		writeln (a.length);
		writefln ("%(%s %)", a);
	}
}


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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const S = readToken();
        const N = cast(int)(S.length);

        auto s = S.dup;

        int[] anss;
        foreach (i; 0 .. N - 5 + 1) {
          if (s[i .. i + 5] == "twone") {
            anss ~= i + 2;
            s[i + 2] = '!';
          }
        }
        debug {
          writeln("s = ", s);
        }
        foreach (i; 0 .. N - 3 + 1) {
          if (s[i .. i + 3] == "one" || s[i .. i + 3] == "two") {
            anss ~= i + 1;
          }
        }

        writeln(anss.length);
        int ou;
        foreach (i; anss) {
          if (ou++) write(" ");
          write(i + 1);
        }
        writeln();
      }
    }
  } catch (EOFException e) {
  }
}

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 t = RD!int;
	auto ans = new size_t[][](t);
	foreach (ti; 0..t)
	{
		auto s = RD!string;
		if (s.length < 3) continue;
		foreach (i; 2..s.length)
		{
			if (s[i-2..i+1] == "one")
			{
				if (i >= 4)
				{
					if (s[i-4..i+1] == "twone")
					{
						++ans[ti][$-1];
						continue;
					}
				}
				ans[ti] ~= i;
			}
			else if (s[i-2..i+1] == "two")
			{
				ans[ti] ~= i;
			}
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
		{
			writeln(0);
			writeln;
		}
		else
		{
			writeln(e.length);
			e.map!(to!string).join(" ").writeln;
		}
	}
	stdout.flush;
	debug readln;
}


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

immutable int INF = 10 ^^ 9 + 23;

void main()
{
    int[2] ns;
    int[][2] arr;

    foreach (i; 0 .. 2) {
        readf("%s", &ns[i]);
        readln;
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    Tuple!(int, char)[] ans;
    int i = ns[0] - 1, gidx = ns[1]-1;
    for ( ; i >= 0 && gidx >= 0; ) {
        int cursm = 0;
        int j = i;
        while (j >= 0 && cursm < arr[1][gidx]) {
            cursm += arr[0][j];
            j -= 1;
        }

        debug { writeln(j+1, ' ', i, ' ', cursm, ' ', arr[1][gidx]); }

        if (cursm > arr[1][gidx]) {
            writeln("NO");
            return;
        }

        int mx = arr[0][j+1 .. i+1].maxElement;
        int mn = arr[0][j+1 .. i+1].minElement;
        if (i - j > 1 && mx == mn) {
            writeln("NO");
            return;
        }

        int start = j+1;
        for (int k = j+1; k <= i; ++k) {
            if (arr[0][k] != mx) { continue; }
            if ((k > j+1 && arr[0][k-1] < mx) || (k < i && arr[0][k+1] < mx)) {
                start = k;
                break;
            }
        }

        int curidx = start + 1;
        int cursz = arr[0][start];
        int lb = start-1, rb = start+1;
        while (lb > j || rb <= i) {
            if (lb > j && arr[0][lb] < cursz) {
                cursz += arr[0][lb];
                ans ~= tuple(curidx, 'L');
                curidx -= 1;
                lb -= 1;
            } else {
                cursz += arr[0][rb];
                ans ~= tuple(curidx, 'R');
                rb += 1;
            }
        }

        i = j;
        gidx -= 1;
    }

    if (i >= 0 || gidx >= 0) {
        writeln("NO");
        return;
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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

immutable int INF = 10 ^^ 9 + 23;

void main()
{
    int[2] ns;
    int[][2] arr;

    foreach (i; 0 .. 2) {
        readf("%s", &ns[i]);
        readln;
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    Tuple!(int, char)[] ans;
    int i = ns[0] - 1, gidx = ns[1]-1;
    for ( ; i >= 0 && gidx >= 0; ) {
        int cursm = 0;
        int j = i;
        while (j >= 0 && cursm < arr[1][gidx]) {
            cursm += arr[0][j];
            j -= 1;
        }

        debug { writeln(j+1, ' ', i, ' ', cursm, ' ', arr[1][gidx]); }

        if (cursm > arr[1][gidx]) {
            writeln("NO");
            return;
        }

        bool segAns(int le, int r) {
            if (r - le + 1 == 1) { return true; }

            int mx = arr[0][le .. r+1].maxElement;
            Nullable!int start;
            for (int k = le; k <= r; ++k) {
                if (arr[0][k] != mx) { continue; }
                if ((k > le && arr[0][k-1] < mx) || (k < r && arr[0][k+1] < mx)) {
                    start = k;
                    break;
                }
            }

            if (start.isNull) { return false; }

            int curidx = start + 1;
            int cursz = arr[0][start];
            int lb = start-1, rb = start+1;
            while (lb >= le || rb <= r) {
                if (lb >= le && arr[0][lb] < cursz) {
                    cursz += arr[0][lb];
                    ans ~= tuple(curidx, 'L');
                    curidx -= 1;
                    lb -= 1;
                } else {
                    cursz += arr[0][rb];
                    ans ~= tuple(curidx, 'R');
                    rb += 1;
                }
            }

            return true;
        }

        if (! segAns(j+1, i)) {
            writeln("NO");
            return;
        }

        i = j;
        gidx -= 1;
    }

    if (i >= 0 || gidx >= 0) {
        writeln("NO");
        return;
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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

immutable int INF = 10 ^^ 9 + 23;

void main()
{
    int[2] ns;
    int[][2] arr;

    foreach (i; 0 .. 2) {
        readf("%s", &ns[i]);
        readln;
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    Tuple!(int, char)[] ans;
    int gidx = ns[1]-1;
    for (int i = ns[0]-1; i >= 0 && gidx >= 0; ) {
        int cursm = 0;
        int j = i;
        while (j >= 0 && cursm < arr[1][gidx]) {
            cursm += arr[0][j];
            j -= 1;
        }

        debug { writeln(j+1, ' ', i, ' ', cursm, ' ', arr[1][gidx]); }

        if (cursm > arr[1][gidx]) {
            writeln("NO");
            return;
        }

        int mx = arr[0][j+1 .. i+1].maxElement;
        int mn = arr[0][j+1 .. i+1].minElement;
        if (i - j > 1 && mx == mn) {
            writeln("NO");
            return;
        }

        int start = j+1;
        for (int k = j+1; k <= i; ++k) {
            if (arr[0][k] != mx) { continue; }
            if ((k > j+1 && arr[0][k-1] < mx) || (k < i && arr[0][k+1] < mx)) {
                start = k;
                break;
            }
        }

        int curidx = start + 1;
        int cursz = arr[0][start];
        int lb = start-1, rb = start+1;
        while (lb > j || rb <= i) {
            if (lb > j && arr[0][lb] < cursz) {
                cursz += arr[0][lb];
                ans ~= tuple(curidx, 'L');
                curidx -= 1;
                lb -= 1;
            } else {
                cursz += arr[0][rb];
                ans ~= tuple(curidx, 'R');
                rb += 1;
            }
        }

        i = j;
        gidx -= 1;
    }

    if (gidx >= 0) {
        writeln("NO");
        return;
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}

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

immutable int INF = 10 ^^ 9 + 23;

void main()
{
    int[2] ns;
    int[][2] arr;

    foreach (i; 0 .. 2) {
        readf("%s", &ns[i]);
        readln;
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    Tuple!(int, char)[] ans;
    int gidx = ns[1]-1;
    for (int i = ns[0]-1; i >= 0 && gidx >= 0; ) {
        int cursm = 0;
        int j = i;
        while (j >= 0 && cursm < arr[1][gidx]) {
            cursm += arr[0][j];
            j -= 1;
        }

        debug { writeln(j+1, ' ', i, ' ', cursm, ' ', arr[1][gidx]); }

        if (cursm > arr[1][gidx]) {
            writeln("NO");
            return;
        }

        int mx = arr[0][j+1 .. i+1].maxElement;
        int mn = arr[0][j+1 .. i+1].minElement;
        if (mx == mn) {
            writeln("NO");
            return;
        }

        int start = 0;
        for (int k = j+1; k <= i; ++k) {
            if (arr[0][k] != mx) { continue; }
            if ((k > j+1 && arr[0][k-1] < mx) || (k < i && arr[0][k+1] < mx)) {
                start = k;
                break;
            }
        }

        int curidx = start + 1;
        int cursz = arr[0][start];
        int lb = start-1, rb = start+1;
        while (lb > j || rb <= i) {
            if (lb > j && arr[0][lb] < cursz) {
                ans ~= tuple(curidx, 'L');
                curidx -= 1;
                lb -= 1;
            } else {
                ans ~= tuple(curidx, 'R');
                rb += 1;
            }
        }

        i = j;
        gidx -= 1;
    }

    if (gidx >= 0) {
        writeln("NO");
        return;
    }

    writeln("YES");
    ans.each!(t => writeln(t[0], ' ', t[1]));
}


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

int rows;
int cols;

struct Board {
    bool [] [] contents;
    alias contents this;

    this (int rows, int cols) {
        contents = new bool [] [] (rows, cols);
    }
}

Board readConfig () {
    auto res = Board (rows, cols);
    foreach (row; 0..rows)
 {
        auto line = readln.strip;
        foreach (col; 0..cols)
     {
            res[row][col] = "LR".canFind (line[col]);
        }
    }
    return res;
}

Board trans (const ref Board b) {
    int rows = cast (int) b.length;
    int cols = cast (int) b.front.length;
    auto res = Board (cols, rows);
    foreach (row; 0..rows)
        foreach (col; 0..cols)
            res[col][row] = !b[row][col];
    return res;
}

auto solve (Board b) {
    bool doTrans = cols & 1;
    if (doTrans) {
        b = trans (b);
        swap (rows, cols);
    }

    int [2] [] res;
    foreach (row; 0..rows) {
        foreach (col; 0..cols) {
            if (!b[row][col]) {
                int [2] [] cur;
                int cRow = row;
                int cCol = col;
                while (true) {
                    debug {writefln
                        ("%s %s\n%(%(%6s%)\n%)",
                        cRow, cCol, b);}
                    cur ~= [cRow, cCol];
                    cCol += 1;
                    if (!b[cRow][cCol]) {
                        break;
                    }
                    debug {writefln
                        ("%s %s\n%(%(%6s%)\n%)",
                        cRow, cCol, b);}
                    cur ~= [cRow, cCol];
                    cRow += 1;
                    if (b[cRow][cCol]) {
                        break;
                    }
                }
                foreach_reverse (p; cur) {
                    res ~= p;
                    b[p[0] + 0][p[1] + 0] ^= true;
                    b[p[0] + 0][p[1] + 1] ^= true;
                    b[p[0] + 1][p[1] + 0] ^= true;
                    b[p[0] + 1][p[1] + 1] ^= true;
                }
            }
        }
    }

    if (doTrans) {
        foreach (ref p; res)
            swap (p[0], p[1]);
        swap (rows, cols);
    }
    foreach (ref p; res)
        p[] += 1;
    return res;
}

void main () {
    while (readf (" %s %s", &rows, &cols) > 0) {
        readln;
        auto a = readConfig ();
        auto b = readConfig ();
        auto x = a.solve ();
        auto y = b.solve ();
        auto ans = chain (x, y.retro).array;
        writeln (ans.length);
        writefln ("%(%(%s %)\n%)", ans);
    }
}

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

int rows;
int cols;

struct Board
{
	bool [] [] contents;
	alias contents this;

	this (int rows, int cols)
	{
		contents = new bool [] [] (rows, cols);
	}
}

Board readConfig ()
{
	auto res = Board (rows, cols);
	foreach (row; 0..rows)
	{
		auto line = readln.strip;
		foreach (col; 0..cols)
		{
			res[row][col] = "LR".canFind (line[col]);
		}
	}
	return res;
}

Board trans (const ref Board b)
{
	int rows = cast (int) b.length;
	int cols = cast (int) b.front.length;
	auto res = Board (cols, rows);
	foreach (row; 0..rows)
	{
		foreach (col; 0..cols)
		{
			res[col][row] = !b[row][col];
		}
	}
	return res;
}

auto solve (Board b)
{
	bool doTrans = cols & 1;
	if (doTrans)
	{
		b = trans (b);
		swap (rows, cols);
	}

	int [2] [] res;
	foreach (row; 0..rows)
	{
		foreach (col; 0..cols)
		{
			if (!b[row][col])
			{
				int [2] [] cur;
				int cRow = row;
				int cCol = col;
				while (true)
				{
					debug {writefln
					    ("%s %s\n%(%(%6s%)\n%)",
					    cRow, cCol, b);}
					cur ~= [cRow, cCol];
					cCol += 1;
					if (!b[cRow][cCol])
					{
						break;
					}
					debug {writefln
					    ("%s %s\n%(%(%6s%)\n%)",
					    cRow, cCol, b);}
					cur ~= [cRow, cCol];
					cRow += 1;
					if (b[cRow][cCol])
					{
						break;
					}
				}
				foreach_reverse (p; cur)
				{
					res ~= p;
					b[p[0] + 0][p[1] + 0] ^= true;
					b[p[0] + 0][p[1] + 1] ^= true;
					b[p[0] + 1][p[1] + 0] ^= true;
					b[p[0] + 1][p[1] + 1] ^= true;
				}
			}
		}
	}

	if (doTrans)
	{
		foreach (ref p; res)
		{
			swap (p[0], p[1]);
		}
		swap (rows, cols);
	}
	foreach (ref p; res)
	{
		p[] += 1;
	}
	return res;
}

void main ()
{
	while (readf (" %s %s", &rows, &cols) > 0)
	{
		readln;
		auto a = readConfig ();
		auto b = readConfig ();
		auto x = a.solve ();
		auto y = b.solve ();
		auto ans = chain (x, y.retro).array;
		writeln (ans.length);
		writefln ("%(%(%s %)\n%)", ans);
	}
}


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

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

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

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

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

immutable INF = 1_000_000_000_000_000_000;

int M, N;
long[] A, B;

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		A = new long[M];
		B = new long[N];
		foreach (i; 0 .. M) {
			A[i] = readLong;
		}
		foreach (j; 0 .. N) {
			B[j] = readLong;
		}

		A.sort();
		B.sort();
		long[] ASum = new long[M + 1];
		long[] BSum = new long[N + 1];
		foreach (i; 0 .. M) {
			ASum[i + 1] = ASum[i] + A[i];
		}
		foreach (j; 0 .. N) {
			BSum[j + 1] = BSum[j] + B[j];
		}

		long ans = INF;
		foreach (x; 1 .. M + 1) {
			if (BSum[N] > INF / x) {
				continue;
			}
			chmin(ans, ASum[M - x] + x * BSum[N]);
		}
		foreach (x; 1 .. N + 1) {
			if (ASum[M] > INF / x) {
				continue;
			}
			chmin(ans, BSum[N - x] + x * ASum[M]);
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}

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

void main ()
{
	int m, n;
	while (readf (" %s %s", &m, &n) > 0)
	{
		auto a = new int [m];
		foreach (ref x; a)
		{
			readf (" %s", &x);
		}
		auto b = new int [n];
		foreach (ref x; b)
		{
			readf (" %s", &x);
		}
		sort !("a < b", SwapStrategy.stable) (a);
		sort !("a < b", SwapStrategy.stable) (b);
		auto as = new long [m + 1];
		foreach (i; 0..m)
		{
			as[i + 1] = as[i] + a[i];
		}
		auto bs = new long [n + 1];
		foreach (i; 0..n)
		{
			bs[i + 1] = bs[i] + b[i];
		}

		long res = long.max / 4;
		foreach (i; 0..m)
		{
			if (long.max / 4 / (m - i) <= bs[n])
			{
				continue;
			}
			long cur = (m - i) * bs[n];
			cur += as[i];
			res = min (res, cur);
		}
		foreach (i; 0..n)
		{
			if (long.max / 4 / (n - i) <= as[m])
			{
				continue;
			}
			long cur = (n - i) * as[m];
			cur += bs[i];
			res = min (res, cur);
		}
		writeln (res);
	}
}

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

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

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

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

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

immutable INF = 1_000_000_000_000_000_000;

int M, N;
long[] A, B;

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		A = new long[M];
		B = new long[N];
		foreach (i; 0 .. M) {
			A[i] = readLong;
		}
		foreach (j; 0 .. N) {
			B[j] = readLong;
		}

		A.sort();
		B.sort();
		long[] ASum = new long[M + 1];
		long[] BSum = new long[N + 1];
		foreach (i; 0 .. M) {
			ASum[i + 1] = ASum[i] + A[i];
		}
		foreach (j; 0 .. N) {
			BSum[j + 1] = BSum[j] + B[j];
		}

		long ans = INF;
		foreach (x; 1 .. M + 1) {
			chmin(ans, ASum[M - x] + x * BSum[N]);
		}
		foreach (x; 1 .. N + 1) {
			chmin(ans, BSum[N - x] + x * ASum[M]);
		}

		{
			long now;
			foreach (x; 1 .. M + 1) {
				now += A[M - x] + BSum[N] - max(A[M - x], B[N - 1]);
				chmin(ans, now + ASum[M - x]);
			}
		}
		{
			long now;
			foreach (x; 1 .. N + 1) {
				now += B[N - x] + ASum[M] - max(B[N - x], A[M - 1]);
				chmin(ans, now + BSum[N - x]);
			}
		}

		writeln(ans);

	}
	} catch (EOFException) {}
}

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

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

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

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

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

immutable INF = 1_000_000_000_000_000_000;

int M, N;
long[] A, B;

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		A = new long[M];
		B = new long[N];
		foreach (i; 0 .. M) {
			A[i] = readLong;
		}
		foreach (j; 0 .. N) {
			B[j] = readLong;
		}

		A.sort();
		B.sort();
		long[] ASum = new long[M + 1];
		long[] BSum = new long[N + 1];
		foreach (i; 0 .. M) {
			ASum[i + 1] = ASum[i] + A[i];
		}
		foreach (j; 0 .. N) {
			BSum[j + 1] = BSum[j] + B[j];
		}

		long ans = INF;
		foreach (x; 1 .. M + 1) {
			chmin(ans, x * ASum[M - x] + x * BSum[N]);
		}
		foreach (x; 1 .. N + 1) {
			chmin(ans, x * BSum[N - x] + x * ASum[M]);
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}


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

int main(string[] args)
{
    auto t = to!int(readln.strip);
    foreach (_; 0 .. t)
    {
        auto n = to!int(readln.strip);
        auto left = 1, right = n;
        while (left < right)
        {
            auto mid = (left + right) >> 1;
            writeln("? ", left, " ", mid);
            stdout.flush;
            auto r = map!(to!int)(readln.strip.split(" ")).array;
            int c, i, j = left;
            while (i < r.length && j <= mid)
            {
                if (r[i] < j) ++ i;
                else if (r[i] > j) j = r[i];
                else ++ i, ++ j, ++ c;
            }
            if (c & 1) right = mid;
            else left = mid + 1;
        }
        writeln("! ", left);
        stdout.flush;
    }
    return 0;
}

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

alias ll = ulong;
void solve()
{
    int[][Tuple!(immutable ll, immutable ll)] mp;
    auto get = (immutable ll l, immutable ll r) {
        auto tup = tuple(l, r);
        if (auto val = tup in mp)
            return *val;
        writefln!("? %s %s")(l, r);
        stdout.flush;
        return mp[tup] = readln.splitter.map!(to!int).array;
    };

    ll n;
    readf!(" %s")(n);
    readln;
    ll l = 1, r = n;
    while (l <= r)
    {
        ll mid = (l + r) / 2;
        auto swaps = get(l, mid).count!(x => l <= x && x <= mid);
        if (swaps % 2 == 0)
            l = mid + 1;
        else
            r = mid - 1;
    }
    writefln!("! %s")(l);
    stdout.flush;
}

void main()
{
    size_t TC = 1;
    TC = readln.strip.to!int;
    foreach (_; 0 .. TC)
        solve();
}

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

alias ll = ulong;
void solve()
{
    auto get = (ll l, ll r) {
        writefln!("? %s %s")(l, r);
        stdout.flush;
        return readln.splitter.map!(to!int);
    };

    ll n;
    readf!(" %s")(n);
    readln;
    ll l = 1, r = n;
    while (l <= r)
    {
        ll mid = (l + r) / 2;
        auto swaps = get(l, mid).count!(x => l <= x && x <= mid);
        if (swaps % 2 == 0)
            l = mid + 1;
        else
            r = mid - 1;
    }
    writefln!("! %s")(l);
    stdout.flush;
}

void main()
{
    size_t TC = 1;
    TC = readln.strip.to!int;
    foreach (_; 0 .. TC)
        solve();
}

import std.stdio;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

int[] ask(int l, int r) {
    writefln("? %s %s", l, r);
    stdout.flush;
    return readln.chomp.split(" ").map!(to!int).array;
}

void solve() {
    int N = readln.chomp.to!int;

    int f(int l, int r) {
        if (l == r) return l;
        int[] xs = ask(l, (l+r)/2);
        int R = 0;
        foreach (i, x; xs) {
            if (l <= x && x <= (l+r)/2) {
                R++;
            }
        }
        //stderr.writefln("(%s, %s) -> %s", l, r, R);
        if (R % 2 == 1) {
            r = (l + r) / 2;
        } else {
            l = (l + r) / 2 + 1;
        }
        return f(l, r);
    }

    int ans = f(1, N);
    writefln("! %s", ans);
    stdout.flush;
}

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

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);
		int lo = 1;
		int hi = n + 1;
		while (hi - lo > 1)
		{
			int me = (lo + hi) / 2;
			writefln !("? %s %s") (lo, me - 1);
			stdout.flush ();
			auto a = readln.splitter.map !(to !(int)).array;
			auto num = a.count !(x => lo <= x && x <= me - 1);
			if (num % 2 == 0)
			{
				lo = me;
			}
			else
			{
				hi = me;
			}
		}
		writefln !("! %s") (lo);
		stdout.flush ();
	}
}

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

alias ll = ulong;
void solve()
{
    auto get_ = (ll l, ll r) {
        writefln!("? %s %s")(l, r);
        stdout.flush;
        return readln.splitter.map!(to!int);
    };
    alias get = memoize!get_;
    ll n;
    readf!(" %s")(n);
    readln;
    ll l = 1, r = n;
    while (l <= r)
    {
        ll mid = (l + r) / 2;
        auto swaps = get(l, mid).count!(x => l <= x && x <= mid);
        if (swaps % 2 == 0)
            l = mid + 1;
        else
            r = mid - 1;
    }
    writefln!("! %s")(l);
    stdout.flush;
}

void main()
{
    size_t TC = 1;
    TC = readln.strip.to!int;
    foreach (_; 0 .. TC)
        solve();
}


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

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

    int[40] vals;
    coins.each!(e => ++vals[bsr(e)]);

    debug { vals.writeln; }

    int getAnsForBit(int b, int need, ref int[] vals) {
        int ans = 0;
        if (b == -1) return -1;

        auto saved = min(need, vals[b]);
        need -= saved;
        vals[b] -= saved;
        ans += saved;

        if (need > 0) {
            auto borrow = getAnsForBit(b-1, 2 * need, vals);
            if (borrow == -1) return -1;

            ans += borrow;
        }

        return ans;
    }

    while (q--) {
        uint x;
        readf("%s", &x);
        readln;

        auto ans = 0;
        auto nowvals = vals.dup;
        foreach_reverse (b; 0 .. 32) {
            if (x & (1U << b)) {
                auto cur = getAnsForBit(b, 1, nowvals);
                if (cur == -1) {
                    ans = -1;
                    break;
                }

                ans += cur;
            }
        }

        ans.writeln;
    }

}

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

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

    int[40] vals;
    coins.each!(e => ++vals[bsr(e)]);

    debug { vals.writeln; }

    while (q--) {
        uint x;
        readf("%s", &x);
        readln;

        auto ans = 0;
        auto nowvals = vals.dup;
        foreach_reverse (b; 0 .. 32) {
            if (x & (1U << b)) {

                int getAns(int b, int need) {
                    int ans = 0;
                    if (b == -1) return -1;

                    auto saved = min(need, nowvals[b]);
                    need -= saved;
                    nowvals[b] -= saved;
                    ans += saved;

                    if (need > 0) {
                        auto borrow = getAns(b-1, 2 * need);
                        if (borrow == -1) return -1;

                        ans += borrow;
                    }

                    return ans;
                }

                auto cur = getAns(b, 1);
                if (cur == -1) {
                    ans = -1;
                    break;
                }

                ans += cur;
            }
        }

        ans.writeln;
    }

}


immutable multi = true;

void solve(int tc)
{
	auto a = readInt!int;
	auto b = readInt!int;
	auto pk = new bool[](a + b + 1);
	void tryPair(int c0, int c1)
	{
		foreach(bi0; 0 .. c0+1)
		{
			auto bi1 = b - bi0;
			if (bi1 < 0 || bi1 > c1) continue;
			int breaks = bi0 + (c1 - bi1);
			pk[breaks] = true;
		}
	}
	auto m1 = (a+b)/2;
	auto m2 = (a+b) - m1;
	tryPair(m1, m2);
	tryPair(m2, m1);
	auto ks = new int[](0);
	foreach(k, hk; pk)
		if (hk) ks ~= cast(int)k;
	ks.length.writeln;
	foreach(k; ks) write(k, " ");
	writeln;
}

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

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

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

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

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int a, b;
		readf !(" %s %s") (a, b);
		auto n = a + b;
		auto h = n / 2;
		auto g = n - h;
		auto s = new bool [a + b + 1];
		foreach (k; 0..2)
		{
			for (int i = 0; i <= min (a, g); i++)
			{
				auto ag = i;
				auto ah = a - ag;
				auto bg = g - ag;
				auto bh = b - bg;
				if (0 <= ag && ag <= a && ag <= g &&
				    0 <= ah && ah <= a && ah <= h &&
				    0 <= bg && bg <= b && bg <= g &&
				    0 <= bh && bh <= b && bh <= h)
				{
					s[ah + bg] = true;
				}
			}
			swap (g, h);
		}
		writeln (s.sum);
		writefln !("%(%s %)") (iota (a + b + 1).filter !(x => s[x]));
	}
}

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const A = readInt();
        const B = readInt();

        int[] ans;
        foreach (s; 0 .. 2) {
          const a = (A + B + s) / 2;
          const b = (A + B + (1 - s)) / 2;
          foreach (x; 0 .. a + 1) {
            if (x <= A) {
              const y = B - (a - x);
              if (y >= 0) {
                ans ~= A + B - x - y;
              }
            }
          }
        }

        ans = ans.sort.uniq.array;
        writeln(ans.length);
        foreach (i; 0 .. cast(int)(ans.length)) {
          if (i > 0) write(" ");
          write(ans[i]);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		auto n = a + b;
		bool[int] set;
		{
			auto m = (n+1) / 2;
			auto x = a - m;
			set[x] = true;
			foreach (i; 0..max(b-x, min(a, b)))
			{
				x += 2;
				set[x] = true;
			}
		}
		{
			auto m = n / 2;
			auto x = a - m;
			set[x] = true;
			foreach (i; 0..max(b-x, min(a, b)))
			{
				x += 2;
				set[x] = true;
			}
		}
		foreach (key; set.keys.sort)
			ans[ti] ~= key;
	}

	foreach (e; ans)
	{
		writeln(e.length);
		e.map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}

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

void solve(int a, int b, ref bool[int] possible_k)
{
  int n = a + b;
  foreach (ah ; 0 .. (n + 1) / 2 + 1) {
    int ab = a - ah;
    if (ab < 0)
      break;
    int bh = n / 2 - ab;
    if (bh < 0)
      continue;
    int bb = b - bh;
    if (bb < 0)
      continue;
    int k = ab + bb;
    if (k < 0)
      continue;
    possible_k[k] = true;
  }
}

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int a, b;
    readf!" %d %d "(a, b);
    bool[int] possible_k;
    solve(a, b, possible_k);
    solve(b, a, possible_k);
    writeln(possible_k.length);
    writeln(possible_k.byKey.array.sort.map!text.joiner(" "));
  }
}


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

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

        int ans = 1;
        foreach (i; 0 .. N) foreach (j; i + 1 .. N) {
          int cnt;
          foreach (k; 0 .. N) {
            if ((j - i) * (A[k] - A[i]) == (k - i) * (A[j] - A[i])) {
              ++cnt;
            }
          }
          chmax(ans, cnt);
        }

        writeln(N - ans);
      }
    }
  } catch (EOFException e) {
  }
}

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        readln;

        immutable vec =
            readln.chomp
            .split(' ')
            .to!(int[]);

        immutable longestProgressionLength = (){
            ubyte ret = 1;
            foreach (start; 0 .. vec.length)
                foreach (step; 1 .. vec.length - start) {
                    immutable strive = vec[start + step] - vec[start];
                    immutable nowLength = iota(start, vec.length, 1)
                        .count!((ind) => (vec[ind] - vec[start]) * step == strive * (ind - start));
                    ret = cast(ubyte)max(ret, nowLength);
                }
            return ret;
        }();

        (
            vec.length
            - longestProgressionLength
        ).writeln;
    }
}
// ""

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        readln;

        immutable vec =
            readln.chomp
            .split(' ')
            .to!(int[]);

        immutable longestProgressionLength = (){
            ubyte ret = 1;
            foreach (start; 0 .. vec.length)
                foreach (step; 1 .. vec.length - start) {
                    immutable strive = vec[start + step] - vec[start];
                    immutable nowLength = iota(0, vec.length, 1)
                        .count!((ind) => (vec[ind] - vec[start]) * step == strive * (ind - start));
                    ret = cast(ubyte)max(ret, nowLength);
                }
            return ret;
        }();

        (
            vec.length
            - longestProgressionLength
        ).writeln;
    }
}
// ""

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

void solve() {
    int N; readf("%d\n", &N);
    auto A = readln.chomp.split(" ").map!(to!double).array;

    auto f(int j, int k) {
        int c = 0;
        auto d = (A[k] - A[j]) / (k - j);
        auto b0 = A[j] - d * j;
        for (int i = 0; i < N; i++) {
            auto b = b0 + i * d;
            if (! isClose(A[i], b, 1e-9)) c++;
        }
        return c;
    }

    int ans = int.max;
    if (N <= 2) {
        ans = 0;
    }
    for (int j = 0; j < N; j++) {
        for (int k = j + 1; k < N; k++) {
            ans = min(ans, f(j, k));
        }
    }
    writeln(ans);
}

void main() {
    int T; readf("%d\n", &T);
    foreach (t; 0 .. T) solve();
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto A = scan!real(N);

      int ans = N - 1;
      foreach(i; 0..N - 1) foreach(j; i+1..N) {
        real d = A[j] - A[i] == 0 ? 0 : (A[j] - A[i]) / (j - i);
        real t = A[i] - d*i;
        int tans = N;
        foreach(x; 0..N) {
          if (t.approxEqual(A[x], 1e-04, 1e-04)) tans--;
          t += d;
        }
        ans = min(ans, tans);
      }

      return ans;
    }

    foreach(_; 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"];

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

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;
		int res = n - (n == 1);
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				auto num = a[j] - a[i];
				auto den = j - i;
				int cur = 0;
				foreach (k; 0..n)
				{
					auto value = num * (k - i);
					cur += (a[k] - a[i]) * den != value;
				}
				res = min (res, cur);
			}
		}
		writeln (res);
	}
}

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        readln;

        immutable vec =
            readln.chomp
            .split(' ')
            .to!(int[]);

        immutable longestProgressionLength = (){
            ubyte ret = 1;
            foreach (start; 0 .. vec.length)
                foreach (step; 1 .. vec.length - start) {
                    immutable strive = vec[start + step] - vec[start];
                    immutable nowLength = iota(start, vec.length, step)
                        .count!((ind) => (vec[ind] - vec[start]) * step == strive * (ind - start));
                    ret = cast(ubyte)max(ret, nowLength);
                }
            return ret;
        }();

        (
            vec.length
            - longestProgressionLength
        ).writeln;
    }
}
// ""

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    foreach (test_index; 0 .. tests) {
        readln;

        immutable vec =
            readln.chomp
            .split(' ')
            .to!(byte[]);

        immutable longestProgressionLength = (){
            ubyte ret = 1;
            foreach (start; 0 .. vec.length)
                foreach (step; 1 .. vec.length - start) {
                    immutable strive = vec[start + step] - vec[start];
                    immutable nowLength = iota(start, vec.length, step)
                        .count!((ind) => (vec[ind] - vec[start]) * step == strive * (ind - start));
                    ret = cast(ubyte)max(ret, nowLength);
                }
            return ret;
        }();

        (
            vec.length
            - longestProgressionLength
        ).writeln;
    }
}
// ""


import std.stdio;
import std.exception;
import std.algorithm;
import std.math;
import std.typecons;

void main(){
	int n;
	string a, b;
	readf("%d\n%s\n%s\n", &n, &a, &b);
	int x1=0, q=0, y1=0;
	foreach(i; 0..2*n){
		if (a[i]=='1' && b[i]=='1') q++;
		else if (a[i]=='1') x1++;
		else if (b[i]=='1') y1++;
	}
	int ans1=q/2+q%2, ans2=q/2;
	if (ans1!=ans2){
		if (x1>y1){
			ans2+=y1;
            ans1+=y1;
            x1-=y1;
            ans1+=x1/2;
        }
        else{
            ans1+=x1;
            ans2+=x1;
            y1-=x1;
            ans2+=y1/2+y1%2;
        }
    }
    else{
        if (x1>y1){
            ans2+=y1;
            ans1+=y1;
            x1-=y1;
            ans1+=x1/2+x1%2;
        }
        else{
            ans1+=x1;
            ans2+=x1;
            y1-=x1;
            ans2+=y1/2;
        }
    }
    if (ans1>ans2) writefln("First");
    else if (ans1<ans2) writefln("Second");
    else writefln("Draw");
}

import std.algorithm;
import std.container;
import std.exception;
import std.math;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto s = readln ().strip ();
		auto t = readln ().strip ();
		auto a = new int [4];
		foreach (i; 0..2 * n)
		{
			a[(s[i] == '1') + ((t[i] == '1') << 1)]++;
		}
		debug {writeln (a);}

		auto b = new int [2];
		foreach (i; 0..2 * n)
		{
			int p = i & 1;
			int bj = -1, bv = -3;
			foreach (j; 0..4)
			{
				if (a[j] == 0)
				{
					continue;
				}

				int v = ((j >> p) & 1) + ((j >> !p) & 1);
				if (bv < v)
				{
					bv = v;
					bj = j;
				}
			}
			assert (bj != -1);
			a[bj]--;
			b[p] += (bj >> p) & 1;
		}

		debug {writeln (b);}
		writeln (b[0] < b[1] ? "Second" :
		         (b[0] == b[1] ? "Draw" : "First"));
	}
}


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 int INF = 1 << 29;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto X = (1L << K) - 1;
    auto A = readln.split.map!(to!long).array;

    long ans = 0;
    long tmp = 0;
    long[long] cnt;
    cnt[0] = 1;

    long f(long x) {
        if (x !in cnt) return 0;
        else return cnt[x];
    }

    foreach (i; 0..N) {
        long a = tmp ^ A[i];
        long b = a ^ X;
        if (f(a) <= f(b)) {
            ans += f(a);
            cnt[a] += 1;
            tmp = a;
        } else {
            ans += f(b);
            cnt[b] += 1;
            tmp = b;
        }
    }

    ans = N.to!long * (N.to!long + 1) / 2 - ans;
    ans.writeln;
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto m = (1 << k) - 1;
		foreach (i; 1..n)
		{
			a[i] ^= a[i - 1];
		}

		int [int] v;
		v[0] = 1;
		long res = 0;
		foreach (ref c0; a)
		{
			auto c1 = c0 ^ m;
			auto one = v.get (c0, 0);
			auto two = v.get (c1, 0);
			if (one < two)
			{
				res += one;
				v[c0] += 1;
			}
			else
			{
				res += two;
				v[c1] += 1;
			}
		}
		debug {writeln (v);}
		writeln (n * (n + 1L) / 2 - res);
	}
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto m = (1 << k) - 1;

		int [int] v;
		long res = 0;
		foreach (ref c0; a)
		{
			auto c1 = c0 ^ m;
			auto one = v.get (c0, 0) + (c0 == 0);
			auto two = v.get (c1, 0) + (c1 == 0);
			if (one < two)
			{
				res += one;
				v[c0] += 1;
			}
			else
			{
				res += two;
				v[c1] += 1;
			}
		}
		writeln (n * (n + 1L) / 2 - res);
	}
}


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

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

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		auto t = readln.strip;
		auto k = s.length.to !(int);
		auto n = t.length.to !(int);

		auto p = new int [k];
		p[] = NA;
		int [] stack;
		foreach (j; 0..k)
		{
			if (s[j] == '.')
			{
				if (!stack.empty)
				{
					p[j] = stack.back;
					stack.popBack ();
					stack.assumeSafeAppend ();
				}
			}
			else
			{
				stack ~= j;
			}
		}

		auto f = new int [] [] (2, k + 1);
		int b = 0;
		f[b][0] = 0;
		foreach (j; 1..k + 1)
		{
			f[b][j] = f[b][j - 1] + 1;
			if (p[j - 1] != NA)
			{
				f[b][j] = min (f[b][j], f[b][p[j - 1]]);
			}
		}
		foreach (i; 0..n)
		{
			b ^= 1;
			f[b][] = infinity;
			foreach (j; i + 1..k + 1)
			{
				f[b][j] = f[b][j - 1] + 1;
				if (t[i] == s[j - 1])
				{
					f[b][j] = min (f[b][j], f[!b][j - 1]);
				}
				if (p[j - 1] != NA)
				{
					f[b][j] = min (f[b][j], f[b][p[j - 1]]);
				}
			}
		}
		writeln (f[b][k]);
	}
}

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

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

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		auto t = readln.strip;
		auto k = s.length.to !(int);
		auto n = t.length.to !(int);

		auto p = new int [k];
		p[] = NA;
		int [] stack;
		foreach (j; 0..k)
		{
			if (s[j] == '.')
			{
				if (!stack.empty)
				{
					p[j] = stack.back;
					stack.popBack ();
					stack.assumeSafeAppend ();
				}
			}
			else
			{
				stack ~= j;
			}
		}

		auto f = new int [] [] (2, k + 1);
		int b = 0;
		f[b] = iota (k + 1).array;
		foreach (i; 0..n)
		{
			b ^= 1;
			f[b][] = infinity;
			foreach (j; i + 1..k + 1)
			{
				f[b][j] = f[b][j - 1] + 1;
				if (t[i] == s[j - 1])
				{
					f[b][j] = min (f[b][j], f[!b][j - 1]);
				}
				if (p[j - 1] != NA)
				{
					f[b][j] = min (f[b][j], f[b][p[j - 1]]);
				}
			}
		}
		writeln (f[b][k]);
	}
}

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

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

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		auto t = readln.strip;
		auto k = s.length.to !(int);
		auto n = t.length.to !(int);

		auto p = new int [k];
		int [] stack;
		foreach (j; 0..k)
		{
			if (s[j] == '.')
			{
				if (!stack.empty)
				{
					p[j] = stack.back;
					stack.popBack ();
					stack.assumeSafeAppend ();
				}
			}
			else
			{
				stack ~= j;
			}
		}

		auto f = new int [] [] (2, k + 1);
		int b = 0;
		f[b] = iota (k + 1).array;
		foreach (i; 0..n)
		{
			b ^= 1;
			f[b][] = infinity;
			foreach (j; i + 1..k + 1)
			{
				f[b][j] = f[b][j - 1] + 1;
				if (t[i] == s[j - 1])
				{
					f[b][j] = min (f[b][j], f[!b][j - 1]);
				}
				if (p[j - 1] != NA)
				{
					f[b][j] = min (f[b][j], f[b][p[j - 1]]);
				}
			}
		}
		writeln (f[b][k]);
	}
}


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

void main ()
{
	int n;
	int k;
	readf (" %s %s", &n, &k);
	readln;
	auto a = readln.strip.map !(c => c == '0').array;

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

	bool check (int step)
	{
		int pos = 0;
		foreach (i; 1..k)
		{
			int next = pos + step + 1;
			next = min (next, n - 1);
			next = b[next];
			pos = next;
		}
		return pos == n - 1;
	}

	int lo = 0;
	int hi = n;
	while (lo < hi)
	{
		int me = (lo + hi) >> 1;
		if (check (me))
		{
			hi = me;
		}
		else
		{
			lo = me + 1;
		}
	}
	writeln (lo);
}

module main;
import std.c.stdio;

char [] arr;
int n, k;

bool Go(int m) {
    if (m == 0)
        return false;
    int have = k - 2;
    int prv = 0;
    int nxt = 0;
    for (int i = 1; i < n - 1; ++i) {
        if (arr[i] == '0')
        nxt = i;
        if (i == prv + m) {
            if (nxt > prv) {
                prv = nxt;
                have--;
                if (have < 0)
                    return false;
            }
            else
                return false;
        }
    }
    return true;
}

int main(string[] argv)
{
	scanf("%d %d\n", &n, &k);
	arr = new char[n + 10];
	for(int i = 0; i < n; i++)
		scanf("%c", &arr[i]);
	int L = 0, R = n + 1;
	while (R - L > 1) {
	    int M = (L + R) / 2;
	    if (Go(M))
	        R = M;
	    else
	        L = M;
	}
	printf("%i", R - 1);
	return 0;
}


import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	int n = read.to!int;
	int[] us;

	foreach(i; 0 .. n) us ~= read.to!int - 1;

	int bestx = 1;
	int minc, maxc;
	int[] ucnt = new int[](100_009);
	int[] ccnt = new int[](100_009);
	int allccnt;
	foreach(i; 0 .. n){
		int u = us[i];
		int c = ucnt[u];
		if(c > 0) ccnt[c] -= 1;
		if(c == minc && ccnt[c] == 0) minc += 1;
		ucnt[u] += 1;
		c = ucnt[u];
		ccnt[c] += 1;
		if(c == 1) minc = 1, allccnt += 1;
		if(c > maxc) maxc = c;

		if(minc == 1 && ccnt[minc] == 1 && ccnt[minc] + ccnt[maxc] == allccnt) bestx = i + 1;
		if(minc == maxc - 1 && ccnt[maxc] == 1) bestx = i + 1;
		if(minc == maxc && ccnt[minc] == 1) bestx = i + 1;
		if(minc == maxc && minc == 1 && ccnt[minc] > 1) bestx = i + 1;

	}

	bestx.writeln;

}

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

void main(){
    auto N = readln.chomp.to!(int);
    auto A = readln.split.map!(x => x.to!(int)-1).array;
    const int M = 10^^5;

    auto cnt = new int[](M);
    auto cnt2 = new int[](M+10);
    cnt2[0] = M;
    int ans = 0;
    int day = 0;
    auto rbt = new RedBlackTree!int();

    foreach (a; A) {
        day += 1;
        cnt2[cnt[a]] -= 1;
        cnt[a] += 1;
        cnt2[cnt[a]] += 1;
        if (cnt2[cnt[a]-1] == 0 && cnt[a] != 1) rbt.removeKey(cnt[a]-1);
        if (cnt2[cnt[a]] == 1) rbt.insert(cnt[a]);
        if (rbt.length == 1 && rbt.front == day) {
            ans = day;
        } else if (rbt.length == 1 && rbt.front == 1) {
            ans = day;
        } else if (rbt.length == 2) {
            if (cnt2[rbt.front] == 1 && rbt.front == 1) {
                ans = day;
            } else if (cnt2[rbt.back] == 1 && rbt.back == 1) {
                ans = day;
            } else if (rbt.back - rbt.front == 1 && cnt2[rbt.back] == 1) {
                ans = day;
            }
        }
    }

    ans.writeln;
}

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

void main(){
    auto N = readln.chomp.to!(int);
    auto A = readln.split.map!(x => x.to!(int)-1).array;
    const int M = 10^^5;

    auto cnt = new int[](M);
    auto cnt2 = new int[](M+10);
    cnt2[0] = M;
    int ans = 0;
    int day = 0;
    auto rbt = new RedBlackTree!int();

    foreach (a; A) {
        day += 1;
        cnt2[cnt[a]] -= 1;
        cnt[a] += 1;
        cnt2[cnt[a]] += 1;
        if (cnt2[cnt[a]-1] == 0 && cnt[a] != 1) rbt.removeKey(cnt[a]-1);
        if (cnt2[cnt[a]] == 1) rbt.insert(cnt[a]);
        if (rbt.length == 1 && rbt.front == 1) {
            ans = day;
        } else if (rbt.length == 2) {
            if (cnt2[rbt.front] == 1 && rbt.front == 1) {
                ans = day;
            } else if (cnt2[rbt.back] == 1 && rbt.back == 1) {
                ans = day;
            } else if (rbt.back - rbt.front == 1 && cnt2[rbt.back] == 1) {
                ans = day;
            }
        }
    }

    ans.writeln;
}

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	int n = read.to!int;
	int[] us;

	foreach(i; 0 .. n) us ~= read.to!int - 1;

	int bestx = 1;
	int minc, maxc;
	int[] ucnt = new int[](100_009);
	int[] ccnt = new int[](100_009);
	foreach(i; 0 .. n){
		int u = us[i];
		int c = ucnt[u];
		if(c > 0) ccnt[c] -= 1;
		if(c == minc && ccnt[c] == 0) minc += 1;
		ucnt[u] += 1;
		c = ucnt[u];
		ccnt[c] += 1;
		if(c > maxc) maxc = c;

		if(minc == 1 && ccnt[minc] == 1) bestx = i + 1;
		if(minc == maxc - 1 && ccnt[maxc] == 1) bestx = i + 1;
		if(minc == maxc && ccnt[minc] == 1) bestx = i + 1;
		if(minc == maxc && minc == 1 && ccnt[minc] > 1) bestx = i + 1;

	}

	bestx.writeln;

}

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	int n = read.to!int;
	int[] us;

	foreach(i; 0 .. n) us ~= read.to!int - 1;

	int bestx = 1;
	int minc, maxc;
	int[] ucnt = new int[](100_009);
	int[] ccnt = new int[](100_009);
	foreach(i; 0 .. n){
		int u = us[i];
		int c = ucnt[u];
		if(c > 0) ccnt[c] -= 1;
		if(c == minc && ccnt[c] == 0) minc += 1;
		ucnt[u] += 1;
		c = ucnt[u];
		ccnt[c] += 1;
		if(c == 1) minc = 1;
		if(c > maxc) maxc = c;

		if(minc == 1 && ccnt[minc] == 1) bestx = i + 1;
		if(minc == maxc - 1 && ccnt[maxc] == 1) bestx = i + 1;
		if(minc == maxc && ccnt[minc] == 1) bestx = i + 1;
		if(minc == maxc && minc == 1 && ccnt[minc] > 1) bestx = i + 1;

	}

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

void main() {
  try {
    for (; ; ) {
      const A = readToken();
      writeln(A ~ A.dup.reverse);
    }
  } catch (EOFException e) {
  }
}

import std.range;
import std.stdio;
import std.string;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		writeln (s, s.retro);
	}
}

import std.stdio;
import std.algorithm.mutation;

void main() {
	string a; // = readln();
	readf!"%s\n"(a);

	write(a);

	for (int i=a.length-1; i>=0; i--)
		write(a[i]);
}

import std.stdio;
import std.algorithm.mutation;

void main() {
	string a; // = readln();
	readf!"%s"(a);

	write(a);

	for (int i=a.length-1; i>=0; i--)
		write(a[i]);
}

import std.stdio;
import std.algorithm.mutation;

void main() {
	string a = readln();

	write(a);

	for (int i=a.length-1; i>=0; i--)
		write(a[i]);
}


import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;

struct Dsu
{
  int[] size;
  int[] directParent;
  int noSets;
  static Dsu makeEmpty(int noElements)
  {
    Dsu dsu;
    with(dsu)
      {
	size = new int[](noElements); size[] = 1;
	directParent = new int[](noElements); foreach(i; 0 .. noElements) directParent[i] = i;
	noSets = noElements;
      }
    return dsu;
  }
  int rep(int n)
  {
    int i;
    for(i = n;
	directParent[i] != i;
	i = directParent[i]) {}
    for(int j = n;
	directParent[j] != j;)
      {
	auto oldparent = directParent[j];
	directParent[j] = i;
	j = oldparent;
      }
    return i;
  }
  bool uniteSets(int x, int y)
  {
    x = rep(x);
    y = rep(y);
    if (x == y) return false;
    if (size[x] < size[y])
      swap(x, y);
    assert(size[x] >= size[y]);
    directParent[y] = x;
    noSets--;
    size[x] += size[y];
    return true;
  }
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto n = next!int;
  auto m = next!int;
  auto edges = new int[2][](m);
  auto fdsu = Dsu.makeEmpty(n);
  auto bdsu = Dsu.makeEmpty(n);
  auto fre = new bool[](m);
  auto bre = new bool[](m);
  foreach(e; 0 .. m)
    {
      edges[e][0] = next!int - 1;
      edges[e][1] = next!int - 1;
    }
  foreach(i; 0 .. m)
    fre[i] = fdsu.uniteSets(edges[i][0], edges[i][1]);
  foreach_reverse(i; 0 .. m)
    bre[i] = bdsu.uniteSets(edges[i][0], edges[i][1]);
  struct Adj
  {
    int nei;
    int id;
  }
  auto adj = new Adj[][](n);
  foreach(i, e; edges)
    if (fre[i] || bre[i])
      {
	adj[e[0]] ~= Adj(e[1], cast(int) i);
	adj[e[1]] ~= Adj(e[0], cast(int) i);
      }

  auto visited = new bool[](n);
  auto k = next!int;
  foreach(q; 0 .. k)
    {
      auto l = next!int - 1;
      auto r = next!int - 1;
      visited[] = false;
      void dfs(int i)
      {
	visited[i] = true;
	foreach(a; adj[i])
	  {
	    if (a.id >= l && a.id <= r)
	      continue;
	    if (visited[a.nei])
	      continue;
	    dfs(a.nei);
	  }
      }
      int comps = 0;
      foreach(i; 0 .. n)
	{
	  if (!visited[i])
	    {
	      dfs(i);
	      comps++;
	    }
	}
      comps.writeln;
    }
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;

struct Dsu
{
  int[] size;
  int[] directParent;
  int noSets;
  static Dsu makeEmpty(int noElements)
  {
    Dsu dsu;
    with(dsu)
      {
	size = new int[](noElements); size[] = 1;
	directParent = new int[](noElements); foreach(i; 0 .. noElements) directParent[i] = i;
	noSets = noElements;
      }
    return dsu;
  }
  int rep(int n)
  {
    int i;for(i = n;directParent[i] != i;i = directParent[i]) {}
    for(int j = n;directParent[j] != j;){auto nj = directParent[j];directParent[j] = i;j = nj;}
    return i;
  }
  bool uniteSets(int x, int y)
  {
    x = rep(x);
    y = rep(y);
    if (x == y) return false;
    if (size[x] < size[y])
      swap(x, y);
    assert(size[x] >= size[y]);
    directParent[y] = x;
    noSets--;
    size[x] += size[y];
    return true;
  }
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto n = next!int;
  auto m = next!int;
  auto edges = new int[2][](m);
  auto fdsu = Dsu.makeEmpty(n);
  auto bdsu = Dsu.makeEmpty(n);
  auto fre = new bool[](m);
  auto bre = new bool[](m);
  foreach(e; 0 .. m)
    edges[e][] = [next!int - 1, next!int - 1];
  foreach(i; 0 .. m)
    fre[i] = fdsu.uniteSets(edges[i][0], edges[i][1]);
  foreach_reverse(i; 0 .. m)
    bre[i] = bdsu.uniteSets(edges[i][0], edges[i][1]);
  struct Adj
  {
    int nei;
    int id;
  }
  auto adj = new Adj[][](n);
  foreach(i, e; edges)
    if (fre[i] || bre[i])
      {
	adj[e[0]] ~= Adj(e[1], cast(int) i);
	adj[e[1]] ~= Adj(e[0], cast(int) i);
      }

  auto visited = new bool[](n);
  auto k = next!int;
  foreach(q; 0 .. k)
    {
      auto l = next!int - 1;
      auto r = next!int - 1;
      visited[] = false;
      void dfs(int i)
      {
	visited[i] = true;
	foreach(a; adj[i])
	  {
	    if (a.id >= l && a.id <= r)
	      continue;
	    if (visited[a.nei])
	      continue;
	    dfs(a.nei);
	  }
      }
      int comps = 0;
      foreach(i; 0 .. n)
	{
	  if (!visited[i])
	    {
	      dfs(i);
	      comps++;
	    }
	}
      comps.writeln;
    }
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;

struct Dsu
{
  int[] size;
  int[] directParent;
  int noSets;
  static Dsu makeEmpty(int noElements)
  {
    Dsu dsu;
    with(dsu)
      {
	size = new int[](noElements); size[] = 1;
	directParent = new int[](noElements); foreach(i; 0 .. noElements) directParent[i] = i;
	noSets = noElements;
      }
    return dsu;
  }
  int rep(int n)
  {
    auto p = directParent[n];
    if (p == n)
      return p;
    directParent[n] = rep(p);
    return directParent[n];
  }
  bool uniteSets(int x, int y)
  {
    x = rep(x);
    y = rep(y);
    if (x == y) return false;
    if (size[x] < size[y])
      swap(x, y);
    assert(size[x] >= size[y]);
    directParent[y] = x;
    noSets--;
    size[x] += size[y];
    return true;
  }
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto n = next!int;
  auto m = next!int;
  auto edges = new int[2][](m);
  auto fdsu = Dsu.makeEmpty(n);
  auto bdsu = Dsu.makeEmpty(n);
  auto fre = new bool[](m);
  auto bre = new bool[](m);
  foreach(e; 0 .. m)
    {
      edges[e][0] = next!int - 1;
      edges[e][1] = next!int - 1;
    }
  foreach(i; 0 .. m)
    fre[i] = fdsu.uniteSets(edges[i][0], edges[i][1]);
  foreach_reverse(i; 0 .. m)
    bre[i] = bdsu.uniteSets(edges[i][0], edges[i][1]);
  struct Adj
  {
    int nei;
    int id;
  }
  auto adj = new Adj[][](n);
  foreach(i, e; edges)
    if (fre[i] || bre[i])
      {
	adj[e[0]] ~= Adj(e[1], cast(int) i);
	adj[e[1]] ~= Adj(e[0], cast(int) i);
      }

  auto visited = new bool[](n);
  auto k = next!int;
  foreach(q; 0 .. k)
    {
      auto l = next!int - 1;
      auto r = next!int - 1;
      visited[] = false;
      void dfs(int i)
      {
	visited[i] = true;
	foreach(a; adj[i])
	  {
	    if (a.id >= l && a.id <= r)
	      continue;
	    if (visited[a.nei])
	      continue;
	    dfs(a.nei);
	  }
      }
      int comps = 0;
      foreach(i; 0 .. n)
	{
	  if (!visited[i])
	    {
	      dfs(i);
	      comps++;
	    }
	}
      comps.writeln;
    }
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}


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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		a = [0] ~ a ~ [n + 1];
		auto prev = new int [n + 2];
		prev[0] = 0;
		foreach (i; 0..n + 1)
		{
			prev[i + 1] = i;
		}
		auto next = new int [n + 2];
		next[n + 1] = n + 1;
		foreach (i; 0..n + 1)
		{
			next[i] = i + 1;
		}
		auto iprev = prev.dup;
		auto inext = next.dup;
		auto del = new bool [n + 2];
		del[] = false;

		int res = 0;
		while (true)
		{
			bool ok = false;

			int p = inext[0];
			while (p <= n)
			{
				debug {write (' ', p);}
				if (del[p])
				{
					iprev[inext[p]] = iprev[p];
					inext[iprev[p]] = inext[p];
				}
				debug {writef ("(%s.%s)", a[p], a[next[p]]);}
				if (a[p] > a[next[p]] && !del[next[p]])
				{
					debug {write ('[', next[p], ']');}
					ok = true;
					del[next[p]] = true;
					int q = next[p];
					prev[next[q]] = prev[q];
					next[prev[q]] = next[q];
				}
				else
				{
					iprev[inext[p]] = iprev[p];
					inext[iprev[p]] = inext[p];
				}
				p = inext[p];
			}
			debug {writeln ();}

			if (!ok)
			{
				break;
			}
			res++;
		}
		writeln (res);
	}
}

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

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

    auto a = new int[n];
    foreach (i; 0..n) readf(" %d", &a[i]), --a[i];
    a ~= n;

    auto rt = array(iota(1, n + 1));
    auto ls = array(iota(n));
    int[] nls;
    auto done = new bool[n];

    int ans;
    while (true) {
        foreach_reverse (i; ls)
            if (a[i] > a[rt[i]])
                done[rt[i]] = true, rt[i] = rt[rt[i]];
            else
                done[i] = true;
        foreach (i; ls)
            if (!done[i])
                nls ~= i;
        if (nls !is null) {
            ls = null;
            swap(ls, nls);
            ++ans;
        } else
            break;
    }

    writeln(ans);
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);

  auto n = next!int;
  auto a = next!int(n);
  auto dt = new int[](n);
  dt[] = int.max;
  auto possible = SList!int(0);
 iloop:foreach(i; 1 .. n)
    {
      dt[i] = 1;
    searchkiller: while(true)
        {
          auto np = possible.front;
          if (dt[np] < dt[i])
            {
              possible.removeFront;
              continue searchkiller;
            }
          if (a[np] > a[i])
            {
              possible.insertFront(i);
              continue iloop;
            }
          else
            {
              if (dt[np] == int.max)
                {
                  dt[i] = int.max;
                  possible.insertFront(i);
                  continue iloop;
                }
              dt[i] = dt[np] + 1;
              possible.removeFront;
              continue searchkiller;
            }
        }
    }
  writeln(dt.filter!(t => t != int.max).fold!max(0));
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}