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

int N;
int[] colors;
int[][] adj;

void main() {
    N = readln.chomp.to!int;
    adj = new int[][](N);
    foreach (i; 0..N-1) {
        auto s = readln.split.map!(to!int).array;
        adj[s[0]-1] ~= s[1]-1;
        adj[s[1]-1] ~= s[0]-1;
    }
    colors = readln.split.map!(to!int).array;

    int[int] cnt;
    foreach (c; colors) {
        if (c in cnt) cnt[c]++;
        else cnt[c] = 1;
    }

    if (cnt.keys.length == 1) {
        writeln("YES");
        writeln(1);
    }
    else {
        Tuple!(int, int)[] borders;
        foreach (i; 0..N) {
            foreach (j; adj[i]) {
                if (colors[i] != colors[j]) {
                    borders ~= tuple(i, j);
                }
            }
        }

        foreach (a; borders[0]) {
            bool flag = true;
            foreach (b; borders) {
                if (a != b[0] && a != b[1]) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                writeln("YES");
                writeln(a+1);
                return;
            }
        }

        writeln("NO");
    }
}

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.variant,
	std.stdio,std.bitmanip;
import core.stdc.stdio : freopen;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias boyerMooreFinder strfind;
alias make_pair mp;
alias binary_search bins;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");
alias std.numeric.gcd gcd;
immutable int mod=10^^9+7;
pure nothrow
{
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_)
	{
		pair!(X,Y) pp;
		pp.fi=x_;
		pp.se=y_;
		return pp;
	}
	big gcd(big a,big b)
	{
		while(b)
		{
			a%=b;
			swap(a,b);
		}
		return a;
	}
	T lcm (T)(auto ref T a,auto ref T b)
	{
		return a/gcd(a,b)*b;
	}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	size_t lowb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(g<a[m])r=m;
			else l=m;
		}
		return (g<a[l])?l:r;
	}
	size_t binf(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (g==a[l])?l:a.length;
	}
	bool binary_search(T,X)(in T a,auto ref X g) if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' '){foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a,in size_t n,in size_t m) if(isRandomAccessRange!X)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n) if(hasSlicing!X && !isSomeChar(ElementType!X))
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0)
{
	string f;
	foreach(i;T)
	{
		if(isSomeChar!i)f~=" %c";
		else f~=" %s";
	}
	return readf(f,ptrs)==ptrs.length;
}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{
	string f;
	foreach(i;T)
	{
		if(isSomeChar!i)f~=" %c";
		else f~=" %s";
	}
	f~='\n';
	return readf(f,ptrs)==ptrs.length;
}
nothrow void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter countUntil
//---------------------------------------------------------------program beginning---------------------------------------

void main()
{
	int n;
	loop:while(read(&n))
	{
		auto g=new int[][n+1];
		foreach(i;0..n-1)
		{
			int u,v;
			read(&u,&v);
			u--;v--;
			g[u]~=v;
			g[v]~=u;
		}
		auto cl=arread!int;
		auto a=new int[n];
		int s;
		foreach(i;0..n)
		{
			foreach(x;g[i])
			{
				if(cl[i]!=cl[x])
				{
					a[i]++;
					a[x]++;
					s++;
				}
			}
		}
		foreach(i;0..n)
		{
			if(a[i]==s)
			{
				writeln("YES\n",i+1);
				continue loop;
			}
		}
		writeln("NO");
	}
}

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

int N;
int[] colors;
int[][] adj;

bool dfs(int n, int prev) {
    foreach (m; adj[n]) {
        if (m == prev) continue;
        if (colors[m] != colors[n]) return false;
        if (!dfs(m, n)) return false;
    }
    return true;
}

void main() {
    N = readln.chomp.to!int;
    adj = new int[][](N);
    foreach (i; 0..N-1) {
        auto s = readln.split.map!(to!int).array;
        adj[s[0]-1] ~= s[1]-1;
        adj[s[1]-1] ~= s[0]-1;
    }
    colors = readln.split.map!(to!int).array;

    int[int] cnt;
    foreach (c; colors) {
        if (c in cnt) cnt[c]++;
        else cnt[c] = 1;
    }

    if (N <= 3) {
        writeln("YES");
        writeln(1);
    }
    else if (cnt.keys.length == 1) {
        writeln("YES");
        writeln(1);
    }
    else if (cnt.keys.length == 2) {
        int n1 = -1;
        int n2 = -1;
        int c1 = 0;
        int c2 = 0;

        foreach (i; 0..N) {
            foreach (j; adj[i]) {
                if (colors[i] != colors[j]) {
                    if (colors[i] < colors[j]) {
                        c1++;
                        n1 = i;
                    }
                    else {
                        c2++;
                        n2 = i;
                    }
                    break;
                }
            }
        }

        if (c1 == 1) {
            writeln("YES");
            writeln(n1+1);
        }
        else if (c2 == 1) {
            writeln("YES");
            writeln(n2+1);
        }
        else {
            writeln("NO");
        }

    }
    else if (cnt.keys.length == 3) {
        foreach (i; 0..N) {
            if (cnt[colors[i]] == 1) {
                bool flag = true;
                foreach (j; adj[i]) {
                    if (!dfs(j, i)) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    writeln("YES");
                    writeln(i+1);
                    return;
                }
            }
        }
        writeln("NO");
    }
    else {
        writeln("NO");
    }
}

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

int N;
int[] colors;
int[][] adj;

bool dfs(int n, int prev) {
    foreach (m; adj[n]) {
        if (m == prev) continue;
        if (colors[m] != colors[n]) return false;
        if (!dfs(m, n)) return false;
    }
    return true;
}

void main() {
    N = readln.chomp.to!int;
    adj = new int[][](N);
    foreach (i; 0..N-1) {
        auto s = readln.split.map!(to!int).array;
        adj[s[0]-1] ~= s[1]-1;
        adj[s[1]-1] ~= s[0]-1;
    }
    colors = readln.split.map!(to!int).array;

    int[int] cnt;
    foreach (c; colors) {
        if (c in cnt) cnt[c]++;
        else cnt[c] = 1;
    }

    if (cnt.keys.length == 1) {
        writeln("YES");
        writeln(1);
    }
    else if (cnt.keys.length == 2) {
        int n1 = -1;
        int n2 = -1;
        int c1 = 0;
        int c2 = 0;

        foreach (i; 0..N) {
            foreach (j; adj[i]) {
                if (colors[i] != colors[j]) {
                    if (colors[i] < colors[j]) {
                        c1++;
                        n1 = i;
                    }
                    else {
                        c2++;
                        n2 = i;
                    }
                    break;
                }
            }
        }

        if (c1 == 1) {
            writeln("YES");
            writeln(n1+1);
        }
        else if (c2 == 1) {
            writeln("YES");
            writeln(n2+1);
        }
        else {
            writeln("NO");
        }

    }
    else if (cnt.keys.length == 3) {

        foreach (i; 0..N) {
            if (cnt[colors[i]] == 1) {
                bool flag = true;
                foreach (j; adj[i]) {
                    if (!dfs(j, i)) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    writeln("YES");
                    writeln(i+1);
                    return;
                }
            }
        }
        writeln("NO");
    }
    else {
        writeln("NO");
    }
}

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

int N;
int[] colors;
int[][] adj;

bool dfs(int n, int prev) {
    foreach (m; adj[n]) {
        if (m == prev) continue;
        if (colors[m] != colors[n]) return false;
        if (!dfs(m, n)) return false;
    }
    return true;
}

void main() {
    N = readln.chomp.to!int;
    adj = new int[][](N);
    foreach (i; 0..N-1) {
        auto s = readln.split.map!(to!int).array;
        adj[s[0]-1] ~= s[1]-1;
        adj[s[1]-1] ~= s[0]-1;
    }
    colors = readln.split.map!(to!int).array;

    int[int] cnt;
    foreach (c; colors) {
        if (c in cnt) cnt[c]++;
        else cnt[c] = 1;
    }

    if (cnt.keys.length == 1) {
        writeln("YES");
        writeln(1);
    }
    else if (cnt.keys.length == 2) {
        int n1 = -1;
        int n2 = -1;
        int c1 = 0;
        int c2 = 0;

        foreach (i; 0..N) {
            foreach (j; adj[i]) {
                if (colors[i] != colors[j]) {
                    if (colors[i] < colors[j]) {
                        c1++;
                        n1 = i;
                    }
                    else {
                        c2++;
                        n2 = i;
                    }
                    break;
                }
            }
        }

        if (c1 == 1) {
            writeln("YES");
            writeln(n1+1);
        }
        else if (c2 == 1) {
            writeln("YES");
            writeln(n2+1);
        }
        else {
            writeln("NO");
        }

    }
    else {
        foreach (i; 0..N) {
            if (cnt[colors[i]] == 1) {
                bool flag = true;
                foreach (j; adj[i]) {
                    if (!dfs(j, i)) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    writeln("YES");
                    writeln(i+1);
                    return;
                }
            }
        }
        writeln("NO");
    }
}


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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto n = readln.chomp.to!double * 2;
        if (n == 4) {
            writefln("%.12f", 1.0);
            continue;
        }
        auto r = 1.0 / sin(PI / n);

        auto d = 2.0 * PI / n;
        auto res = 0.0;
        foreach (x; 0..n.to!int) {
            auto t = 45.0 * PI / 180.0 + d * x;
            res = max(res, r * sin(t));
        }
        writefln("%.12f", res);
    }
}

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

