void main() { runSolver(); }

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

  auto solve() {
    void subSolve(int n, int[] arr) {
      foreach(ref a; arr) {
        while(a > n) a /= 2;
      }

      auto counts = new int[](n + 1);
      foreach(a; arr) {
        while(a > 0) {
          counts[a]++;
          a /= 2;
        }
      }

      auto used = new bool[](n + 1);
      foreach(a; arr) {
        int minValue = 0;
        int minCounts = int.max;
        while(a > 0) {
          if (!used[a] && minCounts.chmin(counts[a])) minValue = a;
          a /= 2;
        }

        if (minValue > 0) used[minValue] = true;
      }

      bool ans = used[1..$].count(false) == 0;
      writeln(ans ? "YES" : "NO");
    }

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

  outputForAtCoder(&solve);
}

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

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

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

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

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

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

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

  return ok;
}

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

bool can_convert(int from, int to)
{
  while (from > to) {
    from >>= 1;
  }
  return from == to;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    DList!int l;
    foreach (x ; a)
      l.insertBack(x);

    bool good = true;

    foreach_reverse (target ; 1 .. n + 1) {
      bool converted = false;
      foreach (i ; 0 .. n) {
        auto x = l.front;
        l.removeFront;
        if (can_convert(x, target)) {
          converted = true;
          break;
        }
        l.insertBack(x);
      }
      if (!converted) {
        good = false;
        break;
      }
    }
    writeln(good ? "YES" : "NO");
  }
}

import std;

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

    BigLoop: foreach (test_index; 0 .. tests) {
        immutable n = readln().chomp.to!uint;

         size_t[][uint] aa;
         foreach (i, val; readln.chomp.split(' ').to!(uint[])) {
             while (val) {
                 aa[val] ~= i;
                 val /= 2;
             }
         }

         bool[size_t] used;

         foreach (val; iota(n, 0, -1)) {
             if (val !in aa) {
                 writeln("NO");
                 continue BigLoop;
             }

             auto r = aa[val].filter!(x => x !in used);

             if (r.empty) {
                 writeln("NO");
                 continue BigLoop;
             }
             used[r.front] = true;
        }
         writeln("YES");
    }
}
// ""


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;

immutable int NA = -1;

int [] [] g;
bool [] b;
int [] p;

bool bipart (int v)
{
	if (b[v])
	{
		return false;
	}
	b[v] = true;

	foreach (c; g[v])
	{
		if (c == NA)
		{
			continue;
		}
		if (p[c] == NA || bipart (p[c]))
		{
			p[c] = v;
			return true;
		}
	}

	return false;
}

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto r = new bool [n + 1];
		auto c = new bool [n + 1];
		r[] = false;
		c[] = false;
		r[2..n] = true;
		c[2..n] = true;
		foreach (i; 0..m)
		{
			int cr, cc;
			readf (" %s %s", &cr, &cc);
			r[cr] = false;
			c[cc] = false;
		}
		int add = 0;
		if (n & 1)
		{
			if (r[n / 2 + 1] || c[n / 2 + 1])
			{
				add++;
				r[n / 2 + 1] = false;
				c[n / 2 + 1] = false;
			}
		}

		auto rv = new int [] [] (n + 1, 2);
		auto cv = new int [] [] (n + 1, 2);
		g = new int [] [n * 4];
		int k = 0;
		foreach (i; 2..n)
		{
			if (r[i])
			{
				rv[i] = [k, k + 1];
				k += 2;
			}
			else
			{
				rv[i] = [NA, NA];
			}

			if (c[i])
			{
				cv[i] = [k, k + 1];
				k += 2;
			}
			else
			{
				cv[i] = [NA, NA];
			}
		}
		debug {writeln ("k = ", k);}

		int res = 0;
		int t = 0;
		foreach (i; 2..n)
		{
			if (r[i])
			{
				g[t] = [t ^ 1, cv[i][0], cv[n - i + 1][1]];
				t++;
				g[t] = [t ^ 1, cv[i][1], cv[n - i + 1][0]];
				t++;
			}
			if (c[i])
			{
				g[t] = [t ^ 1, rv[i][0], rv[n - i + 1][1]];
				t++;
				g[t] = [t ^ 1, rv[i][1], rv[n - i + 1][0]];
				t++;
			}
		}

		b = new bool [k];
		p = new int [k];
		p[] = NA;
		foreach (i; 0..k)
		{
			b[] = false;
			if (p[i] == NA && bipart (i))
			{
				res++;
			}
		}

		writeln (k - res + add);
	}
}

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

void play(){
    int n, m;
    n = rd!int;
    m = rd!int;
    auto rows = new ll[](n);
    auto cols = new ll[](n);
    rows[n-1] += 2;
    cols[n-1] += 2;
    rows[0] += 2;
    cols[0] += 2;
    foreach(i; 0..m){
        int xi = rd!int - 1;
        int yi = rd!int - 1;
        ++rows[xi];
        ++cols[yi];
    }
    ll cnt = 0, midd = 0;
    foreach(i; 0..n){
        if(!rows[i]) ++cnt;
        if(!cols[i]) ++cnt;

        if(i == n/2){
            if(!rows[i]) ++midd;
            if(!cols[i]) ++midd;
        }
    }
    if(n % 2){
        cnt -= midd;
        if(midd) ++cnt;
    }
    writeln(cnt);
}

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

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

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

void main ()
{
	long n;
	while (readf (" %s", &n) > 0)
	{
		while (n % 3 == 0)
		{
			n /= 3;
		}
		long res = n / 3 + 1;
		writeln (res);
	}
}


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

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

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto X = new long[N];
      auto Y = new long[N];
      auto S = new int[N];
      foreach (i; 0 .. N) {
        X[i] = readLong();
        Y[i] = readLong();
        S[i] = readInt();
      }

      long[] xs;
      xs ~= X;
      xs ~= Y;
      xs ~= 0;
      xs.sort;
      const xsLen = cast(int)(xs.length);
      xs ~= X[N - 1] + 1;

      auto es = new int[N];
      auto fs = new int[N];
      auto ids = new int[xsLen];
      ids[] = -1;
      foreach (i; 0 .. N) {
        es[i] = xs.lowerBound(X[i]);
        fs[i] = xs.lowerBound(Y[i]);
        ids[es[i]] = ids[fs[i]] = i;
      }
      debug {
        writeln("xs = ", xs);
        writeln("es = ", es);
        writeln("fs = ", fs);
        writeln("ids = ", ids);
      }

      auto ts = new Mint[xsLen];
      ts[xsLen - 1] = 1;
      foreach_reverse (e; 1 .. xsLen) {
        const i = ids[e];
        if (e == es[i]) {
          ts[e - 1] = ts[e] + (ts[e] - (S[i] ? 0 : 1));
        } else {
          ts[e - 1] = ts[e] - (ts[es[i]] - (S[i] ? 0 : 1));
        }
      }
      debug {
        writeln("ts = ", ts);
      }

      Mint ans;
      foreach (e; 0 .. xsLen) {
        ans += ts[e] * Mint(xs[e + 1] - xs[e]);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

immutable int mod = 998_244_353;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		alias Teleport = Tuple !(int, q{x}, int, q{y}, int, q{state});
		auto t = new Teleport [n];
		alias Event = Tuple !(int, q{pos}, int, q{num}, int, q{type});
		Event [] e;
		e.reserve (n * 2);
		foreach (int i, ref c; t)
		{
			readf !(" %s %s %s") (c.x, c.y, c.state);
			e ~= Event (c.x, i, 0);
			e ~= Event (c.y, i, 1);
		}
		e.schwartzSort !(v => v.pos);

		auto ptr = new int [2] [n];
		foreach (j; 0..n * 2)
		{
			ptr[e[j].num][e[j].type] = j;
		}

		auto r = new int [n * 2 + 1];

		void inc (int pos, int val)
		{
			for (pos += 1; pos <= n * 2; pos += (pos & -pos))
			{
				r[pos] += val - mod;
				r[pos] += (r[pos] < 0) * mod;
			}
		}

		int tot (int pos)
		{
			int res = 0;
			for (pos += 1; pos > 0; pos -= (pos & -pos))
			{
				res += r[pos] - mod;
				res += (res < 0) * mod;
			}
			return res;
		}

		int tot2 (int lo, int hi)
		in
		{
			debug {write (lo, " ", hi);}
		}
		out (res)
		{
			debug {writeln (": ", res);}
		}
		body
		{
			return (tot (hi - 1) + mod - tot (lo - 1)) % mod;

		}

		foreach (i; 0..n)
		{
			int value = (t[i].x - t[i].y) % mod;
			value = (value + tot2 (ptr[i][1], ptr[i][0])) % mod;
			inc (ptr[i][0], value);
		}
		debug {writeln (r);}

		int res = (t.back.x + 1) % mod;
		foreach (i; 0..n)
		{
			if (t[i].state)
			{
				auto pos = ptr[i][0];
				debug {writeln (i, ": ", tot2 (pos, pos + 1));}
				res = (res + tot2 (pos, pos + 1)) % mod;
			}
		}
		writeln (res);
	}
}

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

