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

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

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

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

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

        bool check(int k) {
          int now;
          foreach (i; 0 .. N) {
            if (now <= B[i] && k - 1 - now <= A[i]) {
              ++now;
            }
          }
          return (now >= k);
        }

        int lo = 0, hi = N + 1;
        for (; lo + 1 < hi; ) {
          const mid = (lo + hi) / 2;
          (check(mid) ? lo : hi) = mid;
        }
        writeln(lo);
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

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

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

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

		bool f(long x)
		{
			long cnt;
			foreach (i; 0..n)
			{
				if (cnt > b[i]) continue;
				if (x-cnt-1 > a[i]) continue;
				++cnt;
				if (cnt == x) break;
			}
			return cnt == x;
		}
		ans[ti] = binarySearch!(f)(0, n+1);
	}

	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 n;
		readf !(" %s") (n);
		auto a = new int [n];
		auto b = new int [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s") (a[i], b[i]);
		}

		bool ok (int lim)
		{
			int down = 0;
			int up = lim - 1;
			foreach (i; 0..n)
			{
				if (b[i] >= down && a[i] >= up)
				{
					down += 1;
					up -= 1;
					if (up < 0)
					{
						return true;
					}
				}
			}
			return false;
		}

		int lo = 1;
		int hi = n + 1;
		while (hi - lo > 1)
		{
			int me = (lo + hi) / 2;
			if (ok (me))
			{
				lo = me;
			}
			else
			{
				hi = me;
			}
		}
		writeln (lo);
	}
}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = new int[](n);
	auto b = new int[](n);
	foreach(i; 0 .. n)
	{
		a[i] = readInt!int;
		b[i] = readInt!int;
	}
	bool can(int k)
	{
		int left = 0;
		int right = k - 1;
		int elems = 0;
		foreach(i; 0 .. n)
		{
			if (right <= a[i] && left <= b[i]) { left++, right--; elems++;}
		}
		return elems >= k;
	}
	int hi = n;
	int lo = 0;
	int ans = -1;
	while (lo <= hi)
	{
		int mi = (lo + hi)/2;
		if (can(mi))
		{
			ans = mi;
			lo = mi + 1;
		}
		else
		{
			hi = mi - 1;
		}
	}
	assert(ans != -1);
	return writeln(ans);
}

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

