Haha, try to solve this, SelectorUnlimited!— antontrygubO_oYour friends Alice and Bob practice fortune telling.Fortune telling is performed as follows. There is a well-known array $$$a$$$ of $$$n$$$ non-negative integers indexed from $$$1$$$ to $$$n$$$. The tellee starts with some non-negative number $$$d$$$ and performs one of the two operations for each $$$i = 1, 2, \ldots, n$$$, in the increasing order of $$$i$$$. The possible operations are: replace their current number $$$d$$$ with $$$d + a_i$$$ replace their current number $$$d$$$ with $$$d \oplus a_i$$$ (hereinafter $$$\oplus$$$ denotes the bitwise XOR operation)Notice that the chosen operation may be different for different $$$i$$$ and for different tellees.One time, Alice decided to start with $$$d = x$$$ and Bob started with $$$d = x + 3$$$. Each of them performed fortune telling and got a particular number in the end. Notice that the friends chose operations independently of each other, that is, they could apply different operations for the same $$$i$$$.You learnt that either Alice or Bob ended up with number $$$y$$$ in the end, but you don't know whose of the two it was. Given the numbers Alice and Bob started with and $$$y$$$, find out who (Alice or Bob) could get the number $$$y$$$ after performing the operations. It is guaranteed that on the jury tests, exactly one of your friends could have actually gotten that number.HacksYou cannot make hacks in this problem.

On the first line of the input, you are given one number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The following $$$2 \cdot t$$$ lines contain test cases. The first line of each test case contains three numbers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le x \le 10^9$$$, $$$0 \le y \le 10^{15}$$$) — the length of array $$$a$$$, Alice's initial number (Bob's initial number is therefore $$$x+3$$$), and the number that one of the two friends got in the end. The second line of each test case contains $$$n$$$ numbers — the array $$$a$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print the name of the friend who could get the number $$$y$$$: "Alice" or "Bob".

NoteIn the first test case, Alice could get $$$9$$$ using the following operations: $$$7 + 2 = 9$$$.In the second test case, Alice could get $$$2$$$ using this operations: $$$(0 + 1) \oplus 3 = 2$$$.In the third test case, Bob started with $$$x+3 = 0+3=3$$$ and could get $$$1$$$ this way: $$$(((3 + 1) + 2) \oplus 3) \oplus 4 = 1$$$.

// cheese-cracker [2022-02-06]

void solve(){
    long n = scan;
    long x = scan;
    long y = scan;
    auto arr = scanArray;
    long summ = arr.sum + x;
    if(summ % 2 == y % 2){
        writeln("Alice");
    }else{
        writeln("Bob");
    }
}

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

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

import std.stdio, 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 euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
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 bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto x = RD;
		auto y = RD;
		auto a = RDA;

		auto cnt = new long[](60);
		foreach (i; 0..n)
		{
			foreach (j; 0..60)
			{
				auto bit = 1L << j;
				if (a[i] & bit)
					++cnt[j];
			}
		}

		foreach (j; 0..60)
		{
			auto bit = 1L << j;
			if (y & bit)
				--cnt[j];
		}

		foreach (j; 0..60)
		{
			auto bit = 1L << j;
			if (x & bit)
				++cnt[j];
		}

		bool ok = true;
		long add;
		foreach (i; 0..60)
		{
			auto c = cnt[i] + add;
			if (c % 2 && add == 0)
			{
				ok = false;
				break;
			}
			add = c / 2;
		}
		ans[ti] = ok;
	}

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


You are given an array $$$a$$$ of length $$$n$$$. We define the equality of the array as the number of indices $$$1 \le i \le n - 1$$$ such that $$$a_i = a_{i + 1}$$$. We are allowed to do the following operation:  Select two integers $$$i$$$ and $$$x$$$ such that $$$1 \le i \le n - 1$$$ and $$$1 \le x \le 10^9$$$. Then, set $$$a_i$$$ and $$$a_{i + 1}$$$ to be equal to $$$x$$$. Find the minimum number of operations needed such that the equality of the array is less than or equal to $$$1$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10 ^ 5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$

For each test case, print the minimum number of operations needed.

NoteIn the first test case, we can select $$$i=2$$$ and $$$x=2$$$ to form $$$[1, 2, 2, 1, 1]$$$. Then, we can select $$$i=3$$$ and $$$x=3$$$ to form $$$[1, 2, 3, 3, 1]$$$.In the second test case, we can select $$$i=3$$$ and $$$x=100$$$ to form $$$[2, 1, 100, 100, 2]$$$.

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

int solve (int [] a, int n)
{
	int lo = n;
	int hi = -1;
	foreach (i; 0..n - 1)
	{
		if (a[i] == a[i + 1])
		{
			lo = min (lo, i);
			hi = max (hi, i);
		}
	}
	return max (0, hi - lo - 1) + (hi - lo == 1);
}

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;
		writeln (solve (a, n));
	}
}

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[] xs;
        foreach (i; 0 .. N - 1) {
          if (A[i] == A[i + 1]) {
            xs ~= i;
          }
        }

        int ans;
        if (xs.length >= 2) {
          ans = max(xs[$ - 1] - xs[0] - 1, 1);
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


You are given a $$$1$$$ by $$$n$$$ pixel image. The $$$i$$$-th pixel of the image has color $$$a_i$$$. For each color, the number of pixels of that color is at most $$$20$$$.You can perform the following operation, which works like the bucket tool in paint programs, on this image:   pick a color — an integer from $$$1$$$ to $$$n$$$;  choose a pixel in the image;  for all pixels connected to the selected pixel, change their colors to the selected color (two pixels of the same color are considered connected if all the pixels between them have the same color as those two pixels). Compute the minimum number of operations needed to make all the pixels in the image have the same color.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 3\cdot10^3$$$) — the number of pixels in the image. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the colors of the pixels in the image. Note: for each color, the number of pixels of that color is at most $$$20$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\cdot10^3$$$.

For each test case, print one integer: the minimum number of operations needed to make all the pixels in the image have the same color.

NoteIn the first example, the optimal solution is to apply the operation on the third pixel changing its color to $$$2$$$ and then to apply the operation on any pixel that has color $$$2$$$ changing its color and the color of all pixels connected to it to $$$1$$$. The sequence of operations is then: $$$[1, 2, 3, 2, 1] \to [1, 2, 2, 2, 1] \to [1, 1, 1, 1, 1]$$$.In the second example, we can either change the $$$1$$$s to $$$2$$$s in one operation or change the $$$2$$$s to $$$1$$$s also in one operation.In the third example, one possible way to make all the pixels have the same color is to apply the operation on the first, third and the fourth pixel each time changing its color to $$$2$$$.

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

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

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

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