immutable int mod = 998_244_353;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		alias Teleport = Tuple !(int, q{x}, int, q{y}, int, q{state});
		auto t = new Teleport [n];
		alias Event = Tuple !(int, q{pos}, int, q{num}, int, q{type});
		Event [] e;
		e.reserve (n * 2);
		foreach (int i, ref c; t)
		{
			readf !(" %s %s %s") (c.x, c.y, c.state);
			e ~= Event (c.x, i, 0);
			e ~= Event (c.y, i, 1);
		}
		e.schwartzSort !(v => v.pos);

		auto ptr = new int [2] [n];
		foreach (j; 0..n * 2)
		{
			ptr[e[j].num][e[j].type] = j;
		}

		auto r = new int [n * 2 + 1];

		void inc (int pos, int val)
		{
			for (pos += 1; pos <= n * 2; pos += (pos & -pos))
			{
				r[pos] += val - mod;
				r[pos] += (r[pos] < 0) * mod;
			}
		}

		int tot (int pos)
		{
			int res = 0;
			for (pos += 1; pos > 0; pos -= (pos & -pos))
			{
				res += r[pos] - mod;
				res += (res < 0) * mod;
			}
			return res;
		}

		int tot2 (int lo, int hi)
		in
		{
			debug {write (lo, " ", hi);}
		}
		out (res)
		{
			debug {writeln (": ", res);}
		}
		body
		{
			return (tot (hi - 1) + mod - tot (lo - 1)) % mod;

		}

		foreach (i; 0..n)
		{
			int value = (t[i].x - t[i].y) % mod;
			value = (value + tot2 (ptr[i][1], ptr[i][0])) % mod;
			inc (ptr[i][0], value);
		}
		debug {writeln (r);}

		int res = t.back.x + 1;
		foreach (i; 0..n)
		{
			if (t[i].state)
			{
				auto pos = ptr[i][0];
				debug {writeln (i, ": ", tot2 (pos, pos + 1));}
				res = (res + tot2 (pos, pos + 1)) % mod;
			}
		}
		writeln (res);
	}
}


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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    auto B = N.iota.map!(i => tuple(i, A[i])).array;

    if (N == 2) {
        writeln(1);
        return;
    }

    if (N == 3) {
        writeln(2);
        return;
    }

    int solve() {
        long d = B[1][1] - B[0][1];
        int cnt = 0;
        int ans = -1;
        long prev = B[1][1];

        foreach (i; 2..N) {
            if (B[i][1] - prev != d) {
                cnt += 1;
                if (cnt > 1) break;
                ans = B[i][0] + 1;
            } else {
                prev = B[i][1];
            }
        }

        if (cnt == 0) {
            return B[0][0] + 1;
        } else if (cnt == 1) {
            return ans;
        } else {
            return -1;
        }
    }

    B.sort!"a[1] < b[1]";
    int ans = solve();
    if (ans != -1) {
        ans.writeln;
        return;
    }

    B.sort!"a[1] > b[1]";
    ans = solve();
    if (ans != -1) {
        ans.writeln;
        return;
    }

    writeln(-1);
}

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

bool isAP (R) (R a)
{
	foreach (i; 2..a.length)
	{
		if (a[i - 0].value - a[i - 1].value !=
		    a[i - 1].value - a[i - 2].value)
		{
			return false;
		}
	}
	return true;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		alias Pair = Tuple !(int, q{value}, int, q{num});
		auto a = new Pair [n];
		foreach (i, ref x; a)
		{
			readf (" %s", &x.value);
			x.num = i + 1;
		}
		sort (a);

		int res = -1;
		if (isAP (a[1..$]))
		{
			res = 0;
		}
		else if (isAP (a[0..$ - 1]))
		{
			res = n - 1;
		}
		else
		{
			int d = a[$ - 1].value - a[0].value;
			if (d % (n - 2) == 0)
			{
				d /= n - 2;
				int j = -1;
				foreach (i; 0..n)
				{
					if (a[i].value != a[0].value + d * i)
					{
						j = i;
						break;
					}
				}
				if (isAP (a[0..j] ~ a[j + 1..$]))
				{
					res = j;
				}
			}
		}
		writeln (res >= 0 ? a[res].num : res);
	}
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    auto B = N.iota.map!(i => tuple(i, A[i])).array;

    if (N == 2) {
        writeln(1);
        return;
    }

    if (N == 3) {
        writeln(2);
        return;
    }

    int solve() {
        long d = B[1][1] - B[0][1];
        int cnt = 0;
        int ans = -1;
        long prev = B[1][1];

        foreach (i; 2..N) {
            if (B[i][1] - prev != d) {
                cnt += 1;
                if (cnt > 1) break;
                ans = B[i][0] + 1;
            } else {
                prev = B[i][1];
            }
        }

        if (cnt == 0) {
            return 1;
        } else if (cnt == 1) {
            return ans;
        } else {
            return -1;
        }
    }

    B.sort!"a[1] < b[1]";
    int ans = solve();
    if (ans != -1) {
        ans.writeln;
        return;
    }
    B.sort!"a[1] > b[1]";
    ans = solve();
    if (ans != -1) {
        ans.writeln;
        return;
    }
    writeln(-1);
}


void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan;
      int[char] counts;
      foreach(c; S) counts[c]++;

      string ans;
      foreach(c, count; counts) {
        if (count == 2) ans ~= c;
      }

      ans ~= ans;
      foreach(c, count; counts) {
        if (count == 1) ans ~= c;
      }

      return ans;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		readln.strip.array.sort.text.writeln;
	}
}

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int[] s = readln.strip.dup.map!(x => cast(int)x).array;
    s.sort;
    writeln(s.map!(x => cast(char)x).array.idup);
  }
}


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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (i; 0..2^^n.length)
		{
			if (i >> max(0, cast(int)(n.length)-2)) continue;
			long cnt = 1;
			foreach (j; 0..n.length)
			{
				long x = n[j] - '0';
				if (j >= 2)
					if (i & (1L << (j-2)))
						--x;

				long c;
				if (i & (1L << j))
					x += 10;
				foreach (k; 0..10)
				{
					if (inside(x - k, 0, 10))
					{
						++c;
						debug writeln("i:", i, " j:", j, " x:", x, " k:", k);
					}
				}
				cnt *= c;
			}
			if (i == 0)
			{
				if (cnt != 0)
					ans[ti] += cnt-2;
			}
			else
				ans[ti] += cnt;
		}
	}

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

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