// 提出解
void solve(){
	foreach(_; 0 .. scan!int){
		int n = scan!int;
		int[] as, bs;
		foreach(i; 0 .. n) as ~= scan!int, bs ~= scan!int;
		log("as:", as);
		log("bs:", bs);

		int calc(int k){
			int[] cs;
			foreach(i; 0 .. n) cs ~= k - 1 - as[i]; // 自分より貧乏な人数の下限
			int cnt;
			foreach(i; 0 .. n){
				if(cs[i] <= cnt && cnt <= bs[i]) cnt += 1;
			}
			log("k:", k, "cs:", cs, "cnt:", cnt);
			return cnt;
		}
		bool isOK(int k){
			return calc(k) >= k;
		}

		int ans = mid(1, n + 2, &isOK) - 1;
		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.stdio;
import std.algorithm;

const int N = 200000;

class Request
{
	int arrivalTime;
	int executionTime;
	long readyTime;
}

class Server
{
	private Request[N] queue;

	private int queueStart;

	private int queueEnd;

	private int queueSize;

	private long currentTime;

	public this(int queueSize)
	{
		this.queueSize = queueSize;
	}

	private void processUpTo(long time)
	{
		while (currentTime <= time && queueEnd > queueStart) {
			currentTime += queue[queueStart].executionTime;
			queue[queueStart].readyTime = currentTime;
			queueStart++;
		}
	}

	void enqueue(Request request)
	{
		processUpTo(request.arrivalTime);
		if (queueEnd - queueStart >= queueSize) {
			request.readyTime = -1;
		}
		else {
			currentTime = max(currentTime, request.arrivalTime);
			queue[queueEnd] = request;
			queueEnd++;
		}
	}

	void finish()
	{
		processUpTo(long.max);
	}
}

void main()
{
	int nRequests;
	int queueSize;

	readf("%d %d", &nRequests, &queueSize);

	Server s = new Server(queueSize);
	Request[] requests = new Request[](nRequests);
	for (int i = 0; i < nRequests; i++) {
		Request r = new Request();

		readf(" %d %d", &r.arrivalTime, &r.executionTime);
		requests[i] = r;

		s.enqueue(r);
	}
	s.finish();

	for (int i = 0; i < nRequests; i++) {
		writef("%d", requests[i].readyTime);
		writef(i < nRequests - 1 ? " " : "\n");
	}
}

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

void main ()
{
	int n;
	int b;
	while (readf (" %s %s", &n, &b) > 0)
	{
		alias Query = Tuple !(long, q{t}, int, q{d});
		auto q = new Query [n];
		foreach (ref r; q)
		{
			readf (" %s %s", &r.t, &r.d);
		}
		q ~= Query (long.max, int.max);

		auto a = new long [n];
		int [] s;
		long c = 0;
		foreach (i; 0..n + 1)
		{
			while (!s.empty && c <= q[i].t)
			{
				int k = s.front;
				s.popFront ();
				s.assumeSafeAppend ();
				c += q[k].d;
				a[k] = c;
			}
			c = max (c, q[i].t);

			if (s.length >= b)
			{
				a[i] = -1;
			}
			else
			{
				s ~= i;
			}
		}
		writefln ("%(%s %)", a);
	}
}

import std.stdio;
import std.algorithm;

const int N = 200000;

class Request
{
	int arrivalTime;
	int executionTime;
	int readyTime;
}

class Server
{
	private Request[N] queue;

	private int queueStart;

	private int queueEnd;

	private int queueSize;

	private int currentTime;

	public this(int queueSize)
	{
		this.queueSize = queueSize;
	}

	private void processUpTo(int time)
	{
		while (currentTime <= time && queueEnd > queueStart) {
			currentTime += queue[queueStart].executionTime;
			queue[queueStart].readyTime = currentTime;
			queueStart++;
		}
	}

	void enqueue(Request request)
	{
		processUpTo(request.arrivalTime);
		if (queueEnd - queueStart >= queueSize) {
			request.readyTime = -1;
		}
		else {
			currentTime = max(currentTime, request.arrivalTime);
			queue[queueEnd] = request;
			queueEnd++;
		}
	}

	void finish()
	{
		processUpTo(int.max);
	}
}

void main()
{
	int nRequests;
	int queueSize;

	readf("%d %d", &nRequests, &queueSize);

	Server s = new Server(queueSize);
	Request[] requests = new Request[](nRequests);
	for (int i = 0; i < nRequests; i++) {
		Request r = new Request();

		readf(" %d %d", &r.arrivalTime, &r.executionTime);
		requests[i] = r;

		s.enqueue(r);
	}
	s.finish();

	for (int i = 0; i < nRequests; i++) {
		writef("%d", requests[i].readyTime);
		writef(i < nRequests - 1 ? " " : "\n");
	}
}


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

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

		int mex (int [] a)
		{
			auto b = new bool [n + 1];
			foreach (i; 0..n)
			{
				b[a[i]] = true;
			}
			int res = 0;
			while (b[res])
			{
				res += 1;
			}
			return res;
		}

		int [] answer;
		while (!equal (a, n.iota))
		{
			auto v = mex (a);

			void set (int pos)
			{
				answer ~= pos + 1;
				a[pos] = v;
			}
			if (v < n)
			{
				set (v);
			}
			else
			{
				int pos = 0;
				while (a[pos] == pos)
				{
					pos += 1;
				}
				set (pos);
			}
		}
		writeln (answer.length);
		writefln !("%(%s %)") (answer);
	}
}

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

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

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

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

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

        int[] ans;
        auto as = A.dup;
        for (; ; ) {
          auto app = new bool[N];
          foreach (i; 0 .. N) {
            if (as[i] < N) {
              app[as[i]] = true;
            }
          }
          int x;
          for (x = 0; x < N; ++x) {
            if (!app[x]) {
              break;
            }
          }
          if (x == N) {
            int im = -1;
            foreach (i; 0 .. N) {
              if (as[i] != i) {
                if (im == -1 || as[im] > as[i]) {
                  im = i;
                }
              }
            }
            if (im == -1) {
              break;
            }
            ans ~= im;
            as[im] = x;
          } else {
            ans ~= x % N;
            as[x % N] = x;
          }
          debug {
            writeln("as = ", as);
          }
        }

        writeln(ans.length);
        foreach (h, i; ans) {
          if (h > 0) write(" ");
          write(i + 1);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int;

		BinaryHeap!(Array!int, "a > b") heap;
		foreach (i; 0..n)
		{
			heap.insert(a[i]);
		}

		int i;
		while (true)
		{
			int[] tmp;
			int x;
			while (!heap.empty)
			{
				x = heap.front; heap.removeFront;
				tmp ~= x;
				debug writeln("i:", i, " ", "x:", x, " ", tmp);
				debug writeln(a);
				if (x > i) break;
				i = x+1;
			}
			int ii = -1;
			if (i == n || tmp.empty)
			{
				bool ok = true;
				foreach_reverse (j; 0..n)
				{
					if (a[j] != j)
					{
						i = j;
						ii = n;
						ok = false;
						break;
					}
				}
				if (ok)
				{
					break;
				}
			}

			auto y = a[i];
			if (ii != -1)
			{
				a[i] = ii;
				heap.insert(ii);
			}
			else
			{
				a[i] = i;
				heap.insert(i);
			}
			ans[ti] ~= i+1;
			i = min(i+1, y);

			BinaryHeap!(Array!int, "a > b") nHeap;
			bool done;
			foreach (e; tmp)
			{
				if (!done)
				{
					if (e == y)
					{
						done = true;
						continue;
					}
				}
				nHeap.insert(e);
			}
			while (!heap.empty)
			{
				auto z = heap.front; heap.removeFront;
				if (!done)
				{
					if (z == y)
					{
						done = true;
						continue;
					}
				}
				nHeap.insert(z);
			}
			heap = nHeap;
		}
	}

	foreach (e; ans)
	{
		writeln(e.length);
		e.map!(to!string).join(" ").writeln;
	}
	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();
        auto A = new int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt();
        }

        auto ans = new int[N + 1];
        auto as = A.dup;
        foreach (h; 0 .. N + 1) {
          auto app = new bool[N + 1];
          foreach (i; 0 .. N) {
            if (as[i] <= N) {
              app[as[i]] = true;
            }
          }
          foreach (x; 0 .. N + 1) {
            if (!app[x]) {
              ans ~= x % N;
              as[x % N] = x;
              break;
            }
          }
          debug {
            writeln("as = ", as);
          }
        }

        writeln(ans.length);
        foreach (h, i; ans) {
          if (h > 0) write(" ");
          write(i + 1);
        }
        writeln;
      }
    }
  } 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 N = readInt();
        auto A = new int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt();
        }

        auto ans = new int[N + 1];
        auto as = A.dup;
        foreach (h; 0 .. 2 * N) {
          auto app = new bool[N];
          foreach (i; 0 .. N) {
            if (as[i] < N) {
              app[as[i]] = true;
            }
          }
          int x;
          for (x = 0; x < N; ++x) {
            if (!app[x]) {
              break;
            }
          }
          if (x == N) {
            bool found;
            foreach (i; 0 .. N) {
              if (as[i] != i) {
                found = true;
                ans ~= i;
                as[i] = x;
                break;
              }
            }
            if (!found) {
              break;
            }
          } else {
            ans ~= x % N;
            as[x % N] = x;
          }
          debug {
            writeln("as = ", as);
          }
        }

        writeln(ans.length);
        foreach (h, i; ans) {
          if (h > 0) write(" ");
          write(i + 1);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int;

		BinaryHeap!(Array!int, "a > b") heap;
		foreach (i; 0..n)
		{
			heap.insert(a[i]);
		}

		int i;
		while (true)
		{
			int[] tmp;
			int x;
			while (!heap.empty)
			{
				x = heap.front; heap.removeFront;
				tmp ~= x;
				debug writeln("i:", i, " ", "x:", x, " ", tmp);
				debug writeln(a);
				if (x > i) break;
				i = x+1;
			}
			if (i == n || tmp.empty)
			{
				bool ok = true;
				foreach_reverse (j; 0..n)
				{
					if (a[j] != j)
					{
						i = j;
						ok = false;
						break;
					}
				}
				if (ok)
				{
					break;
				}
			}

			auto y = a[i];
			a[i] = i;
			ans[ti] ~= i+1;
			heap.insert(i);
			i = min(i+1, y);

			BinaryHeap!(Array!int, "a > b") nHeap;
			bool done;
			foreach (e; tmp)
			{
				if (!done)
				{
					if (e == y)
					{
						done = true;
						continue;
					}
				}
				nHeap.insert(e);
			}
			while (!heap.empty)
			{
				auto z = heap.front; heap.removeFront;
				if (!done)
				{
					if (z == y)
					{
						done = true;
						continue;
					}
				}
				nHeap.insert(z);
			}
			heap = nHeap;
		}
	}

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