int solve(const(int[]) A) {
  const N = cast(int)(A.length);
  const lim = A.maxElement + 1;
  auto posss = new int[][lim];
  foreach (i; 0 .. N) {
    posss[A[i]] ~= i;
  }
  // dp[i][j] := min cost to color [i, j] in A[i] or A[j]
  auto dp = new int[][](N, N);
  foreach (i; 0 .. N) {
    dp[i][] = N;
    dp[i][i] = 0;
  }
  foreach_reverse (i; 0 .. N) {
    foreach (j; i + 1 .. N) {
      chmin(dp[i][j], dp[i + 1][j] + 1);
      // chmin(dp[i][j], dp[i][j - 1] + 1);
      foreach (k; posss[A[i]]) {
        if (i < k && k <= j) {
          chmin(dp[i][j], dp[i][k - 1] + dp[k][j]);
        }
      }
      foreach (k; posss[A[j]]) {
        if (i <= k && k < j) {
          // chmin(dp[i][j], dp[i][k] + dp[k + 1][j]);
        }
      }
    }
  }
  return dp[0][N - 1];
}

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

        int[] as;
        for (int i = 0, j; i < N; i = j) {
          for (j = i; j < N && A[i] == A[j]; ++j) {}
          as ~= A[i];
        }
        const ans = solve(as);
        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)); }

int solve(const(int[]) A) {
  const N = cast(int)(A.length);
  const lim = A.maxElement + 1;
  auto posss = new int[][lim];
  foreach (i; 0 .. N) {
    posss[A[i]] ~= i;
  }
  // dp[i][j] := min cost to color [i, j] in A[i] or A[j]
  auto dp = new int[][](N, N);
  foreach (i; 0 .. N) {
    dp[i][] = N;
    dp[i][i] = 0;
  }
  foreach_reverse (i; 0 .. N) {
    foreach (j; i + 1 .. N) {
      chmin(dp[i][j], dp[i + 1][j] + 1);
      chmin(dp[i][j], dp[i][j - 1] + 1);
      foreach (k; posss[A[i]]) {
        if (i < k && k <= j) {
          chmin(dp[i][j], dp[i][k - 1] + dp[k][j]);
        }
      }
      foreach (k; posss[A[j]]) {
        if (i <= k && k < j) {
          chmin(dp[i][j], dp[i][k] + dp[k + 1][j]);
        }
      }
    }
  }
  return dp[0][N - 1];
}

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

        int[] as;
        for (int i = 0, j; i < N; i = j) {
          for (j = i; j < N && A[i] == A[j]; ++j) {}
          as ~= A[i];
        }
        const ans = solve(as);
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


You are given a permutation $$$p$$$ of integers from $$$0$$$ to $$$n-1$$$ (each of them occurs exactly once). Initially, the permutation is not sorted (that is, $$$p_i>p_{i+1}$$$ for at least one $$$1 \le i \le n - 1$$$). The permutation is called $$$X$$$-sortable for some non-negative integer $$$X$$$ if it is possible to sort the permutation by performing the operation below some finite number of times:   Choose two indices $$$i$$$ and $$$j$$$ $$$(1 \le i \lt j \le n)$$$ such that $$$p_i \& p_j = X$$$.  Swap $$$p_i$$$ and $$$p_j$$$. Here $$$\&$$$ denotes the bitwise AND operation.Find the maximum value of $$$X$$$ such that $$$p$$$ is $$$X$$$-sortable. It can be shown that there always exists some value of $$$X$$$ such that $$$p$$$ is $$$X$$$-sortable.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^4)$$$  — the number of test cases. Description of test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^5)$$$  — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, ..., p_n$$$ ($$$0 \le p_i \le n-1$$$, all $$$p_i$$$ are distinct)  — the elements of $$$p$$$. It is guaranteed that $$$p$$$ is not sorted. It is guaranteed that the sum of $$$n$$$ over all cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output a single integer — the maximum value of $$$X$$$ such that $$$p$$$ is $$$X$$$-sortable.

void main() { runSolver(); }

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

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

      int[] swapee;
      foreach(i, a; A) {
        if (i != a) swapee ~= a;
      }
      int l = swapee.length.to!int;

      int ans;
      foreach(i; 0..30) {
        bool ok = true;
        foreach(ref s; swapee) {
          if (s % 2 == 0) ok = false;
          s /= 2;
        }
        if (ok) ans += 2^^i;
      }

      ans.writeln;
    }

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

  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"];

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

void main() { runSolver(); }

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

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

      int[] swapee;
      foreach(i, a; A) {
        if (i != a) swapee ~= a;
      }

      int ans;
      int swl = swapee.length.to!int;
      foreach(i; 0..swl - 1) foreach(j; i + 1..swl) {
        ans = max(ans, swapee[i] & swapee[j]);
      }

      ans.writeln;
    }

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

  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"];

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


Kuroni has $$$n$$$ daughters. As gifts for them, he bought $$$n$$$ necklaces and $$$n$$$ bracelets:  the $$$i$$$-th necklace has a brightness $$$a_i$$$, where all the $$$a_i$$$ are pairwise distinct (i.e. all $$$a_i$$$ are different),  the $$$i$$$-th bracelet has a brightness $$$b_i$$$, where all the $$$b_i$$$ are pairwise distinct (i.e. all $$$b_i$$$ are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the $$$i$$$-th daughter receives a necklace with brightness $$$x_i$$$ and a bracelet with brightness $$$y_i$$$, then the sums $$$x_i + y_i$$$ should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are $$$a = [1, 7, 5]$$$ and $$$b = [6, 1, 2]$$$, then we may distribute the gifts as follows:  Give the third necklace and the first bracelet to the first daughter, for a total brightness of $$$a_3 + b_1 = 11$$$. Give the first necklace and the third bracelet to the second daughter, for a total brightness of $$$a_1 + b_3 = 3$$$. Give the second necklace and the second bracelet to the third daughter, for a total brightness of $$$a_2 + b_2 = 8$$$. Here is an example of an invalid distribution:   Give the first necklace and the first bracelet to the first daughter, for a total brightness of $$$a_1 + b_1 = 7$$$. Give the second necklace and the second bracelet to the second daughter, for a total brightness of $$$a_2 + b_2 = 8$$$. Give the third necklace and the third bracelet to the third daughter, for a total brightness of $$$a_3 + b_3 = 7$$$. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$)  — the number of daughters, necklaces and bracelets. The second line of each test case contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$)  — the brightnesses of the necklaces. The third line of each test case contains $$$n$$$ distinct integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 1000$$$)  — the brightnesses of the bracelets.

For each test case, print a line containing $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$, representing that the $$$i$$$-th daughter receives a necklace with brightness $$$x_i$$$. In the next line print $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$, representing that the $$$i$$$-th daughter receives a bracelet with brightness $$$y_i$$$. The sums $$$x_1 + y_1, x_2 + y_2, \dots, x_n + y_n$$$ should all be distinct. The numbers $$$x_1, \dots, x_n$$$ should be equal to the numbers $$$a_1, \dots, a_n$$$ in some order, and the numbers $$$y_1, \dots, y_n$$$ should be equal to the numbers $$$b_1, \dots, b_n$$$ in some order.  It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.