long solve(long n)
{
  long odd, even;
  long mult = 1;
  while (n > 0) {
    long odddigit = n % 10;
    n /= 10;
    long evendigit = n % 10;
    n /= 10;
    odd += odddigit * mult;
    even += evendigit * mult;
    mult *= 10;
  }
  return (odd + 1) * (even + 1) - 2;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    writeln(solve(n));
  }
}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!long;
	int[10] digs;
	foreach(i, ref di; digs)
	{
		di = n%10;
		n/=10;
	}
	debug writeln(digs);
	auto ans = 0L;
	void consider(int carry)
	{
		if (carry&0b11) return;
		int carryAt(int i)
		{
			return int((carry & (1 << i)) != 0);
		}
		long ways = 1;
		foreach(i; 0 .. 10)
		{
			if (carryAt(i+2))
			{
				auto d = digs[i];
				// x1+ci + x2 >= 10
				// (x1+x2)%10 == d
				// if (x1+ci > d) x2 is set, x1+ci + x2 >= 10
				// x1+ci > d x1+ci+9
				long w = void;
				// x1+ci+x2 = 10+d
				// x2 = 10+d-x1-ci
				// x2 >= 0 10+d-x1-ci >= 0 x1 <=
				// x2 < 10 10+d-x1-ci < 10
				// d-x1-ci < 0
				long l = d-carryAt(i)+1;
				long h = 9;
				if (l <= h) w = h-l+1;
				else w = 0;
				ways *= w;
			}
			else
			{
				auto d = digs[i];
				long w = void;
				//x1+ci+x2 = d
				// x2 = d-x1-ci
				// x2 >= 0 -> d-x1-ci >= 0 -> x1 <= d-ci
				// x2 < 10 -> d-x1-ci < 10 -> x1 > d-ci-10
				long l = 0;
				long h = d-carryAt(i);
				if (l <= h) w = h-l+1;
				else w = 0;
				ways *= w;
			}
		}
		ans += ways;
	}
	foreach(int carry; 0 .. (1<<8))
	{
		consider(carry<<2);
	}
	writeln(ans-2);
}

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

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

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

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

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


import std.conv, std.functional, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.numeric, std.range, 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, M;
int[] A, B;

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

      auto cnt = new int[N];
      auto mn = new int[N];
      mn[] = N;
      foreach (i; 0 .. M) {
        ++cnt[A[i]];
        chmin(mn[A[i]], (B[i] - A[i] + N) % N);
      }

      foreach (x; 0 .. N) {
        int ans;
        foreach (y; 0 .. N) {
          if (cnt[y] > 0) {
            chmax(ans, (y - x + N) % N + (cnt[y] - 1) * N + mn[y]);
          }
        }
        if (x > 0) {
          write(" ");
        }
        write(ans);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}

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

immutable int INF = 10L ^^ 9 + 23;
immutable int MD = 998244353;

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

    auto cnt = new int[] (n);
    auto dst = new int[] (n);

    foreach (_; 0 .. m) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        --a, --b;
        cnt[a] += 1;
        int closest = b - a + (b < a ? n : 0);
        dst[a] = dst[a] == 0 ? closest : min(dst[a], closest);
    }

    debug { writeln(dst, ' ', cnt); }

    int[] ans;

    foreach (st; 0 .. n) {
        int cur = 0;
        foreach (mv; 0 .. n) {
            int pos = (st + mv) % n;
            cur = max(cur, mv + (cnt[pos] - 1) * n + dst[pos]);
        }

        ans ~= cur;
    }

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


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

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

    auto cnt = new int[](10);
    int ans = 0;
    int day = 0;

    foreach (a; A) {
        ++day;
        cnt[a] += 1;
        foreach (j; 0..10) {
            if (cnt[j] == 0) continue;
            cnt[j] -= 1;
            if (cnt.filter!(x => x != 0).empty || cnt.reduce!max == cnt.filter!(x => x != 0).reduce!min) {
                ans = day;
            }
            cnt[j] += 1;
        }

    }

    ans.writeln;
}

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

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

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

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

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

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

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

	}

	bestx.writeln;

}

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

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

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

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

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

	int bestx = 1;
	int[] ucnt = new int[](10);
	foreach(i; 0 .. n){
		int u = us[i];
		ucnt[u] += 1;
		if(isOk(ucnt)) bestx = i + 1;
	}

	bestx.writeln;

}

bool isOk(int[] ucnt){
	int[int] countcnt;
	foreach(u; 0 .. 10){
		if(ucnt[u] == 0) continue;
		if(!ucnt[u] in countcnt) countcnt[ucnt[u]] = 0;
		countcnt[ucnt[u]] += 1;
	}

	print!1(countcnt);

	int[] ks = countcnt.keys;
	if(ks.length == 1){
		if(ks[0] == 1) return 1;
	}
	else if(ks.length == 2){
		if(ks[0] > ks[1]){
			if(ks[0] - ks[1] == 1 && countcnt[ks[0]] == 1) return 1;
			if(ks[1] == 1 && countcnt[ks[1]] == 1) return 1;
		}
		if(ks[0] < ks[1]){
			if(ks[1] - ks[0] == 1 && countcnt[ks[1]] == 1) return 1;
			if(ks[0] == 1 && countcnt[ks[0]] == 1) return 1;
		}
	}

	return 0;
}

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

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

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

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

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

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

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

	}

	bestx.writeln;

}

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

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

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

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

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

	int bestx = 1;
	int[] ucnt = new int[](10);
	foreach(i; 0 .. n){
		int u = us[i];
		ucnt[u] += 1;
		if(isOk(ucnt)) bestx = i + 1;
	}

	bestx.writeln;

}

bool isOk(int[] ucnt){
	int[int] countcnt;
	foreach(u; 0 .. 10){
		if(ucnt[u] == 0) continue;
		if(!ucnt[u] in countcnt) countcnt[ucnt[u]] = 1;
		countcnt[ucnt[u]] += 1;
	}

	print!1(countcnt);

	int[] ks = countcnt.keys;
	if(ks.length == 1){
		if(ks[0] == 1) return 1;
	}
	else if(ks.length == 2){
		if(ks[0] > ks[1]){
			if(ks[0] - ks[1] == 1 && countcnt[ks[0]] == 1) return 1;
			if(ks[1] == 1 && countcnt[ks[1]] == 1) return 1;
		}
		if(ks[0] < ks[1]){
			if(ks[1] - ks[0] == 1 && countcnt[ks[1]] == 1) return 1;
			if(ks[0] == 1 && countcnt[ks[0]] == 1) return 1;
		}
	}

	return 0;
}


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

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

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

  foreach (i; 1..n) a[i] += a[i-1];
  auto as = a.assumeSorted;

  auto t = 0L;
  foreach (ki; k) {
    t += ki;
    if (t >= as.back) t = 0;
    writeln(as.upperBound(t).length);
  }
}

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

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

    auto s = new long[n];

    long cs = 0;

    foreach(ref v; s)
    {
        long t;
        readf(" %s", t);
        cs += t;
        v = cs;
    }

    auto sorted = assumeSorted(s);

    cs = 0;

    foreach (_; 0 .. q)
    {
        long t;
        readf(" %s", t);
        cs += t;

        if (cs < s.back)
        {
            writeln(sorted.upperBound(cs).length);
        }
        else
        {
            writeln(s.length);
            cs = 0;
        }
    }
}

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;

void main()
{
	int n, q;
	readln.chomp.split.tie(n, q);
	ulong[] a = readln.chomp.split.map!(to!ulong).array;
	ulong[] k = readln.chomp.split.map!(to!ulong).array;

	ulong[] b = new ulong[](n);
	b[0] = a[0];
	for (int i = 1; i < n; ++i) {
		b[i] = b[i - 1] + a[i];
	}
	auto c = b.assumeSorted;
	ulong l = 0;
	OutBuffer buf = new OutBuffer();
	foreach (v; k) {
		l += v;
		debug verbose(l, c.upperBound(l));
		auto remain = c.upperBound(l).length;
		if (remain == 0) {
			l = 0;
			remain = n;
		}
		buf.writeln = remain;
	}
	buf.toString.write;
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}

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