immutable multi = true;

void solve(int tc)
{
	auto s = readString;
	int i = 0;
	int blocks = 0;
	int minLength = int.max;
	while (i < s.length)
	{
		blocks ^= 1;
		char ch = s[i];
		int len = 0;
		while (i < s.length && s[i] == ch) { i++; len++; }
		minLength = min(len, minLength);
	}
	if (blocks) return writeln(s);
	write(s[0] == 'a'? 'b' : 'a');
	writeln(s[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.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip.dup;
		auto n = s.length.to !(int);
		string res;
		foreach (i; 0..n + 1)
		{
			if (i < n)
			{
				s[i] ^= 3;
			}
			if (s.count ("ab") == s.count ("ba"))
			{
				res = s.idup;
			}
			if (i < n)
			{
				s[i] ^= 3;
			}
		}
		writeln (res);
	}
}

immutable multi = true;

void solve(int tc)
{
	auto s = readString;
	int i = 0;
	int blocks = 0;
	int minLength = int.max;
	while (i < s.length)
	{
		blocks ^= 1;
		char ch = s[i];
		int len = 0;
		while (i < s.length && s[i] == ch) { i++; len++; }
		minLength = min(len, minLength);
	}
	if (blocks) return writeln(s);
	i = 0;
	while (i < s.length)
	{
		char ch = s[i];
		int len = 0;
		while (i < s.length && s[i] == ch) { i++; len++; }
		if (len == minLength)
		{
			char otherCh = ch == 'a'? 'b' : 'a';
			foreach(_; 0 .. len) write(otherCh);
			minLength = int.max;
		}
		else
		{
			foreach(_; 0 .. len) write(ch);
		}
	}
	writeln;
}

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

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

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

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

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


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() {
  /*
  debug {
    foreach (n; 1 .. 5 + 1) {
      auto as = iota(n).array;
      do {
        int[][] invs;
        foreach (i; 0 .. n) foreach (j; i + 1 .. n) {
          if (as[i] > as[j]) {
            invs ~= [i, j];
          }
        }
        const invsLen = cast(int)(invs.length);
        writeln(as);
        bool found;
        auto perm = iota(invsLen).array;
        do {
          auto bs = as.dup;
          foreach (k; 0 .. invsLen) {
            swap(bs[invs[perm[k]][0]], bs[invs[perm[k]][1]]);
          }
          if (bs == iota(n).array) {
            found = true;
            foreach (k; 0 .. invsLen) {
              write(" ", invs[perm[k]]);
            }
            writeln;
          }
        } while (perm.nextPermutation);
        if (!found) {
          writeln("no solution");
        }
      } while (as.nextPermutation);
    }
  }
  //*/

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

      Tuple!(int, int)[] ps;
      foreach (i; 0 .. N) {
        ps ~= tuple(A[i], i);
      }
      ps.sort;
      auto as = new int[N];
      foreach (i; 0 .. N) {
        as[ps[i][1]] = i;
      }
      debug {
        writeln("as = ", as);
      }

      auto poss = new int[N];
      foreach (i; 0 .. N) {
        poss[as[i]] = i;
      }
      int[][] ans;
      foreach (h; 0 .. N - 1) {
        foreach (a; 0 .. N - 1) {
          const i = poss[a];
          const j = poss[a + 1];
          if (i > j) {
            ans ~= [j, i];
            swap(as[i], as[j]);
            swap(poss[a], poss[a + 1]);
          }
        }
      }

      writeln(ans.length);
      foreach (p; ans) {
        writeln(p[0] + 1, " ", p[1] + 1);
      }
    }
  } 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 !(long)).array;
		foreach (i; 0..n)
		{
			a[i] = a[i] * n + i;
		}

		alias Pair = Tuple !(int, q{u}, int, q{v});
		Pair [] answer;
		auto inv = new int [] [n];
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				if (a[i] > a[j])
				{
					inv[i] ~= j;
				}
			}
		}

		void apply (int i, int j)
		{
			answer ~= Pair (i + 1, j + 1);
			swap (a[i], a[j]);
		}

		foreach (i; 0..n)
		{
			inv[i].schwartzSort !(j => a[j]);
			foreach_reverse (j; inv[i])
			{
				apply (i, j);
			}
		}
		debug {writeln (a);}

		writeln (answer.length);
		foreach (p; answer)
		{
			writeln (p.u, " ", p.v);
		}
	}
}