NoteIn the first test case, it is enough to give the $$$i$$$-th necklace and the $$$i$$$-th bracelet to the $$$i$$$-th daughter. The corresponding sums are $$$1 + 8 = 9$$$, $$$8 + 4 = 12$$$, and $$$5 + 5 = 10$$$.The second test case is described in the statement.

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		auto b = readln.splitter.map !(to !(int)).array;
		sort (b);
		writefln !("%(%s %)") (a);
		writefln !("%(%s %)") (b);
	}
}

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

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

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    const n = r.next!uint;
    auto a = r.nextA!uint (n);
    auto b = r.nextA!uint (n);
    sort (a);
    sort (b);
    writefln ("%(%s %)", a);
    writefln ("%(%s %)", b);
  }
}

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 B = new int[N];
        foreach (i; 0 .. N) {
          B[i] = readInt();
        }

        A.sort;
        B.sort;
        foreach (i; 0 .. N) {
          if (i > 0) write(" ");
          write(A[i]);
        }
        writeln();
        foreach (i; 0 .. N) {
          if (i > 0) write(" ");
          write(B[i]);
        }
        writeln();
      }
    }
  } catch (EOFException e) {
  }
}

import std.stdio;
import std.algorithm;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		readf(" %d", &a);
		int[] m = new int[a];
		int[] n = new int[a];
		for (int j=0; j<a; j++)
		{
			readf(" %d", &m[j]);
		}
		for (int j=0; j<a; j++)
		{
			readf(" %d", &n[j]);
		}
		m.sort;
		n.sort;
		for (int j=0; j<a; j++)
		{
			writeln(m[j]);
		}
		for (int j=0; j<a; j++)
		{
			writeln(n[j]);
		}
	}
	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 = 998244353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new long[][](t*2);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto b = RDA;
		a.sort();
		b.sort();
		foreach (i; 0..n)
		{
			ans[ti*2] ~= a[i];
			ans[ti*2+1] ~= b[i];
		}
	}

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


You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$.You can do the following operation any number of times (possibly zero):   Choose any index $$$i$$$ and set $$$a_i$$$ to any integer (positive, negative or $$$0$$$). What is the minimum number of operations needed to turn $$$a$$$ into an arithmetic progression? The array $$$a$$$ is an arithmetic progression if $$$a_{i+1}-a_i=a_i-a_{i-1}$$$ for any $$$2 \leq i \leq n-1$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$).

Print a single integer: the minimum number of operations needed to turn $$$a$$$ into an arithmetic progression.

// Not my code! Taken from https://codeforces.com/contest/1654/submission/150267074
// Replaced malloc with a regular array allocation and marked 'main()' as @system
// Everything else is marked as @safe by default

@safe:
import core.stdc.stdlib;
import std.algorithm;
import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable int total  = 100_005;
immutable int limit  =     320;
immutable int limit2 = total / limit + 1;

int small (int [] a, int n)
{
    auto len = total * (limit + 2) * 2;
    auto m = new int[len];
    int res = 0;
    for (int d = -limit; d <= +limit; d++)
    {
	{
	    int cur = len / 2 + max (0, -d) * n;
	    foreach (ref x; a)
	    {
		m[cur + x] += 1;
		res = max (res, m[cur + x]);
		cur += d;
	    }
	}
	{
	    int cur = len / 2 + max (0, -d) * n;
	    foreach (ref x; a)
	    {
		m[cur + x] -= 1;
		cur += d;
	    }
	}
    }
    return res;
}

int large (int [] a, int n)
{
    int res = 0;
    for (int i = 0; i < n; i++)
    {
	int lo = max (0, i - limit2);
	int hi = min (n, i + limit2 + 1);
	int [int] s;
	for (int j = lo; j < hi; j++)
	{
//			if (j == i || (a[i] - a[j]) % (i - j) != 0)
	    if (j == i)
	    {
		continue;
	    }
	    auto d = (a[i] - a[j]) / (i - j);
	    if (d * (i - j) != (a[i] - a[j]))
	    {
		continue;
	    }
	    s[d] += 1;
	    res = max (res, s[d]);
	}
    }
    return res + 1;
}

void main () @system
{
    int n;
    while (readf !(" %s") (n) > 0)
    {
	readln;
	auto a = readln.splitter.map !(to !(int)).array;

	int x = small (a, n);
	int y = large (a, n);
	writeln (n - max (x, y));
    }
}

// Not my code! Taken from https://codeforces.com/contest/1654/submission/150267074
// Replaced malloc with a regular array allocation and marked 'main()' as @system

import core.stdc.stdlib;
import std.algorithm;
import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable int total  = 100_005;
immutable int limit  =     320;
immutable int limit2 = total / limit + 1;

int small (int [] a, int n)
{
    auto len = total * (limit + 2) * 2;
    auto m = new int[len];
    int res = 0;
    for (int d = -limit; d <= +limit; d++)
    {
	{
	    int cur = len / 2 + max (0, -d) * n;
	    foreach (ref x; a)
	    {
		m[cur + x] += 1;
		res = max (res, m[cur + x]);
		cur += d;
	    }
	}
	{
	    int cur = len / 2 + max (0, -d) * n;
	    foreach (ref x; a)
	    {
		m[cur + x] -= 1;
		cur += d;
	    }
	}
    }
    return res;
}

int large (int [] a, int n)
{
    int res = 0;
    for (int i = 0; i < n; i++)
    {
	int lo = max (0, i - limit2);
	int hi = min (n, i + limit2 + 1);
	int [int] s;
	for (int j = lo; j < hi; j++)
	{
//			if (j == i || (a[i] - a[j]) % (i - j) != 0)
	    if (j == i)
	    {
		continue;
	    }
	    auto d = (a[i] - a[j]) / (i - j);
	    if (d * (i - j) != (a[i] - a[j]))
	    {
		continue;
	    }
	    s[d] += 1;
	    res = max (res, s[d]);
	}
    }
    return res + 1;
}

void main () @system
{
    int n;
    while (readf !(" %s") (n) > 0)
    {
	readln;
	auto a = readln.splitter.map !(to !(int)).array;

	int x = small (a, n);
	int y = large (a, n);
	writeln (n - max (x, y));
    }
}

import core.stdc.stdlib;
import std.algorithm;
import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable int total  = 100_005;
immutable int limit  =     320;
immutable int limit2 = total / limit + 1;

int small (int [] a, int n)
{
	auto len = total * (limit + 2) * 2;
	auto m = cast (int *) (malloc (len * int.sizeof))[0..len];
	int res = 0;
	for (int d = -limit; d <= +limit; d++)
	{
		{
			int cur = len / 2 + max (0, -d) * n;
			foreach (ref x; a)
			{
				m[cur + x] += 1;
				res = max (res, m[cur + x]);
				cur += d;
			}
		}
		{
			int cur = len / 2 + max (0, -d) * n;
			foreach (ref x; a)
			{
				m[cur + x] -= 1;
				cur += d;
			}
		}
	}
	return res;
}