void main()
{
    readln;
    auto a = readln.splitter.map!(to!ulong).cumulativeFold!((a,b) => a+b).array;
    auto q = readln.splitter.map!(to!ulong).array;

    debug { writeln(a); writeln(q); }

    ulong cur = 0;
    ulong [] ans;
    foreach (order; q) {
        cur += order;
        auto rng = a.assumeSorted.upperBound(cur);
        ans ~= rng.length > 0 ? rng.length : a.length;
        if (rng.length == 0) cur = 0;
    }

    ans.each!writeln;
}

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

  int n, q; rd(n, q);
  auto as=readln.split.to!(long[]);
  auto bs=readln.split.to!(long[]);
  auto sub=new long[](n+1); // sum(as[l, r])=sub[r]-sub[l-1]; 1-indexed
  foreach(i; 0..n) sub[i+1]=sub[i]+as[i];
  int pos=1;
  long cur=0;
  foreach(b; bs){
    auto rem=(sub[pos]-sub[0])-cur;
    if(b<rem){
      writeln(n-pos+1);
      // writeln("a");
      cur+=b;
    }else{
      auto o=b-rem;
      if((sub[n]-sub[pos])<=o){
        writeln(n);
        // writeln("b");
        pos=1;
        cur=0;
      }else{
        auto tri=sub.assumeSorted.trisect(o+(sub[pos]-sub[0]));
        // if(tri[1].length>0){
        //   pos=tri[0].length+1;
        // }else{

        // }
        pos=(tri[0].length+tri[1].length).to!(int); // aaaaa
        writeln(n-pos+1);
        // writeln("c");
        cur+=b;
      }
    }
    // writeln("cur: ", cur);
    // writeln("pos: ", pos);
  }
}

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


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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		int t = n * (n - 1) / 2;
		if (t <= k)
		{
			writeln ("no solution");
		}
		else
		{
			foreach (i; 0..n)
			{
				writefln ("%s %s", 0, i);
			}
		}
	}
}

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

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    int k;
    readf("%d %d ", &n, &k);
    if (n*(n-1)/2 <= k) {
        writeln("no solution");
    } else {
        foreach (i; 0..n) {
            writeln(0, ' ', i);
        }
    }
}

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

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    int k;
    readf("%d %d ", &n, &k);
    if (n*(n-1)/2 < k) {
        writeln("no solution");
    } else {
        foreach (i; 0..n) {
            writeln(0, ' ', i);
        }
    }
}

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

void main() {
    //stdin.open("input.txt", "r");
    //stdout.open("output.txt", "w");
    int n;
    int k;
    readf("%d %d ", &n, &k);
    if (n*(n-1)/2 > k) {
        writeln("no solution");
    } else {
        foreach (i; 0..n) {
            writeln(0, ' ', i);
        }
    }
}


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

void solve(string a, int n, string b, int m)
{
    const static int mod = 998244353;
    auto v = new int[n];
    v[n - 1] = 1;
    for (int i = n - 2; i >= 0; -- i)
    {
        v[i] = v[i + 1] << 1;
        v[i] %= mod;
    }
    auto c = new int[max(n, m)];
    fill(c, 0);
    auto start = n > m ? n - m : 0;
    foreach (i; start .. max(n, m))
    {
        c[i] = b[i - start] == '1' ? 1 : 0;
        if (i > start) c[i] += c[i - 1];
    }
    auto ans = 0;
    auto shift = n > m ? 0 : m - n;
    start = n > m ? n - m : 0;
    foreach (i; start .. n)
    {
        if (a[i] == '1')
        {
            ans += (cast(long)c[i + shift] * v[i]) % mod;
            ans %= mod;
        }
    }
    writeln(ans);
}

int main(string[] args)
{
    int n, m;
    while (readf("%d %d\n", &n, &m) == 2)
    {
        auto a = readln.strip;
        auto b = readln.strip;
        solve(a, n, b, m);
    }
    return 0;
}

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

  int n, m;
  rd(n, m);
  auto a = readln.chomp
    .to!(char[])
    .map!((ch) => (ch - '0'))
    .array
    .to!(long[]);
  auto b = readln.chomp
    .to!(char[])
    .map!((ch) => (ch - '0'))
    .array
    .to!(long[]);

  if (n < m) {
    a.reverse;
    foreach (_; 0 .. (m - n))
      a ~= 0;
    a.reverse;
  } else {
    b.reverse;
    foreach (_; 0 .. (n - m))
      b ~= 0;
    b.reverse;
  }

  foreach (i; 1 .. b.length)
    b[i] += b[i - 1];
  const long mod = 998244353;
  long pow2 = 1, ans = 0;
  foreach_reverse (i; 0 .. a.length) {
    if (a[i]) {
      ans += pow2 * b[i] % mod;
      ans %= mod;
    }
    pow2 *= 2;
    pow2 %= mod;
  }
  writeln(ans);

}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}

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

void solve(string a, int n, string b, int m)
{
    const static int mod = 998244353;
    auto v = new int[n];
    v[n - 1] = 1;
    for (int i = n - 2; i >= 0; -- i)
    {
        v[i] = v[i + 1] << 1;
        v[i] %= mod;
    }
    auto c = new int[max(n, m)];
    fill(c, 0);
    auto start = n > m ? n - m : 0;
    foreach (i; start .. max(n, m))
    {
        c[i] = b[i] == '1' ? 1 : 0;
        if (i > start) c[i] += c[i - 1];
    }
    auto ans = 0;
    start = n > m ? n - m : m - n;
    foreach (i; start .. start + n)
    {
        if (a[i - start] == '1')
        {
            ans += (cast(long)c[i] * v[i - start]) % mod;
            ans %= mod;
        }
    }
    writeln(ans);
}

int main(string[] args)
{
    int n, m;
    while (readf("%d %d\n", &n, &m) == 2)
    {
        auto a = readln.strip;
        auto b = readln.strip;
        solve(a, n, b, m);
    }
    return 0;
}

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

void solve(string a, int n, string b, int m)
{
    const static int mod = 998244353;
    auto v = new int[n];
    v[n - 1] = 1;
    for (int i = n - 2; i >= 0; -- i)
    {
        v[i] = v[i + 1] << 1;
        v[i] %= mod;
    }
    auto c = new int[max(n, m)];
    auto start = 0;
    if (n > m)
    {
        start = n - m;
        foreach (i; 0 .. n - m)
        {
            c[i] = 0;
        }
    }
    foreach (i; start .. max(n, m))
    {
        c[i] = b[i] == '1' ? 1 : 0;
        if (i > start) c[i] += c[i - 1];
    }
    auto ans = 0;
    start = m > n ? m - n : 0;
    foreach (i; start .. start + n)
    {
        if (a[i - start] == '1')
        {
            ans += (cast(long)c[i] * v[i - start]) % mod;
            ans %= mod;
        }
    }
    writeln(ans);
}

int main(string[] args)
{
    int n, m;
    while (readf("%d %d\n", &n, &m) == 2)
    {
        auto a = readln.strip;
        auto b = readln.strip;
        solve(a, n, b, m);
    }
    return 0;
}


//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;
import std.random;

int ri () {
  return readln.stripRight.to!int;
}

string slow (string z, int k) {
  auto s = z.dup;
  for (int i = 0; i + k <= s.length; ++i) {
    reverse (s[i .. i + k]);
  }
  return s.idup;
}