module sigod.codeforces.p298B;

import std.stdio;
import std.string;

private {
	struct Direction
	{
		int l_x = 0;
		int l_y = 0;
		int r_x = 0;
		int r_y = 0;

		ref Direction opOpAssign(string op)(in Direction direction)
			if (op == "+")
		{
			l_x += direction.l_x;
			l_y += direction.l_y;
			r_x += direction.r_x;
			r_y += direction.r_y;

			return this;
		}
	}
}

void main()
{
	int t, sx, sy, ex, ey;
	stdin.readf(" %s %s %s %s %s", &t, &sx, &sy, &ex, &ey);

	string direction;
	stdin.readf(" %s", &direction);
	direction = direction.strip();

	Direction[char] compas;
	compas['E'] = Direction(0, 0, 1, 0);
	compas['S'] = Direction(0, 0, 0, -1);
	compas['W'] = Direction(-1, 0, 0, 0);
	compas['N'] = Direction(0, 1, 0, 0);

	Direction zone = Direction(sx, sy, sx, sy);

	foreach (index, way; direction) {
		zone += compas[way];

		if (zone.l_x <= ex && zone.r_x >= ex
			&& zone.l_y >= ey && zone.r_y <= ey)
		{
			stdout.writeln(index + 1);
			return;
		}
	}

	stdout.writeln("-1");
}

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

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

    int t, sx, sy, ex, ey;
    readf(" %s %s %s %s %s\n", &t, &sx, &sy, &ex, &ey);
    char c;
    int et = 0;
    foreach ( l; 0 .. t ) {
        readf(" %s", &c);
        if (c == 'N' && ey > sy) {
            ++sy;
        }
        else if (c == 'S' && ey < sy) {
            --sy;
        }
        else if (c == 'E' && ex > sx) {
            ++sx;
        }
        else if (c == 'W' && ex < sx) {
            --sx;
        }
        ++et;
        if (sx == ex && sy == ey) {
            writeln(et);
            return 0;
        }
    }
    writeln("-1");

    return 0;
}


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