int large (int [] a, int n)
{
	int res = 0;
	for (int i = 0; i < n; i++)
	{
		int lo = max (0, i - limit2);
		int hi = min (n, i + limit2 + 1);
		int [int] s;
		for (int j = lo; j < hi; j++)
		{
//			if (j == i || (a[i] - a[j]) % (i - j) != 0)
			if (j == i)
			{
				continue;
			}
			auto d = (a[i] - a[j]) / (i - j);
			if (d * (i - j) != (a[i] - a[j]))
			{
				continue;
			}
			s[d] += 1;
			res = max (res, s[d]);
		}
	}
	return res + 1;
}

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;

		int x = small (a, n);
		int y = large (a, n);
		writeln (n - max (x, y));
	}
}


You are given a sequence $$$s$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$.You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one.More formally: if the resulting division of the sequence is $$$t_1, t_2, \dots, t_k$$$, where $$$k$$$ is the number of element in a division, then for each $$$i$$$ from $$$1$$$ to $$$k-1$$$ the condition $$$t_{i} < t_{i + 1}$$$ (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied.For example, if $$$s=654$$$ then you can divide it into parts $$$[6, 54]$$$ and it will be suitable division. But if you will divide it into parts $$$[65, 4]$$$ then it will be bad division because $$$65 > 4$$$. If $$$s=123$$$ then you can divide it into parts $$$[1, 23]$$$, $$$[1, 2, 3]$$$ but not into parts $$$[12, 3]$$$.Your task is to find any suitable division for each of the $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 300$$$) — the number of queries. The first line of the $$$i$$$-th query contains one integer number $$$n_i$$$ ($$$2 \le n_i \le 300$$$) — the number of digits in the $$$i$$$-th query. The second line of the $$$i$$$-th query contains one string $$$s_i$$$ of length $$$n_i$$$ consisting only of digits from $$$1$$$ to $$$9$$$.

If the sequence of digits in the $$$i$$$-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line "NO" for this query. Otherwise in the first line of the answer to this query print "YES", on the second line print $$$k_i$$$ — the number of parts in your division of the $$$i$$$-th query sequence and in the third line print $$$k_i$$$ strings $$$t_{i, 1}, t_{i, 2}, \dots, t_{i, k_i}$$$ — your division. Parts should be printed in order of the initial string digits. It means that if you write the parts one after another without changing their order then you'll get the string $$$s_i$$$. See examples for better understanding.

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

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

    if (N == 1) {
        writeln("NO");
        return;
    }

    if (N == 2) {
        if (S[0] >= S[1]) {
            writeln("NO");
            return;
        }
    }

    writeln("YES");
    writeln(2);
    writeln(S[0], " ", S[1..$]);
}

void main() {
    auto T = readln.chomp.to!int;
    while (T--) solve;
}


You are given a string $$$s$$$, consisting only of characters '0' or '1'. Let $$$|s|$$$ be the length of $$$s$$$.You are asked to choose some integer $$$k$$$ ($$$k > 0$$$) and find a sequence $$$a$$$ of length $$$k$$$ such that:   $$$1 \le a_1 < a_2 < \dots < a_k \le |s|$$$;  $$$a_{i-1} + 1 < a_i$$$ for all $$$i$$$ from $$$2$$$ to $$$k$$$. The characters at positions $$$a_1, a_2, \dots, a_k$$$ are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence $$$a$$$ should not be adjacent.Let the resulting string be $$$s'$$$. $$$s'$$$ is called sorted if for all $$$i$$$ from $$$2$$$ to $$$|s'|$$$ $$$s'_{i-1} \le s'_i$$$.Does there exist such a sequence $$$a$$$ that the resulting string $$$s'$$$ is sorted?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$s$$$ ($$$2 \le |s| \le 100$$$). Each character is either '0' or '1'.

For each testcase print "YES" if there exists a sequence $$$a$$$ such that removing the characters at positions $$$a_1, a_2, \dots, a_k$$$ and concatenating the parts without changing the order produces a sorted string. Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first testcase you can choose a sequence $$$a=[1,3,6,9]$$$. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.In the second and the third testcases the sequences are already sorted.In the fourth testcase you can choose a sequence $$$a=[3]$$$. $$$s'=$$$ "11", which is sorted.In the fifth testcase there is no way to choose a sequence $$$a$$$ such that $$$s'$$$ is sorted.

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

string FMT_F = "%.10f";

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

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

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

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

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

		int[] a;
		foreach (i; 1..s.length)
		{
			if (s[i] == s[i-1])
			{
				a ~= s[i] - '0';
			}
		}
		auto b = a.dup;
		b.sort;
		ans[ti] = true;
		foreach (i; 0..a.length)
		{
			if (a[i] != b[i])
			{
				ans[ti] = false;
				break;
			}
		}
	}

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


Find out if it is possible to partition the first $$$n$$$ positive integers into two non-empty disjoint sets $$$S_1$$$ and $$$S_2$$$ such that:$$$\mathrm{gcd}(\mathrm{sum}(S_1), \mathrm{sum}(S_2)) > 1$$$ Here $$$\mathrm{sum}(S)$$$ denotes the sum of all elements present in set $$$S$$$ and $$$\mathrm{gcd}$$$ means thegreatest common divisor.Every integer number from $$$1$$$ to $$$n$$$ should be present in exactly one of $$$S_1$$$ or $$$S_2$$$.

The only line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 45\,000$$$)

If such partition doesn't exist, print "No" (quotes for clarity). Otherwise, print "Yes" (quotes for clarity), followed by two lines, describing $$$S_1$$$ and $$$S_2$$$ respectively. Each set description starts with the set size, followed by the elements of the set in any order. Each set must be non-empty. If there are multiple possible partitions — print any of them.

NoteIn the first example, there is no way to partition a single number into two non-empty sets, hence the answer is "No".In the second example, the sums of the sets are $$$2$$$ and $$$4$$$ respectively. The $$$\mathrm{gcd}(2, 4) = 2 > 1$$$, hence that is one of the possible answers.

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!long;

    if (N <= 2) {
        writeln("No");
        return;
    }

    long S = N * (N - 1) / 2;
    foreach_reverse (i; 2..N+1) {
        if (gcd(S-i, i) > 1) {
            writeln("Yes");
            writeln(1, " ", i);
            write(N-1);
            foreach (j; 1..N+1) if (j != i) write(" ", j);
            writeln;
            return;
        }
    }

    writeln("No");
}

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

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

    if (n < 3) {
        writeln("No");
        return;
    }

    int[][2] s;
    for (auto i = 1, j = n, nxt = 0; i <= j; ++i, --j, nxt = (nxt+1) % 2) {
        s[nxt] ~= i;
        if (i != j) s[nxt] ~= j;
    }

    writeln("Yes");
    foreach (rw; s) {
        writef("%s ", rw.length);
        writefln("%(%s %)", rw);
    }
}

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

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

    if (n == 1 || n % 2 == 0) {
        writeln("No");
        return;
    }

    int[] s;
    auto isPr = new bool[654321];
    isPr[] = true;
    foreach (i; 2 .. isPr.length) {
        if (!isPr[i]) continue;

        if (i != 2) s ~= i.to!int;
        foreach (ref e; isPr[i+i .. $].stride(i)) e = false;

        if (s.length == n-1) break;
    }

    writeln("Yes");
    writeln("1 2");
    writef("%s ", n-1);
    s.writefln!("%(%s %)");
}