real solve (int n)
{
	auto alpha = PI / n;
	real x = 0.0;
	real y = 0.0;
	real phi = 0.0;
	foreach (i; 0..n)
	{
		x += cos (phi);
		y += sin (phi);
		phi += alpha;
	}
	return cos (alpha / 4) * hypot (y, x);
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		readln.strip.to !(int).solve.writefln !("%.20f");
	}
}

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

real solve (int n)
{
	auto alpha = PI / n;
	writeln (alpha * 180.0 / PI);
	real x = 0.0;
	real y = 0.0;
	real phi = 0.0;
	foreach (i; 0..n)
	{
		x += cos (phi);
		y += sin (phi);
		phi += alpha;
	}
	return cos (alpha / 4) * hypot (y, x);
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		readln.strip.to !(int).solve.writefln !("%.20f");
	}
}


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

// T: monoid
// op: T * T -> T
// query(a, b): returns t_a ... t_{b-1}
class SegmentTree(T, alias op) {
  import std.functional : binaryFun;
  alias opFun = binaryFun!op;
  const(T) idT;

  int n;
  T[] ts;
  this(int n_, const(T) idT) {
    this.idT = idT;
    for (n = 1; n < n_; n <<= 1) {}
    ts = new T[n << 1];
    ts[] = idT;
  }
  this(inout(T)[] ts_, const(T) idT) {
    this.idT = idT;
    const n_ = cast(int)(ts_.length);
    for (n = 1; n < n_; n <<= 1) {}
    ts = new T[n << 1];
    ts[0 .. n] = idT;
    ts[n .. n + n_] = ts_[];
    ts[n + n_ .. n << 1] = idT;
    build();
  }
  ref T at(int a) {
    return ts[n + a];
  }
  void build() {
    foreach_reverse (a; 1 .. n) ts[a] = opFun(ts[a << 1], ts[a << 1 | 1]);
  }
  void set(int a, const(T) val) {
    ts[a += n] = val;
    for (; a >>= 1; ) ts[a] = opFun(ts[a << 1], ts[a << 1 | 1]);
  }
  void mulL(int a, const(T) val) {
    set(a, opFun(val, ts[a + n]));
  }
  void mulR(int a, const(T) val) {
    set(a, opFun(ts[a + n], val));
  }
  T query(int a, int b) const {
    T prodL = idT, prodR = idT;
    for (a += n, b += n; a < b; a >>= 1, b >>= 1) {
      if (a & 1) prodL = opFun(prodL, ts[a++]);
      if (b & 1) prodR = opFun(ts[--b], prodR);
    }
    return opFun(prodL, prodR);
  }
}

// t -> max{t + a, b}
struct T {
  int a, b;
  T opBinary(string op)(const(T) t) const {
    return T(a + t.a, max(b + t.a, t.b));
  }
}
enum INF = 10^^9;
enum ID_T = T(0, -INF);

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto P = new int[N];
      foreach (i; 0 .. N) {
        P[i] = readInt();
      }
      auto Q = new int[N];
      foreach (j; 0 .. N) {
        Q[j] = readInt() - 1;
      }

      auto poss = new int[N + 1];
      foreach (i; 0 .. N) {
        poss[P[i]] = i;
      }

      auto ans = new int[N];
      auto seg = new SegmentTree!(T, "a * b")(2 * N, ID_T);
      {
        int x = N + 1;
        foreach (j; 0 .. N) {
          for (; max(0 + seg.ts[1].a, seg.ts[1].b) <= 0; ) {
            // add large
            --x;
            seg.set(2 * poss[x], T(1, 0));
            debug {
              writeln(j, " ", x, ": ", seg.ts[1]);
            }
          }
          ans[j] = x;
          // bomb
          seg.set(2 * Q[j] + 1, T(-1, 0));
        }
      }
      foreach (j; 0 .. N) {
        if (j > 0) write(" ");
        write(ans[j]);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}

// Code By H~$~C

module main;

import std.stdio, std.array, std.string, std.math, std.uni, std.format, std.bigint;
import std.algorithm, std.conv, std.container, std.range, std.functional;
import std.random, std.typecons;

immutable Maxn = 300005;

int n;
int[Maxn] p, q;

struct node {
  this()() {
    sum = suf = 0;
  }
  this()(in node x) { *this = x; }
  int sum, suf;
  void apply(int l, int r) {
    sum = suf = 0;
  }
  void apply(int l, int r, int x) {
    sum += x, suf += x;
  }
}
void pullup(ref node a, in node b, in node c) {
  a.suf = max(c.suf, b.suf + c.sum);
  a.sum = b.sum + c.sum;
}

struct segment_tree {
  int N;
  node[] tr;
  private void pushup(int p) {
    pullup(tr[p], tr[p * 2], tr[p * 2 + 1]);
  }
  private void modify_(T...)(int p, int l, int r, int L, int R, T args) {
    if (L == l && r == R) return tr[p].apply(l, r, args);
    pushdown(p, l, r);
    int mid = (l + r) >> 1;
    if (R <= mid) modify_(p * 2, l, mid, L, R, args);
    else if (L > mid) modify_(p * 2 + 1, mid + 1, r, L, R, args);
    else {
      modify_(p * 2, l, mid, L, mid, args);
      modify_(p * 2 + 1, mid + 1, r, mid + 1, R, args);
    }
    pushup(p);
  }
  private node query_(int p, int l, int r, int L, int R) {
    if (L == l && r == R) return tr[p];
    pushdown(p, l, r);
    int mid = (l + r) >> 1;
    if (R <= mid) return query_(p * 2, l, mid, L, R);
    if (L > mid) return query_(p * 2 + 1, mid + 1, r, L, R);
    node left = query_(p * 2, l, mid, L, mid);
    node right = query_(p * 2 + 1, mid + 1, r, mid + 1, R);
    node ans; pullup(ans, left, right); return ans;
  }
  public void build(T...)(int len, T args) {
    N = len;
    tr.length = (N + 1) << 2;
    build(1, 1, N, args);
  }
  public void modify(T...)(int L, int R, T args) {
    if (L > R) return ;
    modify_(1, 1, N, L, R, args);
  }
  public node query(int L, int R) {
    if (L > R) return node();
    return query_(1, 1, N, L, R);
  }
  private void pushdown(int p, int l, int r) {
    int mid = (l + r) >> 1;
  }
  private void build(int p, int l, int r) {
    if (l == r) {
      tr[p].apply(l, r);
      return ;
    }
    int mid = (l + r) >> 1;
    build(p * 2, l, mid);
    build(p * 2 + 1, mid + 1, r);
    pushup(p);
  }
}
segment_tree sgt;

// FIXME
void solve(in int testcase) {
  n.read;
  p[1 .. n + 1] = readarray!int;
  foreach(i; 1 .. n + 1) q[p[i]] = i;
  sgt.build(n);
  int now = n;
  foreach(i; 1 .. n + 1) {
    while (sgt.query(1, n).suf <= 0) {
      sgt.modify(q[now], q[now], 1);
      --now;
    }
    (now + 1).write, (" \n"[i == n]).write;
    int pos = reader!int;
    sgt.modify(pos, pos, -1);
  }
}

// ************************************************************

T reader(T)() { return readToken().to!T; }
void read(T)(ref T t) { t = reader!T; }
T[] readarray(T)() { return readln.splitter.map!(to!T).array; }
void chmax(T)(ref T a, T b) { a = max(a, b); }
void chmin(T)(ref T a, T b) { a = min(a, b); }
alias less = (a, b) => a < b;
alias greater = (a, b) => a > b;
T min_element(T)(in T[] a) { return a.element!less; }
T max_element(T)(in T[] a) { return a.element!greater; }
alias unique = uniq;