long[] arr;

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

    arr = 0 ~ readln.splitter.map!( to!long ).array;

    debug { writeln( arr ); }

    long ans = 0;
    foreach_reverse ( bt; 0..64) {
        long cur = ans | (1L << bt);

        auto ok = new bool [] [] ( n+1, k+1 );
        foreach ( row; ok ) row.fill ( false );
        ok[0][0] = true;

        foreach ( i; 1..n+1 ) {
            foreach ( gr; 1..k+1 ) {

                if ( !ok[ i-1 ][ gr-1 ] ) continue;

                long cursum = 0;
                foreach ( j; i..n+1 ) {
                    cursum += arr[ j ];
                    ok[ j ][ gr ] |= ( cursum & cur ) == cur;
                }
            }
        }
        if ( ok[ n ][ k ] ) ans = cur;
    }

    ans.writeln;
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(ulong)).array;
		ulong res = 0UL;
		foreach_reverse (b; 0..64)
		{
			auto f = new bool [] [] (n + 1, k + 1);
			f[0][0] = true;
			foreach (i; 0..n)
			{
				foreach (j; 0..k)
				{
					if (f[i][j])
					{
						ulong s = 0UL;
						foreach (r; i..n)
						{
							s += a[r];
							if ((s & res) == res)
							{
								if (s & (1UL << b))
								{
									f[r + 1][j + 1] = true;
								}
							}
						}
					}
				}
			}
			if (f[n][k])
			{
				res |= 1UL << b;
			}
		}
		writeln (res);
	}
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;
    auto B = new long[][](N, N);
    foreach (i; 0..N) {
        B[i][i] = A[i];
        foreach (j; i+1..N) B[i][j] = B[i][j-1] + A[j];
    }

    auto mem = new bool[][](N+10, K+10);

    bool dfs(int n, int k, long mask) {
        if (k == 0 && n != N-1) return false;
        if (n >= 0 && mem[n][k]) return false;
        if (k > N - n - 1) return false;
        if (n == N-1) return k == 0;

        int left = n+1;
        foreach (right; n+1..N) {
            if ((B[left][right] & mask) >= mask && dfs(right, k-1, mask))
                return true;
        }

        if (n >= 0) mem[n][k] = true;
        return false;
    }

    long m = 0;

    foreach_reverse (i; 0..60) {
        foreach (j; 0..N+10) mem[j].fill(false);
        if (dfs(-1, K, m | (1L << i))) {
            m |= (1L << i);
        }
    }

    m.writeln;
}

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

long[] arr;

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

    arr = 0 ~ readln.splitter.map!( to!long ).array;

    debug { writeln( arr ); }

    long ans = 0;
    foreach_reverse ( bt; 0..64) {
        long cur = ans | ( 1L << bt );

        auto ok = new bool [] [] ( k+1, n+1 );
        ok.each! ( row => row.fill ( false ) );
        ok[0][0] = true;

        foreach ( gr; 1..k+1 ) {
            foreach ( i; 1..n+1 ) {

                if ( !ok[ gr-1 ][ i-1 ] ) continue;

                long cursum = 0;
                foreach ( j; i..n+1 ) {
                    cursum += arr[ j ];
                    ok[ gr ][ j ] |= ( cursum & cur ) == cur;
                }
            }
        }
        if ( ok[ k ][ n ] ) ans = cur;
    }

    ans.writeln;
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;
    auto B = new long[][](N, N);
    foreach (i; 0..N) {
        B[i][i] = A[i];
        foreach (j; i+1..N) B[i][j] = B[i][j-1] + A[j];
    }

    auto mem = new bool[][](N+10, K+10);

    bool dfs(int n, int k, long mask) {
        if (k == 0 && n != N-1) return false;
        if (n >= 0 && mem[n][k]) return false;
        if (k > N - n - 1) return false;
        if (n == N-1) return k == 0;

        int left = n+1;
        foreach (right; n+1..N) {
            if ((B[left][right] & mask) >= mask && dfs(right, k-1, mask))
                return true;
        }

        if (n >= 0) mem[n][k] = true;
        return false;
    }

    long m = 0;

    foreach_reverse (i; 0..55) {
        foreach (j; 0..N+10) mem[j].fill(false);
        if (dfs(-1, K, m | (1L << i))) {
            m |= (1L << i);
        }
    }

    m.writeln;
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!long).array;
    auto B = new long[][](N, N);
    foreach (i; 0..N) {
        B[i][i] = A[i];
        foreach (j; i+1..N) B[i][j] = B[i][j-1] + A[j];
    }

    auto mem = new bool[][](N+10, K+10);

    bool dfs(int n, int k, long mask) {
        if (k == 0 && n != N-1) return false;
        if (n >= 0 && mem[n][k]) return false;
        if (k > N - n - 1) return false;
        if (n == N-1) return k == 0;

        int left = n+1;
        foreach (right; n+1..N) {
            if ((B[left][right] & mask) >= mask && dfs(right, k-1, mask))
                return true;
        }

        if (n >= 0) mem[n][k] = true;
        return false;
    }

    long m = 0;

    foreach_reverse (i; 0..51) {
        foreach (j; 0..N+1) mem[j].fill(false);
        if (dfs(-1, K, m | (1L << i))) {
            m |= (1L << i);
        }
    }

    m.writeln;
}


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()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    auto s = readln.strip.split("").map!(to!int).array;
    auto ans = iota(n).map!(x => tuple(a[x], s[x], x)).array.sort!((x, y) => x[1] == y[1] ? x[0] < y[0] : x[1] < y[1], SwapStrategy.stable).map!(x => x[2]);
    auto ans2 = iota(n).array;
    foreach (i ; 0 .. n)
      ans2[ans[i]] = i + 1;
    writeln(ans2.map!text.join(" "));
  }
}