A queen is the strongest chess piece. In modern chess the queen can move any number of squares in any horizontal, vertical or diagonal direction (considering that there're no other pieces on its way). The queen combines the options given to the rook and the bishop.There are m queens on a square n × n chessboard. You know each queen's positions, the i-th queen is positioned in the square (ri, ci), where ri is the board row number (numbered from the top to the bottom from 1 to n), and ci is the board's column number (numbered from the left to the right from 1 to n). No two queens share the same position.For each queen one can count w — the number of other queens that the given queen threatens (attacks). For a fixed attack direction only the first queen in this direction is under attack if there are many queens are on the ray of the attack. Obviously, for any queen w is between 0 and 8, inclusive.Print the sequence t0, t1, ..., t8, where ti is the number of queens that threaten exactly i other queens, i.e. the number of queens that their w equals i.

The first line of the input contains a pair of integers n, m (1 ≤ n, m ≤ 105), where n is the size of the board and m is the number of queens on the board. Then m following lines contain positions of the queens, one per line. Each line contains a pair of integers ri, ci (1 ≤ ri, ci ≤ n) — the queen's position. No two queens stand on the same square.

Print the required sequence t0, t1, ..., t8, separating the numbers with spaces.

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

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

    auto rows = new int[][] (n+1);
    auto cols = new int[][] (n+1);
    auto diagtl = new int[][] (2*n-1);
    auto diagbl = new int[][] (2*n-1);

    auto qs = new Tuple!(int, int)[] (m);
    foreach (i; 0 .. m) {
        readf("%s %s", &qs[i][0], &qs[i][1]);
        readln;

        rows[qs[i][0]] ~= i;
        cols[qs[i][1]] ~= i;
        diagtl[qs[i][0]-qs[i][1]+n-1] ~= i;
        diagbl[qs[i][0]+qs[i][1]-2] ~= i;
    }

    auto attacks = new int[] (m);

    auto arrs = [rows, cols, diagtl, diagbl];

    foreach (i; 0 .. 4) {
        foreach (rw; arrs[i]) {
            if (rw.length <= 1) { continue; }

            rw.schwartzSort!(id => qs[id]);

            attacks[rw.front] += 1;
            attacks[rw.back] += 1;
            foreach (e; rw.dropOne.dropBackOne) { attacks[e] += 2; }
        }
    }

    auto ans = new int[] (9);
    foreach (e; attacks) { ans[e] += 1; }

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

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

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

    auto rows = new int[][] (n+1);
    auto cols = new int[][] (n+1);
    auto diagtl = new int[][] (2*n-1);
    auto diagbl = new int[][] (2*n-1);

    auto qs = new Tuple!(int, int)[] (m);
    foreach (i; 0 .. m) {
        readf("%s %s", &qs[i][0], &qs[i][1]);
        readln;

        rows[qs[i][0]] ~= i;
        cols[qs[i][1]] ~= i;
        diagtl[qs[i][0]-qs[i][1]+n-1] ~= i;
        diagbl[qs[i][0]+qs[i][1]-2] ~= i;
    }

    auto attacks = new int[] (m);

    auto arrs = [rows, cols, diagtl, diagbl];
    auto sortOrd = [(int id) => qs[id][1], (int id) => qs[id][0],
                   (int id) => qs[id][0], (int id) => qs[id][0]];

    foreach (i; 0 .. 4) {
        foreach (rw; arrs[i]) {
            if (rw.length <= 1) { continue; }

            rw.schwartzSort!(id => sortOrd[i](id));

            attacks[rw.front] += 1;
            attacks[rw.back] += 1;
            foreach (e; rw.dropOne.dropBackOne) { attacks[e] += 2; }
        }
    }

    auto ans = new int[] (9);
    foreach (e; attacks) { ans[e] += 1; }

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


Let's call an array consisting of n integer numbers a1, a2, ..., an, beautiful if it has the following property:  consider all pairs of numbers x, y (x ≠ y), such that number x occurs in the array a and number y occurs in the array a;  for each pair x, y must exist some position j (1 ≤ j < n), such that at least one of the two conditions are met, either aj = x, aj + 1 = y, or aj = y, aj + 1 = x. Sereja wants to build a beautiful array a, consisting of n integers. But not everything is so easy, Sereja's friend Dima has m coupons, each contains two integers qi, wi. Coupon i costs wi and allows you to use as many numbers qi as you want when constructing the array a. Values qi are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array a of n elements. After that he takes wi rubles from Sereja for each qi, which occurs in the array a. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay.Help Sereja, find the maximum amount of money he can pay to Dima.

The first line contains two integers n and m (1 ≤ n ≤ 2·106, 1 ≤ m ≤ 105). Next m lines contain pairs of integers. The i-th line contains numbers qi, wi (1 ≤ qi, wi ≤ 105). It is guaranteed that all qi are distinct.

In a single line print maximum amount of money (in rubles) Sereja can pay. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Sereja can pay 5 rubles, for example, if Dima constructs the following array: [1, 2, 1, 2, 2]. There are another optimal arrays for this test.In the third sample Sereja can pay 100 rubles, if Dima constructs the following array: [2].

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

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto q = new int [m];
		auto w = new int [m];
		foreach (i; 0..m)
		{
			readf (" %s %s", &q[i], &w[i]);
		}

		w.sort !("a > b", SwapStrategy.stable);

		int res = 0;
		foreach (k; 1..m + 1)
		{
			long len;
			if (k % 2 == 1)
			{
				len = cast (long) k * (k - 1) / 2 + 1;
			}
			else
			{
				len = cast (long) k * k / 2;
			}
			if (len <= n)
			{
				res = max (res, k);
			}
		}

		long ans = 0;
		foreach (i; 0..res)
		{
			ans += w[i];
		}
		writeln (ans);
	}
}