// constant or some variables
immutable int inf = 0x3f3f3f3f;
immutable long lnf = 0x3f3f3f3f3f3f3f3f;
immutable typeof(null) NULL = null;
string[] _tokens;

// functions
T element(alias pred, T)(in T[] a) {
  int pos = 0;
  for (int i = 1; i < cast(int)(a.length); ++i)
    if (binaryFun!pred(a[i], a[pos])) pos = i;
  return a[pos];
}
string readToken() {
  for (; _tokens.empty; ) {
    if (stdin.eof) return "";
    _tokens = readln.split;
  }
  auto token = _tokens.front;
  _tokens.popFront;
  return token;
}
int binary_bearch(alias pred, T)(in T[] as) {
  int l = -1, h = cast(int)(as.length), mid;
  for (; l + 1 < h; ) {
    mid = (l + h) >> 1;
    (unaryFun!pred(as[mid]) ? h : l) = mid;
  }
  return h;
}
int lower_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => a == val || pred(val, a));
}
int upper_bound(alias pred = less, T)(in T[] as, T val) {
  return as.binary_bearch!(a => pred(val, a));
}

void main(string[] args) {
  int tests = 1;
//  tests.read();
  foreach(test; 1 .. tests + 1) solve(test);
}

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

// T: monoid
// op: T * T -> T
// query(a, b): returns t_a ... t_{b-1}
class SegmentTree(T, alias op) {
  import std.functional : binaryFun;
  alias opFun = binaryFun!op;
  const(T) idT;

  int n;
  T[] ts;
  this(int n_, const(T) idT) {
    this.idT = idT;
    for (n = 1; n < n_; n <<= 1) {}
    ts = new T[n << 1];
    ts[] = idT;
  }
  this(inout(T)[] ts_, const(T) idT) {
    this.idT = idT;
    const n_ = cast(int)(ts_.length);
    for (n = 1; n < n_; n <<= 1) {}
    ts = new T[n << 1];
    ts[0 .. n] = idT;
    ts[n .. n + n_] = ts_[];
    ts[n + n_ .. n << 1] = idT;
    build();
  }
  ref T at(int a) {
    return ts[n + a];
  }
  void build() {
    foreach_reverse (a; 1 .. n) ts[a] = opFun(ts[a << 1], ts[a << 1 | 1]);
  }
  void set(int a, const(T) val) {
    ts[a += n] = val;
    for (; a >>= 1; ) ts[a] = opFun(ts[a << 1], ts[a << 1 | 1]);
  }
  void mulL(int a, const(T) val) {
    set(a, opFun(val, ts[a + n]));
  }
  void mulR(int a, const(T) val) {
    set(a, opFun(ts[a + n], val));
  }
  T query(int a, int b) const {
    T prodL = idT, prodR = idT;
    for (a += n, b += n; a < b; a >>= 1, b >>= 1) {
      if (a & 1) prodL = opFun(prodL, ts[a++]);
      if (b & 1) prodR = opFun(ts[--b], prodR);
    }
    return opFun(prodL, prodR);
  }
}

// t -> max{t + a, b}
struct T {
  int a, b;
  T opBinary(string op)(const(T) t) const {
    return T(a + t.a, max(b + t.a, t.b));
  }
}
enum INF = 10^^9;
enum ID_T = T(0, -INF);

void main() {
writeln(T(-1,0)*T(-1,0));
writeln(T(-1,0)*T(-1,0)*T(1,0));
  try {
    for (; ; ) {
      const N = readInt();
      auto P = new int[N];
      foreach (i; 0 .. N) {
        P[i] = readInt();
      }
      auto Q = new int[N];
      foreach (j; 0 .. N) {
        Q[j] = readInt() - 1;
      }

      auto poss = new int[N + 1];
      foreach (i; 0 .. N) {
        poss[P[i]] = i;
      }

      auto ans = new int[N];
      auto seg = new SegmentTree!(T, "a * b")(2 * N, ID_T);
      {
        int x = N + 1;
        foreach (j; 0 .. N) {
          for (; max(0 + seg.ts[1].a, seg.ts[1].b) <= 0; ) {
            // add large
            --x;
            seg.set(2 * poss[x], T(1, 0));
            debug {
              writeln(j, " ", x, ": ", seg.ts[1]);
            }
          }
          ans[j] = x;
          // bomb
          seg.set(2 * Q[j] + 1, T(-1, 0));
        }
      }
      foreach (j; 0 .. N) {
        if (j > 0) write(" ");
        write(ans[j]);
      }
      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.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto N = RD;
	auto B = RD;
	auto A = RD;
	auto s = RDR.ARR;

	long a = A, b = B;
	long ans;
	foreach (e; s)
	{
		if (e == 1 && b != 0 && a != A)
		{
			--b; ++a;
		}
		else if (a != 0)
		{
			--a;
		}
		else if (b != 0)
		{
			--b;
		}
		else
		{
			break;
		}
		++ans;
	}

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

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

const long mod = 1_000_000_007;

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

	long n = read.to!long;
	long b = read.to!long;
	long a = read.to!long;

	bool[] areSunny;
	foreach(i; 0 .. n) areSunny ~= read.to!int.to!bool;

	long amax = a;
	long ans = n;
	foreach(i, s; areSunny){
		if(s){
			if(a == amax && a > 0) a -= 1;
			else if(b > 0) b -= 1, a = min(amax, a + 1);
			else if(a > 0) a -= 1;
			else{
				ans = i;
				break;
			}
		}
		else{
			if(a > 0) a -= 1;
			else if(b > 0) b -= 1;
			else{
				ans = i;
				break;
			}
		}
	}
	ans.writeln;

}
/*

Greedy.
Use battery when sunny and use accumlator when cloudy.
Perform simulation of it.

*/

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

const long mod = 1_000_000_007;

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

	long n = read.to!long;
	long b = read.to!long;
	long a = read.to!long;

	bool[] areSunny;
	foreach(i; 0 .. n) areSunny ~= read.to!int.to!bool;

	long amax = a;
	long ans = n;
	foreach(i, s; areSunny){
		if(s){
			if(b > 0) b -= 1, a = min(amax, a + 1);
			else if(a > 0) a -= 1;
			else{
				ans = i;
				break;
			}
		}
		else{
			if(a > 0) a -= 1;
			else if(b > 0) b -= 1;
			else{
				ans = i;
				break;
			}
		}
	}
	ans.writeln;

}
/*

Greedy.
Use battery when sunny and use accumlator when cloudy.
Perform simulation of it.

*/

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

const long mod = 1_000_000_007;

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

	long n = read.to!long;
	long b = read.to!long;
	long a = read.to!long;

	bool[] areSunny;
	foreach(i; 0 .. n) areSunny ~= read.to!int.to!bool;

	long amax = a;
	long ans = n;
	foreach(i, s; areSunny){
		if(s){
			if(b > 0){
				b -= 1;
				if(a < amax) a += 1;
			}
			else if(a > 0){
				a -= 1;
			}
			else{
				ans = i + 1;
				break;
			}
		}
		else{
			if(a > 0){
				a -= 1;
			}
			else{
				ans = i + 1;
				break;
			}
		}
	}
	ans.writeln;

}
/*

Greedy.
Use battery when sunny and use accumlator when cloudy.
Perform simulation of it.

*/

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto N = RD;
	auto B = RD;
	auto A = RD;
	auto s = RDR.ARR;

	long a = A, b = B;
	long ans;
	foreach (e; s)
	{
		if (e == 1 && b != 0)
		{
			--b; a = min(a+1, A);
		}
		else if (a != 0)
		{
			--a;
		}
		else if (b != 0)
		{
			--b;
		}
		else
		{
			break;
		}
		++ans;
	}

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


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

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

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

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

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

        auto app = new bool[][](K, 2);
        foreach (i; 0 .. N) {
          if (S[i] != '?') {
            app[i % K][S[i] - '0'] = true;
          }
        }

        bool ok = true;
        auto cnt = new int[2];
        foreach (r; 0 .. K) {
          if (app[r][0] && app[r][1]) {
            ok = false;
          }
          foreach (s; 0 .. 2) {
            if (app[r][s]) {
              ++cnt[s];
            }
          }
        }

        bool ans;
        if (ok) {
          if (2 * cnt[0] <= K && 2 * cnt[1] <= K) {
            ans = true;
          }
        }
        writeln(ans ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}

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

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