void main() { runSolver(); }

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

  auto solve() {
    foreach(_; 0..QN) {
      auto N = scan!long;
      auto P = scan!long(N);
      auto S = scan;

      long[] likes, dislikes;
      foreach(i, p; P) if (S[i] == '1') likes ~= p; else dislikes ~= p;

      likes = likes.compress;
      dislikes = dislikes.compress;
      const dl = dislikes.length;

      long[] ans;
      uint l, d;
      foreach(c; S) {
        if (c == '0') ans ~= dislikes[d++] + 1;
        if (c == '1') ans ~= likes[l++] + 1 + dl;
      }

      ans.toAnswerString.writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

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

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

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

void read(S...)(ref S args) {
  auto input = readln.split;
  enforce(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

void main() {
  int T;
  read(T);
  while (T--) {
    int n;
    read(n);
    auto arr = list!int;
    string s = readln;

    int[] good, bad;
    foreach (i; 0 .. n) {
      if (s[i] == '1') good ~= arr[i];
      else bad ~= arr[i];
    }

    sort(good);
    sort(bad);

    int p = n;

    int[int] m;

    foreach (A; [good, bad]) {
      while (!A.empty) {
        m[A.back] = p--;
        A.popBack;
      }
    }

    foreach (i; 0 .. n) {
      writef("%d ", m[arr[i]]);
    }
    writeln;
  }
}

import std;

void main () {
    int test;
    readf("%s\n", test);

    foreach (test_index; 0 .. test) {
        int n;
        readf("%s\n", n);

        int[] p = new int[n];
        string s;

        foreach (i; 0 .. n)
            readf(" %s", p[i]);
        readf!"\n";
        s = readln()[0 .. $ - 1];

        int[] liked;
        int[] disliked;
        foreach (int i, c; s)
            if (c == '0')
                disliked ~= i;
            else
                liked ~= i;

        auto likedV = liked
            .map!(i => tuple(p[i], i))
            .array
            .sort;

        auto dislikedV = disliked
            .map!(i => tuple(p[i], i))
            .array
            .sort;

        //stderr.writeln(likedV, '\n', dislikedV);

        int rating = 1;
        foreach (t; dislikedV) {
            p[t[1]] = rating ++;
        }
        foreach (t; likedV)
            p[t[1]] = rating ++;
        assert(rating == n + 1);
        writefln!"%(%s %)"(p);
    }
}
// ""

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()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    auto s = readln.strip.split("").map!(to!int).array;
    auto ans = iota(n).map!(x => tuple(a[x], s[x], x)).array.sort!((x, y) => x[1] == y[1] ? x[0] < y[0] : x[1] < y[1]).map!(x => x[2] + 1);
    writeln(ans.map!text.join(" "));
  }
}


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 int[][](N, 4);
      foreach (i; 0 .. N) {
        foreach (j; 0 .. 4) {
          A[i][j] = readInt();
        }
      }

      int ans = 1;
      foreach (i; 1 .. N) {
        if (A[0].sum < A[i].sum) {
          ++ans;
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto N = readln.chomp.to!int;
    auto A = N.iota.map!(i => readln.split.map!(to!int).array ~ i).array;
    A.sort!"a.sum-a[4] == b.sum-b[4] ? a[4] < b[4] : a.sum-a[4] > b.sum-b[4]";

    foreach (i; 0..N) {
        if (A[i][4] == 0) {
            writeln(i+1);
        }
    }
}

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

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

    auto t = readln.chomp.split.map!(to!int).sum;

    auto ans = 1;
    foreach (_; 1 .. n) {
        auto s = readln.chomp.split.map!(to!int).sum;
        if (s > t) ++ans;
    }

    ans.writeln;
}

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)
	{
		int [] [] a;
		readln;
		foreach (i; 0..n)
		{
			a ~= i ~ readln.splitter.map !(to !(int)).array;
		}
		a.schwartzSort !(d => tuple (-sum (d[1..$]), d[0]));
		writeln (a.countUntil !(d => d[0] == 0) + 1);
	}
}

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

  struct Student{
    int id, sum;
  }
  int n; rd(n);
  auto students=new Student[](n);
  foreach(i; 0..n){
    auto s=readln.split.to!(int[]).reduce!"a+b";
    students[i]=Student(i, s);
  }
  students.sort!("a.sum==b.sum ? a.id<b.id : a.sum>b.sum");
  foreach(i, student; students){
    if(student.id==0){
      writeln(i+1);
      return;
    }
  }

}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	int[] m = new int[t];
	for (int i=0; i<t; i++)
	{
		int a=0;
		int b=0;
		int c=0;
		int d=0;
		readf(" %d", &a);
		readf(" %d", &b);
		readf(" %d", &c);
		readf(" %d", &d);
		int sum=a+b+c+d;
		m[i]=sum;
	}
	int count=1;
	for (int i=0; i<t; i++)
	{
		if (m[i]>m[0])
		{
			count=count+1;
		}
	}
	writeln(count);
	return 0;
}