You have a string $$$s$$$ consisting of lowercase Latin alphabet letters. You can color some letters in colors from $$$1$$$ to $$$k$$$. It is not necessary to paint all the letters. But for each color, there must be a letter painted in that color.Then you can swap any two symbols painted in the same color as many times as you want. After that, $$$k$$$ strings will be created, $$$i$$$-th of them will contain all the characters colored in the color $$$i$$$, written in the order of their sequence in the string $$$s$$$.Your task is to color the characters of the string so that all the resulting $$$k$$$ strings are palindromes, and the length of the shortest of these $$$k$$$ strings is as large as possible.Read the note for the first test case of the example if you need a clarification.Recall that a string is a palindrome if it reads the same way both from left to right and from right to left. For example, the strings abacaba, cccc, z and dxd are palindromes, but the strings abab and aaabaa — are not.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input data sets in the test.  The descriptions of the input data sets follow. The first line of the description of each input data set contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the length of the string and the number of colors in which its letters can be painted. The second line of the description of each input data set contains a string $$$s$$$ of length $$$n$$$ consisting of lowercase letters of the Latin alphabet. It is guaranteed that the sum of n over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each set of input data, output a single integer  — the maximum length of the shortest palindrome string that can be obtained.

10

8 2

bxyaxzay

6 3

aaaaaa

6 1

abcdef

6 6

abcdef

3 2

dxd

11 2

abcabcabcac

6 6

sipkic

7 2

eatoohd

3 1

llw

6 2

bfvfbv

Note In the first test case, $$$s$$$="bxyaxzay", $$$k=2$$$. We use indices in the string from $$$1$$$ to $$$8$$$. The following coloring will work: $$$\mathtt{\mathbf{\color{red}{b}\color{blue}{xy}\color{red}{a}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}$$$ (the letter z remained uncolored). After painting:  swap two red characters (with the indices $$$1$$$ and $$$4$$$), we get $$$\mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}$$$;  swap two blue characters (with the indices $$$5$$$ and $$$8$$$), we get $$$\mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{y}z\color{red}{a}\color{blue}{x}}}$$$. Now, for each of the two colors we write out the corresponding characters from left to right, we get two strings $$$\mathtt{\mathbf{\color{red}{aba}}}$$$ and $$$\mathtt{\mathbf{\color{blue}{xyyx}}}$$$. Both of them are palindromes, the length of the shortest is $$$3$$$. It can be shown that the greatest length of the shortest palindrome cannot be achieved. In the second set of input data, the following coloring is suitable: $$$[1, 1, 2, 2, 3, 3]$$$. There is no need to swap characters. Both received strings are equal to aa, they are palindromes and their length is $$$2$$$. In the third set of input data, you can color any character and take it into a string. In the fourth set of input data, you can color the $$$i$$$th character in the color $$$i$$$. In the fifth set of input data can be colored in each of the colors of one character. In the sixth set of input data, the following coloring is suitable: $$$[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0]$$$. Rearrange the characters so as to get the palindromes abcba and acbca.

void main() { runSolver(); }

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

  auto solve() {
    void subSolve(int SN, int K, string S) {
      auto chars = new int[](26);
      foreach(c; S) chars[c - 'a']++;

      int baseOdds, baseEvens;
      foreach(cs; chars) {
        if (cs == 0) continue;

        baseOdds += cs%2;
        baseEvens += (cs - cs%2) / 2;
      }
      // [evens, odds].deb;

      int ans;
      foreach(centered; 0..K + 1) {
        auto odds = baseOdds;
        auto evens = baseEvens;

        const m = min(odds, centered);
        odds -= m;
        evens -= (centered - m + 1) / 2;

        // foreach(_; 0..centered) {
        //   if (odds > 0) {
        //     odds--;
        //   } else {
        //     evens -= 2;
        //     odds++;
        //   }
        // }

        int geta = centered == K ? 1 : 0;
        ans = max(ans, geta + (evens / K) * 2);
      }

      ans.writeln;
    }

    foreach(_; 0..QN) {
      subSolve(scan!int, scan!int, scan);
    }
  }

  outputForAtCoder(&solve);
}

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

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

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

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

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

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

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

  return ok;
}

import std;

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

    foreach (test_index; 0 .. tests) {
        immutable n = (){ uint n; readf!"%s "(n); return n; }();
        immutable k = (){ uint k; readf!"%s\n"(k); return k; }();

        const frec = (){
            static assert(true);
            uint[dchar] ret;

            foreach (c; readln.chomp) {
                ++ ret[c];
            }
            return ret;
        }();

        uint total_pairs = 0;
        uint odds = 0;

        foreach (f; frec) {
            total_pairs += f / 2;
            odds += (f % 2 == 1);
        }

        immutable can_do_donations =
            (total_pairs % k + odds >= k - total_pairs % k);
        writeln((total_pairs / k) * 2 + can_do_donations);
    }
}
// ""

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, k;
    readf!" %d %d "(n, k);
    auto s = readln.strip;
    int[char] freq;
    foreach (ch ; s) {
      freq[ch]++;
    }
    int pairs;
    int singles;
    foreach (_, v ; freq) {
      pairs += v / 2;
      singles += v % 2;
    }
    int ans = pairs / k * 2;
    if (pairs % k == 0) {
      ans += (singles >= k);
    } else {
      ans += (singles + (pairs % k) * 2 >= k);
    }
    writeln(ans);
  }
}

import std;

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

    foreach (test_index; 0 .. tests) {
        immutable n = (){ uint n; readf!"%s "(n); return n; }();
        immutable k = (){ uint k; readf!"%s\n"(k); return k; }();

        const frec = (){
            static assert(true);
            uint[dchar] ret;

            foreach (c; readln.chomp) {
                ++ ret[c];
            }
            return ret;
        }();

        uint total_pairs = 0;
        bool have_odd_one = false;

        foreach (f; frec) {
            total_pairs += f / 2;
            have_odd_one = have_odd_one || f % 2 == 1;
        }

        immutable can_donate = have_odd_one || total_pairs % k != 0;
        writeln((total_pairs / k) * 2 + can_donate);
    }
}
// ""


Consider a table of size $$$n \times m$$$, initially fully white. Rows are numbered $$$1$$$ through $$$n$$$ from top to bottom, columns $$$1$$$ through $$$m$$$ from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 115$$$) — the number of rows and the number of columns in the table. The $$$i$$$-th of the next $$$n$$$ lines contains a string of $$$m$$$ characters $$$s_{i1} s_{i2} \ldots s_{im}$$$ ($$$s_{ij}$$$ is 'W' for white cells and 'B' for black cells), describing the $$$i$$$-th row of the table.

Output two integers $$$r$$$ and $$$c$$$ ($$$1 \le r \le n$$$, $$$1 \le c \le m$$$) separated by a space — the row and column numbers of the center of the black square.

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

immutable int MD = 10 ^^ 9 + 7;

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

    auto mtx = new dchar[][] (n, m);
    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            readf("%s", &mtx[i][j]);
        }
        readln;
    }

    debug { mtx.writeln; }

    int le = m, r = 0, d = 0, u = n;
    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            if (mtx[i][j] != 'B') continue;

            le = min(le, j);
            r = max(r, j);
            d = max(d, i);
            u = min(u, i);
        }
    }

    auto x = (d + u) / 2 + 1;
    auto y = (le + r) / 2 + 1;

    writeln(x, ' ', y);
}