void play(){
    int n;
    n = to!int(rd);
    int k = to!int(rd);
    dchar[] wordstr;
    readln(wordstr);
    wordstr.popBack;
    int[] word;
    foreach(cr; wordstr){
        word ~= (cr - '0');
    }
    // Set all initially
    foreach(i; 0..n-k){
        if(word[i] <= 1){
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }else if(word[i+k] <= 1){
            word[i] = word[i+k];
        }
    }
    // Check 0s and 1s
    ll c0 = 0, c1 = 0, cq = 0;
    foreach(i; 0..k){
        if(word[i] == 1) ++c1;
        if(word[i] > 1) ++cq;
    }
    c0 = k - cq - c1;
    foreach(i; k..n-k+1){
        if(c1 > k/2 || c0 > k/2 || abs(c1 - c0) > cq){
            writeln("NO");
            return;
        }
        // Remove
        c1 -= (word[i-k] == 1); c0 -= (word[i-k] == 0); cq -= (word[i-k] > 1);
        // Add
        c1 += (word[i] == 1); c0 += (word[i] == 0); cq += (word[i] > 1);

    }
    /* writeln(word); */
    if(c0 <= k/2 && c1 <= k/2 && abs(c1 - c0) <= cq){
        writeln("YES");
    }else{
        writeln("NO");
    }
}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		auto s = RD!(char[]);

		bool ok = true;
		foreach (i; 0..n-k)
		{
			if (s[i] == s[i+k]) continue;
			if (s[i] == '?')
				s[i] = s[i+k];
			else if (s[i+k] == '?')
				s[i+k] = s[i];
			else
			{
				ok = false;
				break;
			}
		}
		if (!ok) continue;

		long cnt0, cnt1;
		foreach (i; 0..k)
		{
			if (s[i] == '0')
				++cnt0;
			else if (s[i] == '1')
				++cnt1;
		}
		debug writeln("cnt0:", cnt0, " cnt1:", cnt1);

		auto k2 = k/2;
		foreach (i; 0..n-k)
		{
			if (cnt0 > k2 || cnt1 > k2)
			{
				ok = false;
				break;
			}
			if (s[i] == '0')
				--cnt0;
			else if (s[i] == '1')
				--cnt1;

			if (s[i+k] == '0')
				++cnt0;
			else if (s[i+k] == '1')
				++cnt1;
			debug writeln("i:", i, " cnt0:", cnt0, " cnt1:", cnt1);
		}
		if (cnt0 > k2 || cnt1 > k2)
			ok = false;

		ans[ti] = ok;
	}

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

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 n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto s = readln.strip;
		auto p = new int [k];
		p[] = -1;
		foreach (d; 0..k)
		{
			for (int i = d; i < n; i += k)
			{
				if (s[i] != '?')
				{
					auto cur = s[i] - '0';
					if (p[d] == -1)
					{
						p[d] = cur;
					}
					else if (p[d] != cur)
					{
						p[d] = -2;
					}
				}
			}
		}
		writeln ((p.count (-2) > 0 ||
		    p.count (0) > k / 2 ||
		    p.count (1) > k / 2) ? "NO" : "YES");
	}
}

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

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

void play(){
    int n;
    n = to!int(rd);
    int k = to!int(rd);
    dchar[] wordstr;
    readln(wordstr);
    wordstr.popBack;
    int[] word;
    foreach(cr; wordstr){
        word ~= (cr - '0');
    }
    // Set all initially
    foreach(i; 0..n-k-1){
        if(word[i] <= 1){
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }else if(word[i+k] <= 1){
            word[i] = word[i+k];
        }
    }
    // Check 0s and 1s
    ll c0 = 0, c1 = 0, cq = 0;
    foreach(i; 0..k){
        if(word[i] == 1) ++c1;
        if(word[i] > 1) ++cq;
    }
    c0 = k - cq - c1;
    foreach(i; k..n-k+1){
        if(c1 > k/2 || c0 > k/2 || abs(c1 - c0) > cq){
            writeln("NO");
            return;
        }
        // Remove
        c1 -= (word[i-k] == 1); c0 -= (word[i-k] == 0); cq -= (word[i-k] > 1);
        // Add
        c1 += (word[i] == 1); c0 += (word[i] == 0); cq += (word[i] > 1);

    }
    /* writeln(word); */
    if(c0 <= k/2 && c1 <= k/2 && abs(c1 - c0) <= cq){
        writeln("YES");
    }else{
        writeln("NO");
    }
}

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

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

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

void play(){
    int n;
    n = to!int(rd);
    int k = to!int(rd);
    dchar[] wordstr;
    readln(wordstr);
    wordstr.popBack;
    int[] word;
    foreach(cr; wordstr){
        word ~= (cr - '0');
    }
    // Set all initially
    foreach(i; 0..n-k-1){
        if(word[i] <= 1){
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }else if(word[i+k] <= 1){
            word[i] = word[i+k];
        }
    }
    // Check 0s and 1s
    ll roll = 0;
    foreach(i; 0..k){
        if(word[i] == 1) ++roll;
    }
    // Handle ?
    foreach(i; 0..k){
        if(word[i] > 1){
            word[i] = !(roll >= k/2);
            roll += word[i];
        }
        if(i + k < n){
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }
    }
    foreach(i; k .. n-k-1){
        if(i != k){ roll += word[i]; }
        if(roll != k/2){
            writeln("NO");
            return;
        }else{
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }
        roll -= word[i-k];
    }
    /* writeln(word); */
    if(roll == k/2){
        writeln("YES");
    }else{
        writeln("NO");
    }
}

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

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

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

void play(){
    int n;
    n = to!int(rd);
    int k = to!int(rd);
    dchar[] wordstr;
    readln(wordstr);
    wordstr.popBack;
    int[] word;
    foreach(cr; wordstr){
        word ~= (cr - '0');
    }
    // Set all initially
    foreach(i; 0..n-k-1){
        if(word[i] <= 1){
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }else if(word[i+k] <= 1){
            word[i] = word[i+k];
        }
    }
    // Check 0s and 1s
    ll roll = 0;
    foreach(i; 0..k){
        if(word[i] == 1) ++roll;
    }
    // Handle ?
    foreach(i; 0..k){
        // Handle
        if(word[i] > 1){
            word[i] = !(roll >= k/2);
            roll += word[i];
        }
        // HandleNext
        if(i + k < n){
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }
    }
    foreach(i; k..n-k-1){
        // Handle Prev Check
        if(roll != k/2){
            writeln("NO");
            return;
        }else{
            if(word[i+k] <= 1 && word[i+k] != word[i]){
                writeln("NO");
                return;
            }else{
                word[i+k] = word[i];
            }
        }

        // Remove
        roll -= word[i-k];
        // Handle ?
        if(word[i] > 1){ word[i] = !(roll >= k/2); }
        // Add
        if(i != k-1){ roll += word[i]; }
    }
    /* writeln(word); */
    if(roll == k/2){
        writeln("YES");
    }else{
        writeln("NO");
    }
}

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

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;
		auto s = RD!(char[]);

		bool ok = true;
		foreach (i; 0..n-k)
		{
			if (s[i] == s[i+k]) continue;
			if (s[i] == '?')
				s[i] = s[i+k];
			else if (s[i+k] == '?')
				s[i+k] = s[i];
			else
			{
				ok = false;
				break;
			}
		}
		if (!ok) continue;

		long cnt0, cnt1;
		foreach (i; 0..k)
		{
			if (s[i] == '0')
				++cnt0;
			else if (s[i] == '1')
				++cnt1;
		}
		debug writeln("cnt0:", cnt0, " cnt1:", cnt1);

		auto k2 = k/2;
		foreach (i; 0..n-k)
		{
			if (cnt0 > k2 || cnt1 > k2)
			{
				ok = false;
				break;
			}
			if (s[i] == '0')
				--cnt0;
			else if (s[i] == '1')
				--cnt1;

			if (s[i+k] == '0')
				++cnt0;
			else if (s[i] == '1')
				++cnt1;
			debug writeln("i:", i, " cnt0:", cnt0, " cnt1:", cnt1);
		}
		if (cnt0 > k2 || cnt1 > k2)
			ok = false;

		ans[ti] = ok;
	}

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


module sigod.codeforces.p298A;

import std.stdio;