import std.stdio;

int main()
{
	int t=0;
	readf(" %d", &t);
	int h=0;
	int j=0;
	int k=0;
	int l=0;
	readf(" %d", &h);
	readf(" %d", &j);
	readf(" %d", &k);
	readf(" %d", &l);
	int tsum=h+j+k+l;
	int pl=1;
	for (int i=0; i<t-1; i++)
	{
		int a=0;
		int b=0;
		int c=0;
		int d=0;
		readf(" %d", &a);
		readf(" %d", &b);
		readf(" %d", &c);
		readf(" %d", &d);
		int sum=a+b+c+d;
		if (sum>=tsum)
		{
			pl=pl+1;
		}
	}
	if (pl==1)
	{
		writeln(pl);
	}
	else
	{
		writeln(pl-1);
	}
	return 0;
}


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

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

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

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

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

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

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

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

void main()
{
    int N; get(N);
    writefln!"? %d %d"(1, N); stdout.flush();
    int p; get(p);
    int q;
    if (p == 1) {
        q = -1;
    } else if (p == N) {
        q = N;
    } else {
        writefln!"? %d %d"(1, p); stdout.flush();
        get(q);
    }
    if (p == q) {
        int l = 1, r = p;
        while (l + 1 < r) {
            auto m = (l + r) / 2;
            writefln!"? %d %d"(m, p); stdout.flush();
            get(q);
            if (p == q) {
                l = m;
            } else {
                r = m;
            }
        }
        writeln("! ", l); stdout.flush();
    } else {
        int l = p, r = N;
        while (l + 1 < r) {
            auto m = (l + r) / 2;
            writefln!"? %d %d"(p, m); stdout.flush();
            get(q);
            if (p == q) {
                r = m;
            } else {
                l = m;
            }
        }
        writeln("! ", r); stdout.flush();
    }
}

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;

	int l = 1, r = n;
	writeln("? ", l, " ", r);
	stdout.flush;
	auto m = RD!int;
	while (r - l > 1)
	{
		auto m2 = (l+r)/2;
		if (m <= m2)
		{
			auto ll = min(m, l);
			auto rr = m2;
			writeln("? ", ll, " ", rr);
			stdout.flush;
			auto a = RD!int;
			if (a == m)
				r = m2;
			else
				l = m2;
		}
		else
		{
			auto ll = m2;
			auto rr = max(m, r);
			writeln("? ", ll, " ", rr);
			stdout.flush;
			auto a = RD!int;
			if (a == m)
				l = m2;
			else
				r = m2;
		}
	}

	writeln("? ", l, " ", r);
	stdout.flush;
	m = RD!int;
	if (m == l)
		writeln("! ", r);
	else
		writeln("! ", l);
	stdout.flush;
	debug readln;
}

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

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

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

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

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

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

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

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

void main()
{
    int N; get(N);
    writefln!"? %d %d"(1, N); stdout.flush();
    int p; get(p);
    writefln!"? %d %d"(1, p); stdout.flush();
    int q; get(q);
    if (p == q) {
        int l = 1, r = p;
        while (l + 1 < r) {
            auto m = (l + r) / 2;
            writefln!"? %d %d"(m, p); stdout.flush();
            get(q);
            if (p == q) {
                l = m;
            } else {
                r = m;
            }
        }
        writeln("! ", l); stdout.flush();
    } else {
        int l = p, r = N;
        while (l + 1 < r) {
            auto m = (l + r) / 2;
            writefln!"? %d %d"(p, m); stdout.flush();
            get(q);
            if (p == q) {
                r = m;
            } else {
                l = m;
            }
        }
        writeln("! ", r); stdout.flush();
    }
}


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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, x;
		readf !(" %s %s") (n, x);
		readln;
		auto s = readln.splitter.map !(to !(int)).array;
		auto odds = s.count !(q{a % 2 != 0}).to !(int);
		auto evens = s.length.to !(int) - odds;
		bool ok = false;
		foreach (i; 0..x + 1)
		{
			auto j = x - i;
			if (i <= odds && j <= evens)
			{
				if (i % 2 != 0)
				{
					ok = true;
				}
			}
		}
		writeln (ok ? "YES" : "NO");
	}
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 x = RD!int;
		auto a = RDA;

		long e, o;
		foreach (i; 0..n)
		{
			if (a[i] % 2)
				++o;
			else
				++e;
		}

		if (o == 0) continue;

		auto y = min(o, x);
		if (y % 2 == 0)
		{
			--y;
		}
		x -= y;
		ans[ti] = e >= x;
	}

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


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

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

    auto s = readln.chomp;

    auto seg = cast(int)(s[0] == '0');
    foreach (a, b; lockstep(s, s.dropOne)) {
        if (a == '1' && b == '0') ++seg;
    }

    if (seg == 0) {
        writeln(0);
        return;
    }

    auto ans = min(cast(long)seg * y, cast(long)(seg - 1) * x + y);

    ans.writeln;
}

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