You are given an integer $$$x$$$ and an array of integers $$$a_1, a_2, \ldots, a_n$$$. You have to determine if the number $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$.Here $$$k!$$$ is a factorial of $$$k$$$ — the product of all positive integers less than or equal to $$$k$$$. For example, $$$3! = 1 \cdot 2 \cdot 3 = 6$$$, and $$$5! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120$$$.

The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 500\,000$$$, $$$1 \le x \le 500\,000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le x$$$) — elements of given array.

In the only line print "Yes" (without quotes) if $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$, and "No" (without quotes) otherwise.

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

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

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

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

int N, X;
int[] A;

bool solve() {
  auto fs = new int[X + 1];
  foreach (i; 0 .. N) {
    ++fs[A[i]];
  }
  foreach (a; 1 .. X) {
    const q = fs[a] / (a + 1);
    const r = fs[a] % (a + 1);
    if (r != 0) {
      return false;
    }
    fs[a + 1] += q;
  }
  return true;
}

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

      const ans = solve;
      writeln(ans ? "Yes" : "No");
    }
  } 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, x;
	while (readf !(" %s %s") (n, x) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto d = new int [x + 1];
		foreach (c; a)
		{
			c = min (c, x);
			d[c] += 1;
			for ( ; c < x && d[c] == c + 1; c++)
			{
				d[c] = 0;
				d[c + 1] += 1;
			}
		}
		writeln (any (d[0..x]) ? "NO" : "YES");
	}
}

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()
{
  int n, x;
  readf!" %d %d "(n, x);
  auto a = readln.splitter.map!(to!int).filter!(ai => ai < x).array;

  auto h = redBlackTree!("a<b", true, int)();
  foreach (ai ; a)
    h.insert(ai);

  bool good = true;
  while (!h.empty) {
    int cnt = 1;
    int tmp = h.front;
    h.removeFront;
    while (!h.empty && h.front == tmp) {
      cnt++;
      h.removeFront;
    }
    if (cnt % (tmp + 1) != 0) {
      good = false;
      break;
    } else {
      if (tmp + 1 < x) {
        foreach (i ; 0 .. cnt / (tmp + 1))
          h.insert(tmp + 1);
      }
    }
  }

  writeln(good ? "Yes" : "No");
}


Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals n squares (n is an odd number) and each unit square contains some small letter of the English alphabet.Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:  on both diagonals of the square paper all letters are the same;  all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. Help Valera, write the program that completes the described task for him.

The first line contains integer n (3 ≤ n < 300; n is odd). Each of the next n lines contains n small English letters — the description of Valera's paper.

Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes.

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

void main() {
    int N; readf("%d\n", &N);
    auto F = new string[N];
    foreach (i; 0 .. N) {
        F[i] = readln.chomp;
    }
    char x = F[N / 2 + 1][N / 2 + 1];
    char y = F[0][1];
    bool f() {
        if (x == y) return false;
        foreach (i; 0 .. N) {
            foreach (j; 0 .. N) {
                if (i == j || i + j == N - 1) {
                    if (x != F[i][j]) {
                        return false;
                    }
                } else {
                    if (y != F[i][j]) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
    writeln(f ? "YES" : "NO");
}

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int n_Cases = 1;
        // n_Cases = cin.readInt;

	for (int case_i = 1; case_i <= n_Cases; case_i++) {
                int n = cin.readInt;
                char[][] mat = new char[][](n, n);

                for (int i = 0; i < n; i++) {
                        mat[i] = cin.readString.dup;
                }

                char key = mat[0][0];
                char key2 = mat[0][1];

                bool con1 = true;
                bool con2 = true;

                for (int i = 0; i < n; i++) {
                        for (int j = 0; j < n; j++) {
                                if (i == j || i + j == n - 1) {
                                        if (mat[i][j] != key) con1 = false;
                                } else {
                                        if (mat[i][j] == key || mat[i][j] != key2) con2 = false;
                                }
                        }
                }

                writeln((con1 && con2) ? "YES" : "NO");
	}
}


Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.

For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.

NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.

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

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

    while (t--) {
        int n, s, k;
        readf("%s %s %s", &n, &s, &k);
        readln;

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

        int lo = s;
        while (lo >= 1 && lo in rbt) { --lo; }
        int hi = s;
        while (hi <= n && hi in rbt) { ++ hi; }

        if (lo == 0) {
            writeln(hi - s);
        } else if (hi == n+1) {
            writeln(s - lo);
        } else {
            writeln(min(hi - s, s - lo));
        }
    }
}

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

DList!string _words;

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

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

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

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

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

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

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

    }
}

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

void main()
{
  int t;
  read(t);
  foreach(tc; 0 .. t)
    {
      long n, s, k;
      read(n, s, k);
      auto closed = redBlackTree!long();
      foreach(i; 0 .. k)
        {
          long ai;
          read(ai);
          closed.insert(ai);
        }
      long mindistance = long.max;
      foreach(i; s .. n + 1)
        {
          if (i !in closed)
            {
              mindistance = min(mindistance, cast(long)i - s);
              break;
            }
        }
      foreach_reverse(i; 1 .. s)
        {
          if (i !in closed)
            {
              mindistance = min(mindistance, s - cast(long) i);
              break;
            }
        }
      writeln(mindistance);
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s = RD!int;
		auto k = RD!int;
		auto a = RDA!int;
		a.sort();
		int pos;
		foreach (i; 0..k)
		{
			pos = i;
			if (a[i] >= s) break;
		}
		if (a[pos] != s) continue;

		int l = a[0] != 1 ? s-(a[0]-1) : int.max, r = a[$-1] != n ? a[$-1]+1-s : int.max;
		{
			int last = s;
			foreach_reverse (i; 0..pos)
			{
				if (a[i] != last - 1)
				{
					l = s - (last - 1);
					break;
				}
				last = a[i];
			}
		}
		{
			int last = s;
			foreach (i; pos+1..k)
			{
				if (a[i] != last + 1)
				{
					r = (last + 1) - s;
					break;
				}
				last = a[i];
			}
		}
		ans[ti] = min(l, r);
	}

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


You are given two arrays of integers $$$a_1,a_2,\dots,a_n$$$ and $$$b_1,b_2,\dots,b_m$$$. Alice and Bob are going to play a game. Alice moves first and they take turns making a move.They play on a grid of size $$$n \times m$$$ (a grid with $$$n$$$ rows and $$$m$$$ columns). Initially, there is a rook positioned on the first row and first column of the grid.During her/his move, a player can do one of the following two operations:  Move the rook to a different cell on the same row or the same column of the current cell. A player cannot move the rook to a cell that has been visited $$$1000$$$ times before (i.e., the rook can stay in a certain cell at most $$$1000$$$ times during the entire game). Note that the starting cell is considered to be visited once at the beginning of the game. End the game immediately with a score of $$$a_r+b_c$$$, where $$$(r, c)$$$ is the current cell (i.e., the rook is on the $$$r$$$-th row and $$$c$$$-th column). Bob wants to maximize the score while Alice wants to minimize it. If they both play this game optimally, what is the final score of the game?

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n,m \leq 2 \cdot 10^5$$$) — the length of the arrays $$$a$$$ and $$$b$$$ (which coincide with the number of rows and columns of the grid). The second line contains the $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 5 \cdot 10^8$$$). The third line contains the $$$m$$$ integers $$$b_1, b_2,\dots, b_n$$$ ($$$1 \leq b_i \leq 5 \cdot 10^8$$$).