void main()
{
	stdin.readln();
	string road = stdin.readln();

	int r_start = -1;
	int r_end = -1;
	int l_start = -1;
	int l_end = -1;

	foreach (index, c; road) {
		if (c == 'R') {
			r_end = index + 1;

			if (r_start == -1) r_start = index + 1;
		}
		else if (c == 'L') {
			l_end = index + 1;

			if (l_start == -1) l_start = index + 1;
		}
	}

	int start = -1;
	int target = -1;

	if (l_start == -1) {
		start = r_start;
		target = r_end + 1;
	}
	else if (r_start == -1) {
		start = l_end;
		target = l_start - 1;
	}
	else {
		start = r_start;
		target = l_start - 1;
	}

	stdout.writeln(start, " ", target);
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.string;
import std.range;
import std.range.primitives;
import std.conv;

int main() {
    debug stdin = File("in.txt", "r");

    char c;
    int n;
    readf("%s\n", &n);
    int fL = -1, fR = -1, lL = -1, lR = -1;
    foreach ( i ; 1 .. n + 1) {
        readf("%s", &c);
        if (c == 'R') {
            if (fR == -1) fR = i;
            lR = i;
        }
        else if (c == 'L') {
            if (fL == -1) fL = i;
            lL = i;
        }
    }
    if (fR == -1) writeln(lL, " ", fL - 1);
    else if (fL == -1) writeln(fR, " ", lR + 1);
    else writeln(fR, " ", lR);

    return 0;
}


immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto m = readInt!int;
	int mx = max(n, m);
	int mn = min(n, m);
	if (mn > 1) return writeln(2);
	if (mx == 1) return writeln(0);
	return writeln(1);
}

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

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

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

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

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

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const M = readLong();
        const N = readLong();

        int ans;
        if (M == 1 && N == 1) {
          ans = 0;
        } else if (M == 1 || N == 1) {
          ans = 1;
        } else {
          ans = 2;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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 main()
{
  long t;
  readf!" %d "(t);
  foreach (casenum ; 1 .. t + 1) {
    long n, m;
    readf!" %d %d "(n, m);
    if (n == 1 && m == 1)
      writeln(0);
    else if (n == 1 || m == 1)
      writeln(1);
    else
      writeln(2);
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (n == 1 && m == 1)
			ans[ti] = 0;
		else if (n == 1 || m == 1)
			ans[ti] = 1;
		else
			ans[ti] = 2;
	}

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

 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 m, n;
		readf !(" %s %s") (m, n);
		writeln ((m > 1) + (n > 1));
	}
}