void main ()
{
	int n, x, y;
	while (readf (" %s %s %s", &n, &x, &y) > 0)
	{
		readln;
		auto s = readln.strip ~ '1';
		auto k = n.iota.map !(i => s[i..i + 2] == "01").sum;
		long res = 0;
		if (k > 0)
		{
			res += y;
			k -= 1;
		}
		res += k * 1L * min (x, y);
		writeln (res);
	}
}

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.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();
      const X = readLong();
      const Y = readLong();
      const A = readToken();

      long cnt;
      for (int i = 0, j; i < N; i = j) {
        for (j = i; j < N && A[i] == A[j]; ++j) {}
        if (A[i] == '0') {
          ++cnt;
        }
      }
      long ans;
      if (cnt >= 1) {
        ans += (cnt - 1) * min(X, Y);
        ans += Y;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

    auto s = readln.chomp;

    auto seg = cast(int)(s[0] == '0');
    foreach (a, b; lockstep(s, s.dropOne)) {
        if (a == '1' && b == '0') ++seg;
    }

    auto ans = min(cast(long)seg * y, cast(long)(seg - 1) * x + y);

    ans.writeln;
}

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

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

    auto s = readln.chomp;

    if (n == 1) {
        writeln(s[0] == '1' ? 0 : y);
        return;
    }

    auto seg = cast(int)(s[0] == '0');
    foreach (a, b; lockstep(s, s.dropOne)) {
        if (a == '1' && b == '0') ++seg;
    }

    auto ans = min(cast(long)seg * y, cast(long)(seg - 1) * x + y);

    ans.writeln;
}


import std.stdio, std.string;

void solve(int[] a, int n)
{
    auto dp = new int[n];
    auto prev = new int[n];
    int[int] pos;
    foreach (i; 0 .. n)
    {
        dp[i] = 1;
        prev[i] = -1;
        auto val = a[i] - 1;
        if (val in pos)
        {
            prev[i] = pos[val];
            dp[i] = dp[prev[i]] + 1;
        }
        pos[a[i]] = i;
    }
    auto best = 0, idx = -1;
    foreach (i; 0 .. n)
    {
        if (dp[i] > best)
        {
            best = dp[i];
            idx = i;
        }
    }
    writeln(best);
    auto ans = new int[best];
    foreach (i; 0 .. best)
    {
        ans[best - i - 1] = idx + 1;
        idx = prev[idx];
    }
    foreach (i; 0 .. best - 1)
    {
        write(ans[i], " ");
    }
    writeln(ans[best - 1]);
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            readf(" %d", &a[i]);
        }
        readln;
        solve(a, n);
    }
    return 0;
}

import std.stdio, std.string;

void solve(int[] a, int n)
{
    auto dp = new int[n];
    auto prev = new int[n];
    int[int] pos;
    foreach (i; 0 .. n)
    {
        dp[i] = 1;
        prev[i] = -1;
        auto val = a[i] - 1;
        if (val in pos)
        {
            prev[i] = pos[val];
            dp[i] = dp[prev[i]] + 1;
        }
        pos[a[i]] = i;
    }
    auto best = 0, idx = -1;
    foreach (i; 0 .. n)
    {
        if (dp[i] > best)
        {
            best = dp[i];
            idx = i;
        }
    }
    auto ans = new int[best];
    foreach (i; 0 .. best)
    {
        ans[best - i - 1] = idx + 1;
        idx = prev[idx];
    }
    writeln(best);
    foreach (i; 0 .. best - 1)
    {
        write(ans[i], " ");
    }
    writeln(ans[best - 1]);
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        auto a = new int[n];
        foreach (i; 0 .. n)
        {
            readf(" %d", &a[i]);
        }
        readln;
        solve(a, n);
    }
    return 0;
}

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

void main()
{
    readln;

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

    int [int] v;
    a.each!(e => v[e] = max(v.get(e, 0), v.get(e-1, 0) + 1));

    debug { writeln(v); }

    auto p = v.byKeyValue().maxElement!(q{ a.value });
    auto st = p.key - p.value + 1;

    debug { writeln(st); }

    int [] ans;
    foreach (i, e; a.enumerate(1)) {
        if (e == st) {
            ++st;
            ans ~= i;
        }
    }

    writeln(ans.length);
    writefln("%(%s %)", ans);
}

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

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

void main()
{
  int n; readV(n);
  int[] a; readA(n, a);

  int[int] b;
  foreach (i; 0..n) {
    if (a[i]-1 in b) b[a[i]] = b[a[i]-1]+1;
    else             b[a[i]] = 1;
  }

  auto c = -1, m = 0;
  foreach (k, v; b)
    if (v > m) {
      m = v;
      c = k;
    }

  writeln(m);

  auto d = c-m+1;
  foreach (i; 0..n)
    if (a[i] == d) {
      write(i+1, " ");
      ++d;
    }
  writeln;
}