Print a single line containing the final score of the game.

NoteIn the first test case, Alice moves the rook to $$$(2, 1)$$$ and Bob moves the rook to $$$(1, 1)$$$. This process will repeat for $$$999$$$ times until finally, after Alice moves the rook, Bob cannot move it back to $$$(1, 1)$$$ because it has been visited $$$1000$$$ times before. So the final score of the game is $$$a_2+b_1=4$$$.In the second test case, the final score of the game is $$$a_3+b_5$$$.

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

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

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

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

int M, N;
int[] A, B;
int A0, B0;
int X0, Y0;

bool alice(int tar) {
  auto fs = new int[M + 1];
  auto gs = new int[N + 1];
  for (int x = 0, y = N; !(x == M && y == 0); ) {
    if (y == 0 || (x < M && A[x] + B[y - 1] <= tar)) {
      fs[x++] = y;
    } else {
      gs[--y] = x;
    }
  }
  auto fsSum = new long[M + 1];
  foreach (x; 0 .. M) {
    fsSum[x + 1] = fsSum[x] + fs[x];
  }

  debug {
    writeln("tar = ", tar);
    foreach (x; 0 .. M) {
      write("  ");
      foreach (y; 0 .. N) {
        write((x == X0 && y == Y0) ? '@' : (A[x] + B[y] <= tar) ? '1' : '0');
      }
      writeln;
    }
    writeln("  fs = ", fs);
    writeln("  gs = ", gs);
  }

  alias Entry = Tuple!(long, "ind", bool, "without");
  Entry mx = Entry(-1, false);

  // 1 in [0, x) [0, y) and 0 in [x, M) [y, N)
  Entry cut(int x, int y) {
    assert(0 <= x); assert(x <= M);
    assert(0 <= y); assert(y <= N);
    Entry ret;
    if (y < fs[x]) {
      ret.ind += 1L * x * y;
      ret.ind += 1L * (M - x) * (N - y);
      ret.ind -= ((fsSum[gs[y]] - fsSum[x]) - 1L * (gs[y] - x) * y);
    } else {
      ret.ind += 1L * gs[y] * y;
      ret.ind += (fsSum[x] - fsSum[gs[y]]);
      ret.ind += 1L * (M - x) * (N - y);
    }
    ret.without = !(x <= X0 && y <= Y0);
    debug {
      writefln("  cut %s %s = %s", x, y, ret);
    }
    chmax(mx, ret);
    return ret;
  }

  {
    int y;
    foreach (x; 0 .. M + 1) {
      Entry now = cut(x, y);
      for (; y < N; ) {
        const res = cut(x, y + 1);
        if (now <= res) {
          now = res;
          ++y;
        } else {
          break;
        }
      }
    }
  }

  // every matching has (X0, Y0) <=> there exists max ind set without (X0, Y0)
  return mx.without;
}

void main() {
  try {
    for (; ; ) {
      M = readInt;
      N = readInt;
      A = new int[M];
      foreach (x; 0 .. M) A[x] = readInt;
      B = new int[N];
      foreach (y; 0 .. N) B[y] = readInt;

      A0 = A[0];
      B0 = B[0];
      A.sort;
      B.sort;
      X0 = A.lowerBound(A0);
      Y0 = B.lowerBound(B0);
      debug {
        writefln("A = %s, X0 = %s", A, X0);
        writefln("B = %s, Y0 = %s", B, Y0);
      }

      int lo = A[0] + B[0] - 1, hi = A0 + B0;
      for (; lo + 1 < hi; ) {
        const mid = (lo + hi) / 2;
        (alice(mid) ? hi : lo) = mid;
      }
      writeln(hi);
    }
  } 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 M = readInt;
      const N = readInt;
      auto A = new int[M];
      foreach (x; 0 .. M) A[x] = readInt;
      auto B = new int[N];
      foreach (y; 0 .. N) B[y] = readInt;

      const A0 = A[0];
      const B0 = B[0];
      A.sort;
      B.sort;
      const X = A.lowerBound(A0);
      const Y = B.lowerBound(B0);
      debug {
        writefln("A = %s, X = %s", A, X);
        writefln("B = %s, Y = %s", B, Y);
      }

      bool alice(int tar) {
        long fX, fY;
        foreach (y; 0 .. N) if (A[X] + B[y] <= tar) ++fX;
        foreach (x; 0 .. M) if (A[x] + B[Y] <= tar) ++fY;

        long mx0, mx1;
        void check(long x, long y) {
          long a = x, b = y;
          long c = M - x, d = N - y;
          long score0 = a * b + c * d;
          chmax(mx0, score0);
          long da, db, dc, dd;
          (X < x) ? ++da : ++dc;
          (Y < y) ? ++db : ++dd;
          long score1 = (a - da) * (b - db) + (c - dc) * (d - dd);
          score1 += max(min(fX, b), min(N - fX, d) - dd);
          score1 += max(min(fY, a), min(M - fY, c) - dc);
          chmax(mx1, score1);
          debug {
            if (tar == 308925209) {
              if (mx1 == score1) {
                writeln("    ", x, " ", y, ": ", [a, b, c, d], " ", [min(fY, b), min(N - fY, d) - dd, min(fX, a), min(M - fX, c) - dc], " ", score1);
              }
            }
          }
        }

        long all1;
        for (int x = 0, y = N; ; ) {
          check(x, y);
          if (x == M && y == 0) {
            break;
          }
          if (y == 0) {
            all1 += y;
            ++x;
          } else if (x == M) {
            --y;
          } else {
            if (A[x] + B[y - 1] <= tar) {
              all1 += y;
              ++x;
            } else {
              --y;
            }
          }
        }
        chmax(mx0, all1);
        chmax(mx0, 1L * M * N - all1);
        chmax(mx1, all1);
        chmax(mx1, 1L * M * N - 1 - all1);

        debug {
          if (tar == 308925209) {
            writeln("tar = ", tar);
            foreach (x; 0 .. M) {
              write("  ");
              foreach (y; 0 .. N) {
                write((x == X && y == Y) ? '@' : (A[x] + B[y] <= tar) ? '1' : '0');
              }
              writeln;
            }
            writeln("  fX = ", fX);
            writeln("  fY = ", fY);
            writeln("  mx0 = ", mx0);
            writeln("  mx1 = ", mx1);
          }
        }
        mx0 = 1L * M * N - mx0;
        mx1 = 1L * M * N - 1 - mx1;
        return (mx0 != mx1);
      }

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