void research (int k) {
  string p = "1234567890";
  foreach (i; 1 .. k + 1) {
    stderr.writeln (slow (p[0 .. k], i));
  }
}

void reseach0 () {
  research (5);
  stderr.writeln;
  research (6);
  stderr.writeln;
  research (7);
  stderr.writeln;
  research (9);
}

void main() {
  debug reseach0 ();
  const nt = ri ();
  foreach (tid; 0 .. nt) {
    const n = ri ();
    const s = readln.stripRight;
    auto z = new byte[2*n];
    foreach (i; 0 .. 2*n) z[i] = s[i%n].to!byte;
    int best = n - 1;
    byte[] ans = z[0 .. n].dup;
    reverse (ans);
    auto u = new byte[n];
    foreach_reverse (k; 0 .. n - 1) {
      u[] = z[k .. k + n][];
/*
123456 0
234561 1
345612 2
456321 3
561234 4
654321 5

123456789 0
234567891 1
345678921 2
456789123 3
567894321 4
678912345 5
789654321 6
891234567 7
987654321 8
*/
      if ((k & 1) != (n & 1)) {
        reverse (u[n - k .. n]);
      }
      if (cmp (u, ans) <= 0) {
        ans = u.dup;
        best = k;
      }
    }
    foreach (i; ans) {
      write(i.to!char);
    }
    writeln;
    writeln (best+1);
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    foreach(_; 0 .. scan!int){
        int n = scan!int;
        char[] s = scan!(char[]);

        char[] ans;
        foreach(c; s) ans ~= c;
        long best = 0;
        foreach(k; 0 .. n){
            char[] t;
            foreach(c; s[k .. n]) t ~= c;
            if((n - k) % 2) foreach_reverse(c; s[0 .. k]) t ~= c;
            else foreach(c; s[0 .. k]) t ~= c;
            log("s:", s, "k:", k, "t:", t, "ans:", ans, "best:", best);

            if(ans <= t) continue;
            else ans = t, best = k;
        }

        ans.writeln;
        (best + 1).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)); }

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 string[](t);
	auto k = new int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s = RD!string;
		auto list = new int[][](n);
		foreach (i; 0..n)
		{
			foreach (j; i..n)
				list[i] ~= s[j]-'a';
			if ((n-i) % 2 == 0)
			{
				foreach (j; 0..i)
					list[i] ~= s[j]-'a';
			}
			else
			{
				foreach_reverse (j; 0..i)
					list[i] ~= s[j]-'a';
			}
		}
		auto pos = list.MIN_POS();
		k[ti] = cast(int)(pos+1);
		foreach (i; 0..n)
		{
			ans[ti] ~= cast(char)(list[pos][i]+'a');
		}
	}

	foreach (ti; 0..t)
	{
		writeln(ans[ti]);
		writeln(k[ti]);
	}
	stdout.flush;
	debug readln;
}


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

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

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

string[] words;

int solve(char c) {
  int[] arr = new int[words.length];

  foreach (i, w; words) {
    auto a = w.count(c).to!int;
    arr[i] = a - (w.length.to!int - a);
  }

  sort(arr);
  reverse(arr);

  if (arr[0] < 1) return 0;

  long total = arr[0];
  int answer = 1;

  foreach (i; 1 .. arr.length) {
    total += arr[i];
    if (total <= 0) break;
    answer++;
  }

  return answer;
}

void main() {
  int t;
  read(t);

  while (t--) {
    int n;
    read(n);
    words = new string[n];

    foreach (i; 0 .. n) words[i] = readln[0 .. $ - 1];

    int answer = 0;
    foreach (c; 'a' .. 'f') {
      answer = max(answer, solve(c));
    }

    writeln(answer);
  }
}

import std.stdio;
import std.ascii;
import std.algorithm;
import std.range;
import core.stdc.stdio;

void main()
{
	int t = readInt!int;
	while (t--)
	{
		solve();
	}
}

void solve()
{
	int n = readInt!int;
	auto words = new char[][](n);
	foreach(ref word; words)
	{
		word = cast(char[])readString;
	}
	int maxwords = 0;
	void tryChar(char ch)
	{
		auto diff = new int[](n);
		foreach(i; 0 .. n)
		{
			diff[i] = 0;
			foreach(c; words[i])
			{
				if (c == ch) diff[i]++;
				else diff[i]--;
			}
		}
		sort!((a, b) => a > b)(diff);
		int maxlen = 0;
		int prefsum = 0;
		foreach(i, di; diff)
		{
			prefsum += di;
			if (prefsum > 0) maxlen = cast(int)i + 1;
		}
		maxwords = max(maxwords, maxlen);
	}
	foreach(ch; ['a', 'b', 'c', 'd', 'e'])
	{
		tryChar(ch);
	}
	maxwords.writeln;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

	Z!m opBinary(string operator)(Z!m rhs)
	{
		static if (operator == "+")
		{
			long result = rhs.rep + this.rep;
			if (result >= m)
				result -= m;
			return Z!m(result);
		}
		else static if (operator == "-")
		{
			long result = this.rep - rhs.rep;
			if (result < 0)
				result += m;
			return Z!m(result);
		}
		else static if (operator == "*")
		{
			long result = this.rep * rhs.rep;
			if (result >= m)
				result %= m;
			return Z!m(result);
		}
		else
			static assert(text("Operator ", operator, " not supported"));
	}

	Z!m opBinary(string operator)(long exponent) if (operator == "^^")
	{
		assert(exponent >= 0);
		Z!m base = this;
		Z!m result = 1;
		while (exponent)
		{
			if (exponent & 1)
				result = result * base;
			base = base * base;
			exponent >>= 1;
		}
		return result;
	}

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}


import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    A: foreach(_; 0 .. scan!int){
        string s = scan;
        int n = s.length.to!int;

        int a = 0, b = n - 1;
        while(a < b){
            log("a:", a, "b:", b, "s[a]:", s[a], "s[b]:", s[b]);
            if(s[a] != s[b]) break;
            a ++, b --;
        }
        if(a >= b){
            s.writeln;
            continue A;
        }
        log("a:", a, "b:", b);

        string s2 = s.split("").join("$");
        int[] mana1 = manacher(s);
        int[] manatmp = manacher(s2);
        int[] mana2; foreach(i; 0 .. manatmp.length / 2) mana2 ~= manatmp[1 + i * 2] / 2;
        log("mana1:", mana1);
        log("mana2:", mana2);

        bool isPalin(int u, int v){ // s[u .. v] is palin.
            log("u:", u, "v:", v, "s[u..v]:", s[u .. v]);
            if((v - u) % 2){
                int r = mana1[u + (v - u) / 2];
                log("odd;", "r:", r);
                return r - 1 + r >= v - u;
            }
            else{
                int r = mana2[(u + v - 1) / 2];
                log("even;", "r:", r);
                return r + r >= v - u;
            }
        }

        foreach_reverse(i; 0 .. b - a + 1){
            if(isPalin(a, a + i)){
                (s[0 .. a + i] ~ s[b + 1 .. $]).writeln;
                continue A;
            }
            if(isPalin(b - i + 1, b + 1)){
                (s[0 .. a] ~ s[b - i + 1 .. $]).writeln;
                continue A;
            }
        }
    }
}