// 提出解
void solve(){
	foreach(_; 0 .. scan!int){
		long n = scan!long, m = scan!long;
		long ans;
		if(n == 1 && m == 1) ans = 0;
		else if(n == 1 || m == 1) ans = 1;
		else ans = 2;

		ans.print;
	}
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// 愚直解
void jury(){
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// テストケース
void gen(){
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// テンプレ
import std;
bool DEBUG = 0;
void main(string[] args){
	if(args.canFind("-debug")) DEBUG = 1;
	if(args.canFind("-gen")) gen; else if(args.canFind("-jury")) jury; else solve;
}
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); }
void print(T)(T t){ writeln(t); }
void print(T, A ...)(T t, A a){ stdout.write(t, " "), print(a); }
string unsplit(T)(T xs, string d = " "){ return xs.array.to!(string[]).join(d); }
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)(int n){ return n.iota.map!(i => scan!T()).array; }
T mini(T)(ref T x, T y){ if(x > y) x = y; return x; }
T maxi(T)(ref T x, T y){ if(x < y) x = y; return x; }
T mid(T)(T l, T r, bool delegate(T) f){
	T m = (l + r) / 2; (f(m)? l: r) = m; return f(l)? f(r - 1)? r: mid(l, r, f): l;
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// ライブラリ（基本）

class UnionFind{
	this(int n){ foreach(i; 0 .. n) R ~= i, K ~= [i]; } int[] R; int[][] K;
	void unite(int a, int b){
		int ra = R[a], rb = R[b]; if(ra == rb) return;
		if(K[ra].length < K[rb].length) unite(b, a);
		else foreach(k; K[rb]) R[k] = ra, K[ra] ~= k;
	}
	int find(int a){ return R[a]; }
	int getSize(int a){ return K[R[a]].length.to!int; }
}
class Queue(T){
	private T[] xs; private uint i, j;
	this(T[] xs = []){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){ while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1; xs[j ++] = x; }
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	void flush(){ i = j; }
	alias empty = isEmpty, front = peek, popFront = deq, pop = deq, push = enq, top = peek;
	Queue opOpAssign(string op)(T x) if(op == "~"){ enq(x); return this; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}
class Stack(T){
	private T[] xs; private uint j;
	this(T[] xs = []){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j; }
	bool isEmpty(){ return j == 0; }
	void push(T x){ while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1; xs[j ++] = x; }
	T pop(){ assert(j > 0); return xs[-- j]; }
	T peek(){ assert(j > 0); return xs[j - 1]; }
	void clear(){ j = 0; }
	alias empty = isEmpty, front = peek, popFront = pop, top = peek;
	Stack opOpAssign(string op)(T x) if(op == "~"){ push(x); return this; }
	T opIndex(uint li){ assert(j > 0 && j - 1 >= li); return xs[j - 1 - li]; }
	static Stack!T opCall(T[] xs = []){ return new Stack!T(xs); }
	T[] array(){ return xs[0 .. j]; }
	override string toString(){ return array.to!string; }
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// ライブラリ（追加）

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 M = readLong();
        const N = readLong();

        const ans = min(M, N, 2);
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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 M = readLong();
        const N = readLong();

        const ans = min(M, N, 3);
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


import std.stdio;
import std.conv:to;
import std.string:chomp, countchars;
import std.array;

void main() {
    int eggs = to!int(readln().chomp);
    int A, G, iA, iG;
    auto result = appender!string();
    foreach(i; 0..eggs) {
        stdin.readf("%d %d\n", &iA, &iG);

        if((A + iA - G) <= 500) {
            A += iA;
            result.put("A");
        } else {
            G += iG;
            result.put("G");
        }
    }
    writeln(result.data);
}

module cf_282B;

import std.stdio;
import std.algorithm;
import std.math;

void main() {
    immutable MAX_PRICE = 1000;
    immutable HALF_PRICE = 500;

    int n;
    int[] eggs;

    readf("%d", &n);
    eggs = new int[n];
    for (int i = 0; i < n; ++i) {
        readf(" %d %d", &eggs[i], &eggs[i]);
    }

    string result;
    int a = 0, g = 0, cur = 0;

    while (cur < n) {
        while (cur < n && abs(a - g) <= HALF_PRICE) {
            if (abs(a + MAX_PRICE - eggs[cur] - g) > HALF_PRICE) {
                break;
            }

            a += MAX_PRICE - eggs[cur++];
            result ~= 'A';
        }

        while (cur < n && abs(a - g) <= HALF_PRICE) {
            if (abs(g + eggs[cur] - a) > HALF_PRICE) {
                break;
            }

            g += eggs[cur++];
            result ~= 'G';
        }
    }

    if (abs(a - g) > HALF_PRICE) {
        writeln(-1);
    } else {
        writeln(result);
    }
}

module cf_282B;

import std.stdio;
import std.algorithm;
import std.math;

struct Egg {
    int price;
    int pos;
}

void main() {
    immutable MAX_PRICE = 1000;

    int n;
    Egg[] eggs;

    readf("%d", &n);
    eggs = new Egg[n];
    for (int i = 0; i < n; ++i) {
        readf(" %d %d", &eggs[i].price, &eggs[i].price);
        eggs[i].pos = i;
    }

    sort!((egg1, egg2) { return egg1.price < egg2.price; })(eggs);

    char[] result = new char[n];
    int a = 0, g = 0, left = 0, right = n - 1;

    while (left <= right) {
        g += eggs[left].price;
        result[eggs[left].pos] = 'G';
        ++left;
        a += MAX_PRICE - eggs[right].price;
        result[eggs[right].pos] = 'A';
        --right;
    }

    if (abs(a - g) > MAX_PRICE / 2) {
        writeln(-1);
    } else {
        writeln(result);
    }
}

module cf_282B;

import std.stdio;
import std.algorithm;
import std.math;

struct Egg {
    int price;
    int pos;
}

void main() {
    immutable MAX_PRICE = 1000;

    int n;
    Egg[] eggs;

    readf("%d", &n);
    eggs = new Egg[n];
    for (int i = 0; i < n; ++i) {
        readf(" %d %d", &eggs[i].price, &eggs[i].price);
        eggs[i].pos = i;
    }

    sort!((egg1, egg2) { return egg1.price < egg2.price; })(eggs);

    char[] result = new char[n];
    int a = 0, g = 0, left = 0, right = n - 1;

    while (left <= right) {
        if (a > g) {
            g += eggs[left].price;
            result[eggs[left].pos] = 'G';
            ++left;
        } else {
            a += MAX_PRICE - eggs[right].price;
            result[eggs[right].pos] = 'A';
            --right;
        }
    }

    if (abs(a - g) > MAX_PRICE / 2) {
        writeln(-1);
    } else {
        writeln(result);
    }
}

module cf_282B;

import std.stdio;
import std.algorithm;
import std.math;

struct Egg {
    int price;
    int pos;
}

void main() {
    immutable MAX_PRICE = 1000;

    int n;
    Egg[] eggs;

    readf("%d", &n);
    eggs = new Egg[n];
    for (int i = 0; i < n; ++i) {
        readf(" %d %d", &eggs[i].price, &eggs[i].price);
        eggs[i].pos = i;
    }

    sort!((egg1, egg2) { return egg1.price < egg2.price; })(eggs);

    char[] result = new char[n];
    int a = 0, g = 0, left = 0, right = n - 1;

    while (left <= right) {
        if (a > g) {
            g += eggs[left].price;
            result[eggs[left].pos] = 'G';
            ++left;
        } else {
            a += MAX_PRICE - eggs[right].price;
            result[eggs[right].pos] = 'A';
            --right;
        }
    }

    if (abs(a - g) > MAX_PRICE / 2 || n == 1) {
        writeln(-1);
    } else {
        writeln(result);
    }
}

module cf_282B;

import std.stdio;
import std.algorithm;
import std.math;

struct Egg {
    int price;
    int pos;
}

void main() {
    immutable MAX_PRICE = 1000;

    int n;
    Egg[] eggs;

    readf("%d", &n);
    eggs = new Egg[n];
    for (int i = 0; i < n; ++i) {
        readf(" %d %d", &eggs[i].price, &eggs[i].price);
        eggs[i].pos = i;
    }

    sort!((egg1, egg2) { return egg1.price < egg2.price; })(eggs);

    char[] result = new char[n];
    int a = 0, g = 0, eggLeft = 0, eggRight = n - 1;

    while (eggLeft <= eggRight) {
        if (a > g) {
            while (eggLeft <= eggRight && a >= g) {
                g += eggs[eggLeft].price;
                result[eggs[eggLeft].pos] = 'G';
                ++eggLeft;
            }
        } else {
            while (eggLeft <= eggRight && g >= a) {
                a += MAX_PRICE - eggs[eggRight].price;
                result[eggs[eggRight].pos] = 'A';
                --eggRight;
            }
        }
    }

    if (abs(a - g) > MAX_PRICE / 2) {
        writeln(-1);
    } else {
        writeln(result);
    }
}


import std.stdio;

int n, m, x, y, z, p, t;

struct coord {
    int x, y;
}

void transform(ref coord c) {
    int n_t = n, m_t = m;
    for (int i = 0; i < x; i++) {
        t = c.x; c.x = c.y; c.y = n_t-t+1;
        n_t ^= m_t; m_t ^= n_t; n_t ^= m_t;
    }
    if (y)
        c.y = m_t-c.y+1;

    for (int i = 0; i < z; i++) {
        t = c.y; c.y = c.x; c.x = m_t-t+1;
        n_t ^= m_t; m_t ^= n_t; n_t ^= m_t;
    }
}

void main() {
    scanf("%d %d %d %d %d %d", &n, &m, &x, &y, &z, &p); coord c; x %= 4; y %=2; z %= 4;
    while (p--) {
        scanf("%d %d", &c.x, &c.y); transform(c); writeln(c.x, ' ', c.y);
    }
}

import std.stdio;
import std.conv;

int n, m, x, y, z, p, t;

struct coord {
    int x, y;
}

void transform(ref coord c) {
    int n_t = n, m_t = m;
    for (int i = 0; i < x; i++) {
        t = c.x; c.x = c.y; c.y = n_t-t+1;
        n_t ^= m_t; m_t ^= n_t; n_t ^= m_t;
    }
    if (y)
        c.y = m_t-c.y+1;

    for (int i = 0; i < z; i++) {
        t = c.y; c.y = c.x; c.x = m_t-t+1;
        n_t ^= m_t; m_t ^= n_t; n_t ^= m_t;
    }
}

void main() {
    string str = "";
    scanf("%d %d %d %d %d %d", &n, &m, &x, &y, &z, &p); coord c; x %= 4; y %=2; z %= 4;
    while (p--) {
        scanf("%d %d", &c.x, &c.y); transform(c); str ~= to!string(c.x) ~ ' ' ~ to!string(c.y) ~ '\n';
    }
    write(str);
}

import std.stdio;

int n, m, x, y, z, p, t;

struct coord {
    int x, y;
}

void transform(ref coord c) {
    int n_t = n, m_t = m;
    for (int i = 0; i < x; i++) {
        t = c.x; c.x = c.y; c.y = n_t-t+1;
        n_t ^= m_t; m_t ^= n_t; n_t ^= m_t;
    }
    if (y)
        c.y = m_t-c.y+1;

    for (int i = 0; i < z; i++) {
        t = c.y; c.y = c.x; c.x = n_t-t+1;
        n_t ^= m_t; m_t ^= n_t; n_t ^= m_t;
    }
}

void main() {
    scanf("%d %d %d %d %d %d", &n, &m, &x, &y, &z, &p); coord c; x %= 4; y %=2; z %= 4;
    while (p--) {
        scanf("%d %d", &c.x, &c.y); transform(c); writeln(c.x, ' ', c.y);
    }
}


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 N = readInt();
      auto A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }
      const Q = readInt();
      auto S = new int[Q];
      auto T = new int[Q];
      auto U = new int[Q];
      foreach (q; 0 .. Q) {
        S[q] = readInt() - 1;
        T[q] = readInt();
        U[q] = readInt() - 1;
      }

      auto us = new int[int][N];
      long now = A.sum;
      auto cs = new long[N];
      void add(int s, int t, int u) {
        if (cs[u] < A[u]) {
          --now;
        }
        ++cs[u];
        us[s][t] = u;
      }
      void remove(int s, int t) {
        const u = us[s][t];
        --cs[u];
        if (cs[u] < A[u]) {
          ++now;
        }
        us[s][t] = -1;
      }

      foreach (q; 0 .. Q) {
        if (T[q] in us[S[q]] && us[S[q]][T[q]] != -1) {
          remove(S[q], T[q]);
        }
        if (U[q] != -1) {
          add(S[q], T[q], U[q]);
        }
        writeln(now);
      }
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto q = readln.strip.to !(int);
		alias Pair = Tuple !(int, q{num}, int, q{kind});
		int [Pair] b;
		long total = sum (a, 0L);
		auto surplus = new int [n];

		void sub (const ref Pair cur)
		{
			if (cur !in b)
			{
				return;
			}
			auto kind = b[cur];
			b.remove (cur);
			surplus[kind] -= 1;
			if (surplus[kind] < a[kind])
			{
				total += 1;
			}
		}

		void add (const ref Pair cur, int kind)
		{
			if (kind < 0)
			{
				return;
			}
			if (surplus[kind] < a[kind])
			{
				total -= 1;
			}
			b[cur] = kind;
			surplus[kind] += 1;
		}

		foreach (r; 0..q)
		{
			int s;
			int t;
			int u;
			readf !(" %s %s %s") (s, t, u);
			t -= 1;
			u -= 1;
			auto cur = Pair (s, t);
			sub (cur);
			add (cur, u);
			writeln (total);
		}
	}
}


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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	long x1, y1, x2 = 1, y2;
	foreach (i; 0..n*n)
	{
		auto num = RD;
		if (num != 1)
		{
			if (x1 < n && y1 < n)
			{
				writeln(1, " ", x1+1, " ", y1+1);
				stdout.flush;
				if (x1+2 < n)
					x1 += 2;
				else
				{
					++y1;
					x1 = 1 - x1 % 2;
				}
			}
			else
			{
				auto z = num == 2 ? 3 : 2;
				writeln(z, " ", x2+1, " ", y2+1);
				stdout.flush;
				if (x2+2 < n)
					x2 += 2;
				else
				{
					++y2;
					x2 = 1 - x2 % 2;
				}
			}
		}
		else
		{
			if (x2 < n && y2 < n)
			{
				writeln(2, " ", x2+1, " ", y2+1);
				stdout.flush;
				if (x2+2 < n)
					x2 += 2;
				else
				{
					++y2;
					x2 = 1 - x2 % 2;
				}
			}
			else
			{
				writeln(3, " ", x1+1, " ", y1+1);
				stdout.flush;
				if (x1+2 < n)
					x1 += 2;
				else
				{
					++y1;
					x1 = 1 - x1 % 2;
				}
			}
		}
	}

	debug readln;
}

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

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

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

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

alias Pt = Tuple!(int, "x", int, "y");