// Manacher's algorithm
// https://snuke.hatenablog.com/entry/2014/12/02/235837
int[] manacher(string s){
    int n = s.length.to!int;
    int[] res = new int[](n);
    int i = 0, j = 0;
    while(i < n){
        while(i - j >= 0 && i + j < n && s[i - j] == s[i + j]) ++j;
        res[i] = j;
        int k = 1;
        while(i - k >= 0 && i + k < n && k + res[i - k] < j) res [i + k] = res[i - k], ++k;
        i += k; j -= k;
    }
    return res;
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.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[] manacher(T)(T a) {
  const n = cast(int)(a.length);
  auto r = new int[n * 2];
  for (int i = 0, j = 0, k; i < n * 2; i += k, j = max(j - k, 0)) {
    for (; 0 <= i - j && i + j + 1 < n * 2 && a[(i - j) / 2] == a[(i + j + 1) / 2]; ++j) {}
    r[i] = j;
    for (k = 1; 0 <= i - k && 0 <= j - k && r[i - k] != j - k; ++k) {
      r[i + k] = min(r[i - k], j - k);
    }
  }
  return r;
}

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

        const rads = manacher(S);
        debug {
          writeln("rads = ", rads);
        }

        auto ls = new int[L + 1];
        ls[] = -1;
        foreach (x; 0 .. L) {
          // x - rads[x] <= 2 k
          chmax(ls[(x - rads[x] + 1) / 2], x);
        }
        foreach (k; 1 .. L + 1) {
          chmax(ls[k], ls[k - 1]);
        }
        auto rs = new int[L + 1];
        rs[] = 2 * L;
        foreach (x; L - 1 .. 2 * L - 1) {
          // 2 (L - 1 - k) <= x + rads[x]
          chmin(rs[(2 * (L - 1) - x - rads[x] + 1) / 2], x);
        }
        foreach (k; 1 .. L + 1) {
          chmin(rs[k], rs[k - 1]);
        }
        debug {
          writeln("ls = ", ls);
          writeln("rs = ", rs);
        }

        int ansA, ansB;
        void check(int a, int b) {
          if (ansA + ansB < a + b) {
            ansA = a;
            ansB = b;
          }
        }
        foreach (k; 0 .. L + 1) {
          check(k, k);
          if (ls[k] != -1) {
            const i = k;
            const j = ls[k] - i;
            check(k + (j - i + 1), k);
          }
          if (rs[k] != 2 * L) {
            const i = L - 1 - k;
            const j = rs[k] - i;
            check(k, (i - j + 1) + k);
          }
          if ((k + 1) + (k + 1) > L) {
            break;
          }
          if (S[k] != S[L - 1 - k]) {
            break;
          }
        }
        writeln(S[0 .. ansA] ~ S[L - ansB .. L]);
      }
    }
  } catch (EOFException e) {
  }
}

// Code By H~$~C

module main;

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

// FIXME
int[] buildZ(in string s) {
  int n = cast(int)(s.length);
  int[] z; z.length = n;
  for (int i = 1, l = 0, r = 0; i < n; ++i) {
    if (i <= r) z[i] = (z[i - l] < r - i + 1 ? z[i - l] : r - i + 1);
    while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i];
    if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1;
  }
  return z;
}

void solve(in int testcase) {
  string s, t;
  s.read;
  int n = cast(int)(s.length), m;
  for (int i = 0; i < n; ++i)
    t ~= s[n - i - 1];
  if (s == t) {
    s.writeln;
    return ;
  }
  int[] z = buildZ(s ~ '$' ~ t);
  int x = z[n + 1];
  string ans1 = s[0 .. x];
  string ans2 = "";
  int mx = 0;
  string p = s[x .. n - x];
  string o;
  {
    n = cast(int)(p.length), m = n * 2 + 1;
    t = "";
    for (int i = 0; i < n; ++i)
      t ~= p[n - i - 1];
    o = p ~ '$' ~ t;
    z = buildZ(o);
    for (int i = m - 1; i >= 0; --i) {
      if (z[i] == m - i && mx < m - i) {
        mx = m - i;
        ans2 = o[i .. $];
      }
    }
  }
  p = t;
  {
    n = cast(int)(p.length), m = n * 2 + 1;
    t = "";
    for (int i = 0; i < n; ++i)
      t ~= p[n - i - 1];
    o = p ~ '$' ~ t;
    z = buildZ(o);
    for (int i = m - 1; i >= 0; --i) {
      if (z[i] == m - i && mx < m - i) {
        mx = m - i;
        ans2 = o[i .. $];
      }
    }
  }
  string ans3;
  for (int i = 0; i < x; ++i)
    ans3 ~= ans1[x - i - 1];
  (ans1 ~ ans2 ~ ans3).writeln;
}

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

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

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

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

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

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

immutable int q1 = 987_654_319;
immutable int q2 = 987_654_299;
immutable int maxN = 1_000_007;

void main ()
{
	int p1 = uniform (123_456_789, 444_333_222) * 2 + 1;
	int p2 = uniform (123_456_789, 444_333_222) * 2 + 1;
	int [] p1pow = [1];
	p1pow.reserve (maxN + 1);
	int [] p2pow = [1];
	p2pow.reserve (maxN + 1);
	foreach (i; 0..maxN)
	{
		p1pow ~= (p1pow.back * 1L * p1) % q1;
		p2pow ~= (p2pow.back * 1L * p2) % q2;
	}

	int tests;
	readf !(" %s") (tests);
	readln;
	foreach (test; 0..tests)
	{
		auto s = readln.strip;

		string lo = "";
		while (s.length >= 2 && s[0] == s[$ - 1])
		{
			lo ~= s[0];
			s = s[1..$ - 1];
		}
		string hi = lo.retro.text;

		auto n = s.length.to !(int);

		void calc (ref int [] h1, ref int [] h2, const ref string r)
		{
			h1[0] = 0;
			h2[0] = 0;
			foreach (i; 0..n)
			{
				h1[i + 1] = (h1[i] * 1L * p1 + r[i]) % q1;
				h2[i + 1] = (h2[i] * 1L * p2 + r[i]) % q2;
			}
		}

		auto h1lo = new int [n + 1];
		auto h2lo = new int [n + 1];
		calc (h1lo, h2lo, s);

		auto t = s.retro.text;
		auto h1hi = new int [n + 1];
		auto h2hi = new int [n + 1];
		calc (h1hi, h2hi, t);
		reverse (h1hi);
		reverse (h2hi);

		int bestLo = 0;
		foreach (i; 1..n + 1)
		{
			if ((h1hi[0] - h1hi[i] * 1L * p1pow[i] -
			    h1lo[i]) % q1 == 0 &&
			    (h2hi[0] - h2hi[i] * 1L * p2pow[i] -
			    h2lo[i]) % q2 == 0)
			{
				bestLo = i;
			}
		}

		reverse (h1lo);
		reverse (h2lo);
		reverse (h1hi);
		reverse (h2hi);
		swap (h1lo, h1hi);
		swap (h2lo, h2hi);
		int bestHi = 0;
		foreach (i; 1..n + 1)
		{
			if ((h1hi[0] - h1hi[i] * 1L * p1pow[i] -
			    h1lo[i]) % q1 == 0 &&
			    (h2hi[0] - h2hi[i] * 1L * p2pow[i] -
			    h2lo[i]) % q2 == 0)
			{
				bestHi = i;
			}
		}

		if (bestLo > bestHi)
		{
			lo ~= s[0..bestLo];
		}
		else
		{
			hi = s[$ - bestHi..$] ~ hi;
		}
		writeln (lo, hi);
	}
}


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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		foreach (i; 0..n)
			ans[ti][i].length = n;

		if (n % 2 == 0)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..2)
				{
					auto x = (i/2) * 2 + j;
					ans[ti][i][x] = 1;
				}
			}
		}
		else if (n % 3 == 2 || n % 3 == 0)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..3)
				{
					auto x = (i/3) * 3 + j;
					if (x >= n) break;
					ans[ti][i][x] = 1;
				}
			}
		}
		else
		{
			foreach (i; 0..n-4)
			{
				foreach (j; 0..3)
				{
					auto x = (i/3) * 3 + j;
					if (x >= n) break;
					ans[ti][i][x] = 1;
				}
			}
			foreach (i; n-4..n)
			{
				foreach (j; 0..2)
				{
					auto x = ((i-(n-4))/2) * 2 + (n-4) + j;
					ans[ti][i][x] = 1;
				}
			}
		}
	}

	foreach (e; ans)
	{
		foreach (i; 0..e.length)
		{
			write(e[i][0]);
			foreach (j; 1..e.length)
			{
				write(" ", e[i][j]);
			}
			writeln;
		}
	}
	stdout.flush;
	debug readln;
}

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

void play(){
    int n;
    n = rd!int;
    auto mat = new ll[][](n, n);
    foreach(i; 0..n){
        mat[i][] = 0;
        mat[i][i] = 1;
        mat[i][(i + 1) % n] = 1;
    }
    foreach(i; 0..n){
        mat[i].each!(a => write(a, " "));
        writeln;
    }
}

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

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		foreach (i; 0..n)
			ans[ti][i].length = n;

		if (n % 2 == 0)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..2)
				{
					auto x = (i/2) * 2 + j;
					ans[ti][i][x] = 1;
				}
			}
		}
		else
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..3)
				{
					auto x = (i/3) * 3 + j;
					ans[ti][i][x] = 1;
				}
			}
		}
	}

	foreach (e; ans)
	{
		foreach (i; 0..e.length)
		{
			write(e[i][0]);
			foreach (j; 1..e.length)
			{
				write(" ", e[i][j]);
			}
			writeln;
		}
	}
	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		foreach (i; 0..n)
			ans[ti][i].length = n;

		if (n % 2 == 0)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..2)
				{
					auto x = (i/2) * 2 + j;
					ans[ti][i][x] = 1;
				}
			}
		}
		else
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..3)
				{
					auto x = (i/3) * 3 + j;
					if (x >= n) break;
					ans[ti][i][x] = 1;
				}
			}
		}
	}

	foreach (e; ans)
	{
		foreach (i; 0..e.length)
		{
			write(e[i][0]);
			foreach (j; 1..e.length)
			{
				write(" ", e[i][j]);
			}
			writeln;
		}
	}
	stdout.flush;
	debug readln;
}


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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		int [] [] a;
		a ~= readln.splitter.map !(to !(int)).array;
		foreach (i; 1..n)
		{
			auto b = new int [n - i];
			foreach (j; 0..n - i)
			{
				b[j] = a[i - 1][j] ^ a[i - 1][j + 1];
			}
			a ~= b;
		}
		foreach (i; 1..n + 1)
		{
			foreach (j; 0..n - i)
			{
				a[i][j] = max (a[i][j],
				    a[i - 1][j], a[i - 1][j + 1]);
			}
		}

		int q;
		readf (" %s", &q);
		foreach (v; 0..q)
		{
			int l, r;
			readf (" %s %s", &l, &r);
			l -= 1;
			r -= 1;
			writeln (a[r - l][l]);
		}
	}
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;

    auto B = new long[][](N, N);
    foreach (i; 0..N) B[i][i] = A[i];

    foreach (len; 2..N+1) {
        foreach (l; 0..N-len+1) {
            int r = l + len - 1;
            B[l][r] = B[l+1][r] ^ B[l][r-1];
        }
    }

    auto dp = new long[][](N, N);
    foreach (i; 0..N) dp[i][i] = A[i];

    foreach (len; 2..N+1) {
        foreach (l; 0..N-len+1) {
            int r = l + len - 1;
            dp[l][r] = B[l][r];
            dp[l][r] = max(dp[l][r], dp[l+1][r]);
            dp[l][r] = max(dp[l][r], dp[l][r-1]);
        }
    }

    auto Q = readln.chomp.to!int;
    while (Q--) {
        auto s = readln.split.map!(to!int);
        auto a = s[0] - 1;
        auto b = s[1] - 1;
        dp[a][b].writeln;
    }
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;

    auto dp = new int[][](N, N);
    foreach (i; 0..N) dp[i][i] = A[i];

    foreach (len; 2..N+1) {
        foreach (l; 0..N-len+1) {
            int r = l + len - 1;
            if (len == 2 || len % 2 == 1) {
                dp[l][r] = A[l] ^ A[r];
            } else {
                dp[l][r] = A[l] ^ A[l+1] ^ A[r-1] ^ A[r];
            }
            dp[l][r] = max(dp[l][r], dp[l+1][r]);
            dp[l][r] = max(dp[l][r], dp[l][r-1]);
        }
    }

    auto Q = readln.chomp.to!int;
    while (Q--) {
        auto s = readln.split.map!(to!int);
        auto a = s[0] - 1;
        auto b = s[1] - 1;
        dp[a][b].writeln;
    }
}


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

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

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

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

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

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

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

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

void main()
{
    int T; get(T); while (T--) {
        int N; get(N);
        int[] AA; get(AA);
        int[3] cs;
        foreach (a; AA) ++cs[a % 3];
        int r;
        foreach (i; 0..4) {
            auto d = max(0, cs[i % 3] - N / 3);
            cs[i % 3] -= d;
            r += d;
            cs[(i + 1) % 3] += d;
        }
        writeln(r);
    }
}

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 int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int;

		auto cnt = new int[](3);
		foreach (i; 0..n)
		{
			++cnt[a[i]%3];
		}
		debug writeln("cnt:", cnt);

		auto y = n/3;
		bool done;
		while (!done)
		{
			done = true;
			foreach (i; 0..3)
			{
				if (cnt[i] > y)
				{
					done = false;
					auto x = cnt[i] - y;
					cnt[i] = y;
					ans[ti] += x;
					cnt[(i+1)%3] += x;
				}
			}
			debug writeln("cnt:", cnt);
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto c = new int [3];
		foreach (ref x; a)
		{
			c[x % 3] += 1;
		}
		int res = 0;
		foreach (j; 0..2)
		{
			foreach (i; 0..3)
			{
				while (c[i] > n / 3)
				{
					c[i] -= 1;
					c[(i + 1) % 3] += 1;
					res += 1;
				}
			}
		}
		writeln (res);
	}
}


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

int[] transform(long num)
{
    int[] res;
    while (num)
    {
        res ~= (num % 10);
        num /= 10;
    }
    reverse(res);
    return res;
}

int saiki(int idx, int cnt, int flag, int[][][] dp, int[] d)
{
    if (dp[idx][cnt][flag] != -1) return dp[idx][cnt][flag];
    if (idx == cast(int)d.length)
    {
        dp[idx][cnt][flag] = 1;
        return 1;
    }
    dp[idx][cnt][flag] = 0;
    auto bound = flag == 0 ? d[idx] : 9;
    foreach (i; 0 .. bound + 1)
    {
        if (i == 0 || cnt < 3)
        {
            auto nextFlag = i < d[idx] ? 1 : flag;
            auto ret = saiki(idx + 1, cnt + (i != 0), nextFlag, dp, d);
            dp[idx][cnt][flag] += ret;
        }
    }
    return dp[idx][cnt][flag];
}

void solve(long left, long right)
{
    auto dl = transform(left - 1);
    auto dr = transform(right);
    auto m = max(dl.length, dr.length);
    auto dp = new int[][][](m + 1, 4, 2);
    foreach (i; 0 .. m + 1)
    {
        foreach (j; 0 .. 4) fill(dp[i][j], -1);
    }
    auto cl = saiki(0, 0, 0, dp, dl);
    foreach (i; 0 .. m + 1)
    {
        foreach (j; 0 .. 4) fill(dp[i][j], -1);
    }
    auto cr = saiki(0, 0, 0, dp, dr);
    writeln(cr - cl);
}