void main() {
  const N = readInt();

  Pt[] ps, qs;
  foreach (x; 1 .. N + 1) foreach (y; 1 .. N + 1) {
    if ((x + y) % 2 == 0) {
      ps ~= Pt(x, y);
    } else {
      qs ~= Pt(x, y);
    }
  }
  const psLen = cast(int)(ps.length);
  const qsLen = cast(int)(qs.length);
  int posP, posQ;

  foreach (_; 0 .. N^^2) {
    const A = readInt();
    int b;
    Pt p;
    if (A != 1 && posP < psLen) {
      b = 1;
      p = ps[posP++];
    } else if (A != 2 && posQ < qsLen) {
      b = 2;
      p = qs[posQ++];
    } else if (A != 3 && posP < psLen) {
      b = 3;
      p = ps[posP++];
    } else if (A != 3 && posQ < qsLen) {
      b = 3;
      p = qs[posQ++];
    } else {
      assert(false);
    }
    writefln("%s %s %s", b, p.x, p.y);
    stdout.flush;
  }
}

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

int main(string[] args)
{
    auto n = to!int(readln.strip);
    Tuple!(int, int)[] f, s;
    foreach (i; 1 .. n + 1) foreach (j; 1 .. n + 1)
    {
        if ((i + j) & 1) s ~= tuple(i, j);
        else f ~= tuple(i, j);
    }
    int c0, c1, fidx, sidx;
    foreach (i; 0 .. n * n)
    {
        auto r = to!int(readln.strip);
        int c, x, y;
        if (fidx == f.length)
        {
            foreach (j; 1 .. 4) if (j != c0 && j != r)
            {
                c = j;
                break;
            }
            x = s[sidx][0], y = s[sidx][1];
            ++ sidx;
        }
        else if (sidx == s.length)
        {
            foreach (j; 1 .. 4) if (j != c1 && j != r)
            {
                c = j;
                break;
            }
            x = f[fidx][0], y = f[fidx][1];
            ++ fidx;
        }
        else
        {
            if (r != c0)
            {
                if (c0 == 0) c0 = (r == 1 ? 2 : 1);
                c = c0;
                x = f[fidx][0], y = f[fidx][1];
                ++ fidx;
            }
            else
            {
                if (c1 == 0)
                {
                    foreach (j; 1 .. 4) if (j != c0 && j != r)
                    {
                        c1 = j;
                        break;
                    }
                }
                c = c1;
                x = s[sidx][0], y = s[sidx][1];
                ++ sidx;
            }
        }
        writeln(c, " ", x, " ", y);
        stdout.flush;
    }
    return 0;
}

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

alias Pt = Tuple!(int, "x", int, "y");

void main() {
  const N = readInt();

  Pt[] ps, qs;
  foreach (x; 1 .. N + 1) foreach (y; 1 .. N + 1) {
    if ((x + y) % 2 == 0) {
      ps ~= Pt(x, y);
    } else {
      qs ~= Pt(x, y);
    }
  }
  const psLen = cast(int)(ps.length);
  const qsLen = cast(int)(ps.length);
  int posP, posQ;

  foreach (_; 0 .. N^^2) {
    const A = readInt();
    int b;
    Pt p;
    if (A != 1 && posP < psLen) {
      b = 1;
      p = ps[posP++];
    } else if (A != 2 && posQ < qsLen) {
      b = 2;
      p = qs[posQ++];
    } else if (A != 3 && posP < psLen) {
      b = 3;
      p = ps[posP++];
    } else if (A != 3 && posQ < qsLen) {
      b = 3;
      p = qs[posQ++];
    } else {
      assert(false);
    }
    writefln("%s %s %s", b, p.x, p.y);
    stdout.flush;
  }
}


module sigod.codeforces.p298C;

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

void main()
{
	string a = stdin.readln().strip();
	string b = stdin.readln().strip();

	size_t a_count = a.count('1');
	if (a_count % 2 == 1) ++a_count;

	size_t b_count = b.count('1');

	stdout.writeln(a_count >= b_count ? "YES" : "NO");
}

import std.stdio, std.string;

int main() {
	string s1, s2;
	s1 = chomp(readln());
	s2 = chomp(readln());
	if ((count(s1, '1')+1)/2*2 >= count(s2, '1')) {
		writeln("YES");
	} else {
		writeln("NO");
	}
    return 0;
}

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

void main ()
{
	string s, t;
	while ((s = readln ()) != null)
	{
		t = readln ();
		auto x = s.count ('1');
		x += x & 1;
		auto y = t.count ('1');
		writefln ("%s", x >= y ? "YES" : "NO");
	}
}

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

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

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

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

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

string A, B;

void main(string[] args) {
	try {
	for (; ; ) {
		A = readToken;
		B = readToken;

		int a = A.count('1');
		int b = B.count('1');
		if (a % 2 != 0) {
			++a;
		}
		writeln((a >= b) ? "YES" : "NO");
	}
	} catch (EOFException) {}
}


import std.stdio;
import std.algorithm;
import std.typecons;
import std.container;

immutable int mod = cast(int)1e9 + 7;
alias pair = Tuple!(int, "x", int, "y");

int N, K;
pair[] A;

int mul(int x, int y) {
	int ans = 1;
	for (int i = 0; (1 << i) <= y; ++i) {
		if (y & (1 << i)) ans = cast(int)(cast(long)1 * ans * x % mod);
		x = cast(int)(cast(long)x * x % mod);
	}
	return ans;
}

void main() {
	readf("%d %d\n", &N, &K);
	A ~= pair(cast(int)1e9 + 5, 0);
	foreach(i; 0..N) {
		int x, y; readf("%d %d\n", &x, &y);
		A ~= [pair(x, 1), pair(y + 1, -1)];
	}
	sort!`a.x < b.x`(A);
	int cnt = 0, ways = 0;
	int ans = 0;
	for (int i = 0; i + 1 < A.length; ++i) {
		int st = i;
		while (i + 1 < A.length && A[i].x == A[st].x) {
			if (A[i].y == 1) {
				++cnt;
				if (cnt == K) ways = 1;
				else ways = cast(int)(cast(long)cnt * ways % mod * mul(cnt - K, mod - 2) % mod);
			} else if (A[i].y == -1) {
				--cnt;
				if (cnt < K) ways = 0;
				else ways = cast(int)(cast(long)ways * mul(cnt + 1, mod - 2) % mod * (cnt - K + 1) % mod);
			}
			++i;
		} --i;
		//writeln(A[st].x, ' ', cnt, ' ', ways * (A[i + 1].x - A[i].x));
		ans = (ans + cast(long)ways * (A[i + 1].x - A[i].x) % mod) % mod;
	}
	writeln(ans);
}

import std.stdio, std.conv;
import std.algorithm, std.range, std.random;
import std.string, std.array, std.container, std.bigint;
import std.exception;

int main() {
    immutable MN = 200200;
    Mint[] fact = new Mint[](MN), iFac = new Mint[](MN);
    fact[0] = Mint(1);
    foreach (i; 1..MN) {
        fact[i] = fact[i-1] * Mint(i);
    }
    foreach (i; 0..MN) {
        iFac[i] = Mint.inv(fact[i]);
    }
    Mint C(int n, int k) {
        return fact[n]*iFac[k]*iFac[n-k];
    }
    int n, k;
    readf("%d %d\n", &n, &k);
    alias P = int[2];
    int[2][] ev;
    foreach (i; 0..n) {
        int l, r;
        readf("%d %d\n", &l, &r);
        ev ~= [l, 0];
        ev ~= [r+1, 1];
    }
    ev.sort;
    int co = 0;
    Mint ans = 0;
    foreach (i, e; ev) {
        if (e[1] == 0) co++;
        else co--;

        if (i < ev.length-1 && ev[i+1][0] != ev[i][0]) {
            Mint di = Mint(ev[i+1][0]-ev[i][0]);
            if (k <= co) {
                ans += di * C(co, k);
            }
        }
    }
    writeln(ans);
	return 0;
}

T pow(T)(T x, ulong n) {
    T r = 1;
    while (n) {
        if (n & 1) r *= x;
        x *= x;
        n >>= 1;
    }
    return r;
}

struct ModInt(uint MD) {
    import std.conv : to;
    uint v;
    this(long v) {this.v = (v%MD+MD)%MD;}
    auto normS(uint x) {return (x<MD)?x:x-MD;};
    auto opBinary(string op:"+")(ModInt r) {return ModInt(normS(v+r.v));};
    auto opBinary(string op:"-")(ModInt r) {return this+ModInt(MD-r.v);};
    auto opBinary(string op:"*")(ModInt r) {return ModInt(cast(ulong)v*r.v%MD);};
    auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}
    static ModInt inv(Mint x) { return pow(x, MD-2); }
    string toString() {return v.to!string;}
}
//alias Mint = ModInt!(10^^9+7);
alias ModInt!(10^^9+7) Mint;
string readToken() {
    import std.stdio : readln;
    import std.string : split;
    static size_t pos;
    static string[] tokens;
    while (!(pos < tokens.length)) {
        pos = 0;
        tokens = readln.split;
    }
    return tokens[pos++];
}
T read(T)() {
    import std.conv : to;
    return readToken.to!T;
}