int main(string[] drgs)
{
    auto T = to!int(readln.strip);
    foreach (i; 0 .. T)
    {
        auto p = map!(to!long)(readln.strip.split(' '));
        solve(p[0], p[1]);
    }
    return 0;
}

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

  int t;
  rd(t);
  while (t--) {
    auto args = readln.split.to!(long[]);
    long solve(long nn) {
      auto n = digit(nn);
      auto dp = new long[][][](n.length + 1, 2, 20);
      dp[0][0][0] = 1;
      foreach (i; 0 .. n.length) {
        foreach (l; 0 .. 2) {
          foreach (c; 0 .. 19) {
            auto d = l ? 9 : n[i];
            for (int digit = 0; digit <= d; digit++) {
              auto less = l || (digit < d);
              auto count = c + (digit > 0);
              dp[i + 1][less][count] += dp[i][l][c];
            }
          }
        }
      }
      long ret = 0;
      foreach (l; 0 .. 2) {
        for (int c = 0; c <= 3; c++) {
          ret += dp[n.length][l][c];
        }
      }
      return ret;
    }

    writeln(solve(args[1]) - solve(args[0] - 1));
  }
}

int[] digit(long x) {
  int[] ret;
  do {
    ret = x % 10 ~ ret;
    x /= 10;
  }
  while (x);
  return ret;
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}

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

  int t;
  rd(t);
  while (t--) {
    auto args = readln.split.to!(long[]);
    long solve(long s) {
      int[] n;
      do {
        n = s % 10 ~ n;
        s /= 10;
      }
      while (s);
      auto memo = new long[][][](n.length + 1, 2, n.length + 1);
      foreach (i; 0 .. (n.length + 1))
        foreach (j; 0 .. 2)
          foreach (k; 0 .. (n.length + 1))
            memo[i][j][k] = -1;
      long f(size_t i, bool less, int count) {
        if (i == n.length) {
          return count <= 3;
        } else {
          if (memo[i][less][count] >= 0)
            return memo[i][less][count];
          long ret = 0;
          auto digit = less ? 9 : n[i];
          for (int d = 0; d <= digit; d++) {
            auto l = less || (d < digit);
            auto c = count + (d > 0);
            ret += f(i + 1, l, c);
          }
          return memo[i][less][count] = ret;
        }
      }

      return f(0, 0, 0);
    }

    writeln(solve(args[1]) - solve(args[0] - 1));
  }
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}

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

immutable int INF = 10L ^^ 9 + 23;

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

    while (t--) {
        long le, r;
        readf("%s %s", &le, &r);
        readln;

        long go(string x) {
            int xlen = x.length.to!int;

            long getAns(bool alwaysSmaller, int pos, int nonZeroLeft, int allLeft) {
                if (pos >= xlen) { return 1; }

                if (alwaysSmaller) {
                    if (pos == 0) { //nonZeroLeft  and allLeft always > 0
                        return 9 * getAns(true, pos+1, nonZeroLeft-1, allLeft-1);
                    }

                    long ret = 0;
                    foreach (nrs; 0 .. nonZeroLeft + 1) {
                        if (nrs > allLeft) { continue; }

                        if (nrs == 0) { ret += 1; }
                        if (nrs == 1) { ret += 9 * allLeft; }
                        if (nrs == 2) { ret += 9 ^^ 2 * allLeft * (allLeft-1) / 2; }
                    }

                    return ret;
                }

                long ret = 0;
                int curDig = x[pos] - '0';

                if (pos > 0) { ret += getAns(curDig > 0, pos+1, nonZeroLeft, allLeft-1); }

                if (nonZeroLeft > 0 && curDig > 0) {
                    if (curDig > 1) {
                        int start = 1;
                        int end = x[pos] - '0' - 1;
                        int span = end - start + 1;
                        ret += span * getAns(true, pos+1, nonZeroLeft-1, allLeft-1);
                    }

                    ret += getAns(false, pos+1, nonZeroLeft-1, allLeft-1);
                }

                return ret;
            }

            long ans = getAns(false, 0, 3, xlen);
            foreach (digs; 1 .. xlen) { ans += getAns(true, 0, 3, digs); }

            return ans;
        }

        auto ans = go(r.to!string) - go((le-1).to!string);
        ans.writeln;
    }
}

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

  int t;
  rd(t);
  while (t--) {
    auto args = readln.split.to!(long[]);
    long solve(long nn) {
      auto n = digit(nn);
      auto dp = new long[][][](n.length + 1, 2, 4);
      dp[0][0][0] = 1;
      foreach (i; 0 .. n.length) {
        foreach (l; 0 .. 2) {
          foreach (c; 0 .. 4) {
            auto d = l ? 9 : n[i];
            for (int digit = 0; digit <= d; digit++) {
              auto less = l || (digit < d);
              auto count = max(3, c + (digit > 0));
              dp[i + 1][less][count] += dp[i][l][c];
            }
          }
        }
      }
      long ret = 0;
      foreach (l; 0 .. 2) {
        for (int c = 0; c <= 3; c++) {
          ret += dp[n.length][l][c];
        }
      }
      return ret;
    }

    writeln(solve(args[1]) - solve(args[0] - 1));
  }
}

int[] digit(long x) {
  int[] ret;
  do {
    ret = x % 10 ~ ret;
    x /= 10;
  }
  while (x);
  return ret;
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}


import std.stdio,std.conv;
double[100000] pp;
double ans;
long n,p,l,r;
void main()
{
	scanf(" %d %d",&n,&p);
	for(int i=0;i<n;++i)
	{
		scanf(" %d %d",&l,&r);
		pp[i]=(to!double((r/p-(l-1)/p)))/(r-l+1);
	}
	int t=to!int(n-1);
	ans=(pp[0]+pp[t]-pp[0]*pp[t])*1000;
	for(int i=1;i<n;++i)
	{
		ans+=(pp[i]+pp[i-1]-pp[i]*pp[i-1])*1000;
	}
	writef("%.10f",ans*2);
}

import std.stdio;

void main() {
  int n, p;
  readf(" %s %s", &n, &p);
  auto l = new int[n];
  auto r = new int[n];
  foreach (i; 0..n) {
    readf(" %s %s", &l[i], &r[i]);
  }
  real exp = 0;
  foreach (i; 0..n) {
    int j = (i + 1) % n;
    int ci = r[i] / p - (l[i] - 1) / p;
    int cj = r[j] / p - (l[j] - 1) / p;
    exp += 1.0 * cj / (r[j] - l[j] + 1);
    exp += 1.0 * ci / (r[i] - l[i] + 1);
    exp -= 1.0 * ci * cj / (r[i] - l[i] + 1) / (r[j] - l[j] + 1);
  }
  writeln(exp * 2000);
}

import std.stdio;

void main() {
  int n, p;
  readf(" %s %s", &n, &p);
  auto l = new int[n];
  auto r = new int[n];
  foreach (i; 0..n) {
    readf(" %s %s", &l[i], &r[i]);
  }
  real exp = 0;
  foreach (i; 0..n) {
    int j = (i + 1) % n;
    real denom = 1.0 * (r[i] - l[i] + 1) * (r[j] - l[j] + 1);
    int ci = r[i] / p - (l[i] - 1) / p;
    int cj = r[j] / p - (l[j] - 1) / p;
    exp += cj * (r[i] - l[i] + 1) / denom;
    exp += ci * (r[j] - l[j] + 1) / denom;
    exp -= ci * cj / denom;
  }
  writeln(exp * 2000);
}

import std.stdio,std.conv;
double[100000] pp;
double ans;
long n,p,l,r;
void main()
{
	scanf(" %d %d",&n,&p);
	for(int i=0;i<n;++i)
	{
		scanf(" %d %d",&l,&r);
		pp[i]=(to!double((r/p-(l-1)/p)))/(r-l+1);
	}
	int t=to!int(n-1);
	ans=(pp[0]+pp[t]-pp[0]*pp[t])*1000;
	for(int i=1;i<n;++i)
	{
		ans+=(pp[i]+pp[i-1]-pp[i]*pp[i-1])*1000;
	}
	writeln(ans*2);
}