import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	int n = read.to!int;
	int[] as;
	foreach(i; 0 .. n) as ~= read.to!int;

	int f = 0;
	int last = -10;
	foreach(a; as){
		if(last < a){
			if(f == 1){
				"NO".writeln;
				return;
			}
		}
		if(last > a){
			if(f == 0) f = 1;
		}
		last = a;
	}

	"YES".writeln;
	return;

}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;
	long pos = MIN_POS!"a > b"(a);
	int l = cast(int)pos-1, r = cast(int)pos+1;
	long top = n;
	bool ans = true;
	while (top != 1)
	{
		if (l >= 0)
		{
			if (a[l] == top-1)
			{
				--l;
				--top;
				continue;
			}
		}
		if (r < n)
		{
			if (a[r] == top-1)
			{
				++r;
				--top;
				continue;
			}
		}
		ans = false;
		break;
	}

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

import std.algorithm.searching : maxIndex;
import std.algorithm.sorting : isSorted;
import std.stdio;

void main()
{
  char c;
  int n;
  readf!"%d\n"(n);
  auto a = new int[n];
  foreach (i; 0..n) readf!"%d%c"(a[i], c);

  auto i = maxIndex(a);
  if (isSorted(a[0..i]) && isSorted!"a > b"(a[i+1..$])) {
    writeln("YES");
  } else {
    writeln("NO");
  }
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;
	long pos = MIN_POS!"a > b"(a);
	int l = cast(int)pos-1, r = cast(int)pos+1;
	long top = n;
	bool ans = true;
	while (top != 1)
	{
		if (l >= 0)
		{
			if (a[l] == top-1)
			{
				--l;
				--top;
				continue;
			}
		}
		if (r < n)
		{
			if (a[r] == top-1)
			{
				--r;
				--top;
				continue;
			}
		}
		ans = false;
		break;
	}

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


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

void main() {
    int n = readln.chomp.to!int;
    ulong[] s = readln.chomp.split.map!(to!ulong).array;

    ulong ans = s.sum;
    if (ans & 1) {
        ans -= s.filter!"a & 1".array.minPos[0];
    }

    ans.writeln;
}

import std.stdio;
import std.conv;
import std.string;
import std.array: Appender;

void main()
{
	auto n = split(strip(readln))[0];
	auto s = split(strip(readln));
	long[] a = new long[to!int(n,10)];
	long sum;
	long min = long.max;
	foreach(i, el; s)
	{
		a[i] = to!long(el,10);
		sum += a[i];
		if (a[i] % 2 != 0 && min > a[i])
		{
			min = a[i];
		}
	}
	if (sum % 2 != 0)
		sum -= min;
	writeln(sum);
}

import std.stdio,std.array,std.algorithm;
void main()
{
	stdin.readln;
	auto v=stdin.readln.split.map!"to!ulong(a)";
	auto s=v.sum;
	writeln(s%2?s-v.filter!"a%2".reduce!"a<b?a:b":s);
}

import std.stdio,std.algorithm;
long n,no,ne,mino,so,se,temp;
void main()
{
	scanf(" %d",&n);
	mino=long.max;
	for(int i=0;i<n;++i)
	{
		scanf(" %d",&temp);
		if(temp%2)
		{
			mino=min(mino,temp);
			so+=temp;
			++no;
		}else{
			se+=temp;
			++ne;
		}
	}
	writeln(se+so-(no%2?mino:0));
}

import std.stdio,std.algorithm;
long n,t,s,m=long.max;
void main()
{
	scanf(" %d",&n);
	foreach(i;0..n)
	{
		scanf(" %d",&t);
		s+=t;
		if(t%2) m=min(m,t);
	}
	writeln(s%2?s-m:s);
}


module main;

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

int main() {

    auto s = readln().strip();

    char[] stack;
    string open = "({[<";
    string close = ")}]>";

    int result;

    bool flag = true;
    foreach (int i; 0..s.length)
        if (canFind(open, s[i])) {
            stack.assumeSafeAppend();
            stack ~= s[i];
        } else {
            if (stack.length == 0 || canFind(stack.back.to! (string), close)) {
                flag = false;
                break;
            }

            if (s[i] == ')' && stack.back != '(' || s[i] == '}' && stack.back != '{' || s[i] == ']' &&
                stack.back != '[' || s[i] == '>' && stack.back != '<')
                    result++;

            stack.popBack();
        }

    writeln((flag && stack.length == 0) ? result.to! (string) : "Impossible");

	return 0;
}

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

immutable int NA = -1;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		int n = s.length;
		auto t = '*'.repeat (n).array;
		t.reserve (n * 2);
		int res = 0;
		foreach (char c; s)
		{
			if (c == '<')
			{
				t ~= '>';
			}
			else if (c == '{')
			{
				t ~= '}';
			}
			else if (c == '[')
			{
				t ~= ']';
			}
			else if (c == '(')
			{
				t ~= ')';
			}
			else if (t.back == '*')
			{
				res = NA;
				break;
			}
			else
			{
				res += (c != t.back);
				t.popBack ();
				t.assumeSafeAppend ();
			}
		}
		if (t.length != n || res == NA)
		{
			writeln ("Impossible");
		}
		else
		{
			writeln (res);
		}
	}
}

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

immutable int NA = -1;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		int n = s.length;
		auto t = '*'.repeat (n).array;
		t.reserve (n * 2);
		int res = 0;
		foreach (char c; s)
		{
			if (c == '<')
			{
				t ~= '>';
			}
			else if (c == '{')
			{
				t ~= '}';
			}
			else if (c == '[')
			{
				t ~= ']';
			}
			else if (c == '(')
			{
				t ~= ')';
			}
			else if (t.back == '*')
			{
				res = NA;
				break;
			}
			else
			{
				res += (c != t.back);
				t.popBack ();
				t.assumeSafeAppend ();
			}
		}
		writeln (equal (t, '*'.repeat (n)) ? res : NA);
	}
}


import std.algorithm;
import std.container;
import std.stdio;

void main ()
{
    int n, k;
    while (readf (" %s %s", &n, &k) > 0)
    {
        if (k == 1)
        {
            k = 0;
        }

        auto c = redBlackTree !(long);
        foreach (i; 0..n)
        {
            int a;
            readf (" %s", &a);
            c.insert (a);
        }

        int res;
        foreach (e; c)
        {
            c.removeKey (e * k);
            res++;
        }
        writefln ("%s", res);
    }
}

import std.algorithm;
import std.stdio;

void main ()
{
    int n, k;
    while (readf (" %s %s", &n, &k) > 0)
    {
        if (k == 1)
        {
            k = 0;
        }
        auto a = new long [n];
        foreach (i; 0..n)
        {
            readf (" %s", &a[i]);
        }
        sort (a);
        int j;
        int res = n;
        foreach (i; 0..n)
        {
            while (j < n && a[i] * k > a[j])
            {
                j++;
            }
            if (j < n && a[i] * k == a[j])
            {
                a[j] = -1;
                res--;
                j++;
            }
        }
        writefln ("%s", res);
    }
}

import std.algorithm;
import std.stdio;

void main ()
{
    int n, k;
    while (readf (" %s %s", &n, &k) > 0)
    {
        auto a = new long [n];
        foreach (i; 0..n)
        {
            readf (" %s", &a[i]);
        }
        sort (a);
        int j;
        int res = n;
        foreach (i; 0..n)
        {
            while (j < n && a[i] * k > a[j])
            {
                j++;
            }
            if (j < n && a[i] * k == a[j])
            {
                a[i] = -1;
                res--;
                j++;
            }
        }
        writefln ("%s", res);
    }
}

import std.algorithm;
import std.stdio;

void main ()
{
    int n, k;
    while (readf (" %s %s", &n, &k) > 0)
    {
        auto a = new long [n];
        foreach (i; 0..n)
        {
            readf (" %s", &a[i]);
        }
        sort (a);
        int j;
        int res = n;
        foreach (i; 0..n)
        {
            while (j < n && a[i] * k > a[j])
            {
                j++;
            }
            if (j < n && a[i] * k == a[j])
            {
                a[j] = -1;
                res--;
                j++;
            }
        }
        writefln ("%s", res);
    }
}