// Vicfred
// https://codeforces.com/contest/1395/problem/C
// bit manipulation
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

    int[] a = readln.split.map!(to!int).array;
    int[] b = readln.split.map!(to!int).array;

    int ans = 0;
    for(int i = 0; i < n; i++) {
        int maxima = 0;
        for(int j = 0; j < n; j++) {
            int inf = int.max;
            for(int k = 0; k < m; k++) {
                inf = min(inf, a[j] & b[k] & (~ans));
            }
            maxima = max(maxima, inf);
        }
        ans |= maxima;
    }

    ans.writeln;
}

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

immutable int limit = 1 << 9;

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto b = readln.splitter.map !(to !(int)).array;
		auto f = new bool [] [] (2, limit);
		int z = 0;
		f[z][0] = true;
		foreach (i; 0..n)
		{
			z ^= 1;
			f[z][] = false;
			foreach (v; 0..limit)
			{
				if (f[!z][v])
				{
					foreach (j; 0..m)
					{
						f[z][v | (a[i] & b[j])] = true;
					}
				}
			}
		}
		writeln (f[z].countUntil (true));
	}
}

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

alias type = single;
struct TestCase
{
  mixin prettyPrinting;

  long n, m;
  @Dim("n") long[] a;
  @Dim("m") long[] b;

  void solve(long tc = -1)
  {
    long val = 0;
    auto neighs = makeSlice!(long[])(n);
    foreach(ref n; neighs)
      n = b.dup;
    foreach_reverse(b; 0 .. cast(long)9)
      {
        bool canAvoid = true;
        foreach(i; 0 .. n)
          {
            if (neighs.at(i).filter!(nei => ((nei & a.at(i)) & (1 << b)) == 0).empty)
              {
                canAvoid = false;
                break;
              }
          }
        if (canAvoid)
          {
            foreach(i; 0 .. n)
              {
                neighs.at(i) = neighs.at(i).filter!(nei => ((nei & a.at(i)) & (1 << b)) == 0).array;
              }
          }
        else
          {
            val = val | (1 << b);
          }
      }
    writeln(val);
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

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

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

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

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

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

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

    }
}

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

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

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 n = RD!int;
	auto m = RD!int;
	auto a = RDA;
	auto b = RDA;

	int ans = int.max;
	foreach (i; 0..2^^9)
	{
		bool okok = true;
		foreach (j; 0..n)
		{
			bool ok;
			foreach (k; 0..m)
			{
				auto x = a[j] & b[k];
				bool ng;
				foreach (l; 0..9)
				{
					auto bit = 1 << l;
					if ((i & bit) == 0 && (x & bit))
					{
						ng = true;
						break;
					}
				}
				if (!ng)
				{
					ok = true;
					break;
				}
			}
			if (!ok)
			{
				okok = false;
				break;
			}
		}
		if (okok)
			ans.chmin(i);
	}

	writeln(ans);
	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)); }
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!int;

		auto x = n;
		long keta;
		while (x != 0)
		{
			++keta;
			x /= 10;
		}

		ans[ti] += (keta-1) * 9;
		auto y = n / (10^^(keta-1));
		string s;
		foreach (i; 0..keta)
			s ~= cast(char)('0'+y);
		if (n >= s.to!long)
			ans[ti] += y;
		else
			ans[ti] += y-1;
	}

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

// Vicfred
// https://codeforces.com/contest/1520/problem/B
// greedy
import std.stdio;

void main() {
    long[] ordinary;
    long sum = 0;
    for(int i = 0; i <= 9; ++i) {
        sum += 10L^^i;
        for(long j = 1L; j <= 9L; ++j) {
            ordinary ~= j*sum;
        }
    }

    int t;
    readf("%s\n", &t);

while(t--) {
    long n;
    readf("%s\n", &n);

    int idx = 0;
    while(true) {
        if(ordinary[idx] <= n)
            idx += 1;
        else
            break;
    }
    idx.writeln;
}
}

// Vicfred
// https://codeforces.com/contest/1520/problem/B
// greedy
import std.stdio;

void main() {
    long[] ordinary;
    long sum = 0;
    for(int i = 0; i < 9; ++i) {
        sum += 10^^i;
        for(int j = 1; j <= 9; ++j) {
            ordinary ~= j*sum;
        }
    }

    int t;
    readf("%s\n", &t);

while(t--) {
    long n;
    readf("%s\n", &n);

    int idx = 0;
    while(true) {
        if(ordinary[idx] <= n)
            idx += 1;
        else
            break;
    }
    idx.writeln;
}
}

// Vicfred
// https://codeforces.com/contest/1520/problem/B
// greedy
import std.stdio;

void main() {
    long[] ordinary;
    long sum = 0;
    for(int i = 0; i < 9; ++i) {
        sum += 10^^i;
        for(int j = 1; j <= 9; ++j) {
            ordinary ~= j*sum;
        }
    }

    int t;
    readf("%s\n", &t);

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

    int idx = 0;
    while(true) {
        if(ordinary[idx] <= n)
            idx += 1;
        else
            break;
    }
    idx.writeln;
}
}


import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        int n;
        scanf("%d", &n);
        getchar();
        long[] a = readln.strip.split(" ").to!(long[]);
        long[] b = readln.strip.split(" ").to!(long[]);
        foreach (i; 0..n)
        {
            if (a[i] < b[i])
                swap(a[i], b[i]);
        }
        writeln(maxElement(a)*maxElement(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)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		long x, y;
		foreach (i; 0..n)
		{
			x.chmax(max(a[i], b[i]));
			y.chmax(min(a[i], b[i]));
		}
		ans[ti] = x * y;
	}

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

import std;

T read(T, string ending = "", string beginning = "") () {
    scope T x;
    readf!(beginning ~ "%s" ~ ending)(x);
    return x;
}

auto asVec (T) (scope return T x) @safe {
    return x.splitter(' ').map!(to!ushort).cache;
}

void main () {
    immutable tests = read!(ubyte, "\n");

    foreach (test_index; 0 .. tests) {
        immutable n = read!(uint, "\n");

        immutable ret = StoppingPolicy.requireSameLength.zip(
            asVec(readln.chomp),
            asVec(readln.chomp)
        )
            .map!(t => t[0] > t[1] ? tuple(t[1], t[0]) : t)
            .fold!((acc, t) => tuple(max(acc[0], t[0]), max(acc[1], t[1])));

        writeln(cast(uint)ret[0] * ret[1]);
    }
}
// ""

// cheese-cracker [2022-01-27]

void solve(){
    auto n = scan!int;
    auto a = scanArray;
    auto b = scanArray;
    long mn = min(a[0], b[0]);
    long mx = max(a[0], b[0]);
    for(int i = 0; i < n; ++i){
        mn = max(min(a[i], b[i]), mn);
        mx = max(max(a[i], b[i]), mx);
    }
    writeln(mn * mx);
}

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

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


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

long sd(long n)
{
  long res = 0;
  while(n)
    {
      res += n % 10;
      n /= 10;
    }
  return res;
}

long pmod(long a, long m)
{
  return (a%m + m)%m;
}

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

  auto nt = next!int;
  foreach(tc; 0 .. nt)
    {
      auto n = next!long;
      auto s = next!long;
      long tp = 1;
      foreach(i; 0 .. 19)
        {
          long rounded = n + pmod(-n, tp);
          if (rounded.sd <= s)
            {
              writeln(pmod(-n, tp));
              break;
            }
          tp *= 10;
        }
    }
}

// INPUT

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

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

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

import std.stdio, 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 long[](t);
	foreach (ti; 0..t)
	{
		auto ss = RD!(char[]);
		auto n = ss.to!long;
		auto s = RD;

		ss.reverse;

		ans[ti] = long.max;
		foreach (long i; 0..ss.length+1)
		{
			auto x = n;
			auto unit = 10L^^i;
			auto rem = x % unit ? unit - (x % unit) : 0;
			x += rem;
			long cnt;
			while (x != 0)
			{
				cnt += x % 10;
				x /= 10;
			}
			if (cnt <= s)
			{
				ans[ti].chmin(rem);
			}
		}
	}

	foreach (e; ans)
		writeln(e);
	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 long[](t);
	foreach (ti; 0..t)
	{
		auto ss = RD!(char[]);
		auto n = ss.to!long;
		auto s = RD;

		ss.reverse;

		ans[ti] = long.max;
		foreach (long flag; 0..2^^ss.length)
		{
			auto x = n;
			long tmp;
			foreach (k; 0..ss.length)
			{
				auto bit = 1L << k;
				if (!(flag & bit)) continue;
				auto y = (x / (10^^k)) % 10;
				if (y == 0) continue;
				auto z = (10 - y) * 10^^k;
				tmp += z;
				x += z;
			}
			long cnt;
			while (x != 0)
			{
				cnt += x % 10;
				x /= 10;
			}
			if (cnt <= s)
			{
				//debug writeln("flag:", flag, " tmp:", tmp, " cnt:", cnt);
				ans[ti].chmin(tmp);
			}
		}
	}

	foreach (e; ans)
		writeln(e);
	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 long[](t);
	foreach (ti; 0..t)
	{
		auto ss = RD!(char[]);
		auto n = ss.to!long;
		auto s = RD;

		ss.reverse;

		ans[ti] = long.max;
		foreach (flag; 0..2^^ss.length)
		{
			auto x = n;
			long tmp;
			foreach (k; 0..ss.length)
			{
				auto bit = 1L << k;
				if (!(flag & bit)) continue;
				auto y = (x / (10^^k)) % 10;
				if (y == 0) continue;
				auto z = (10 - y) * 10^^k;
				tmp += z;
				x += z;
			}
			long cnt;
			while (x != 0)
			{
				cnt += x % 10;
				x /= 10;
			}
			if (cnt <= s)
			{
				debug writeln("flag:", flag, " tmp:", tmp, " cnt:", cnt);
				ans[ti].chmin(tmp);
			}
		}
	}

	foreach (e; ans)
		writeln(e);
	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 long[](t);
	foreach (ti; 0..t)
	{
		auto ss = RD!(char[]);
		auto n = ss.to!long;
		auto s = RD;

		ss.reverse;

		ans[ti] = long.max;
		foreach (long flag; 0..2L^^ss.length)
		{
			auto x = n;
			long tmp;
			foreach (k; 0..ss.length)
			{
				auto bit = 1L << k;
				if (!(flag & bit)) continue;
				auto y = (x / (10^^k)) % 10;
				if (y == 0) continue;
				auto z = (10 - y) * 10^^k;
				tmp += z;
				x += z;
			}
			long cnt;
			while (x != 0)
			{
				cnt += x % 10;
				x /= 10;
			}
			if (cnt <= s)
			{
				//debug writeln("flag:", flag, " tmp:", tmp, " cnt:", cnt);
				ans[ti].chmin(tmp);
			}
		}
	}

	foreach (e; ans)
		writeln(e);
	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 long[](t);
	foreach (ti; 0..t)
	{
		auto ss = RD!(char[]);
		auto n = ss.to!long;
		auto s = RD;

		ss.reverse;

		ans[ti] = long.max;
		foreach (i; 0..ss.length+1)
		{
			auto x = n;
			auto unit = 10^^i;
			auto rem = x % unit ? unit - (x % unit) : 0;
			x += rem;
			long cnt;
			while (x != 0)
			{
				cnt += x % 10;
				x /= 10;
			}
			if (cnt <= s)
			{
				ans[ti].chmin(rem);
			}
		}
	}

	foreach (e; ans)
		writeln(e);
	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)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

        int[] xs;
        foreach (i; 0 .. N - 1) {
          if (A[i] == A[i + 1]) {
            xs ~= i;
          }
        }

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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


import std.stdio;
import std.algorithm;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		readf(" %d", &a);
		int[] m = new int[a];
		int[] n = new int[a];
		for (int j=0; j<a; j++)
		{
			readf(" %d", &m[j]);
		}
		for (int j=0; j<a; j++)
		{
			readf(" %d", &n[j]);
		}
		m.sort;
		n.sort;
		for (int j=0; j<a; j++)
		{
			writeln(m[j]);
		}
		for (int j=0; j<a; j++)
		{
			writeln(n[j]);
		}
	}
	return 0;
}

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

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

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

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

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

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

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

string FMT_F = "%.10f";

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto N = readln.chomp.to!long;

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

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

    writeln("No");
}

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

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

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

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

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

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

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


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

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

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

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

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

    auto attacks = new int[] (m);

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

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

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

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

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

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

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

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

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

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

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

    auto attacks = new int[] (m);

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

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

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

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

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

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


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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n, k;
    readf!" %d %d "(n, k);
    auto s = readln.strip;
    int[char] freq;
    foreach (ch ; s) {
      freq[ch]++;
    }
    int pairs;
    int singles;
    foreach (_, v ; freq) {
      pairs += v / 2;
      singles += v % 2;
    }
    int ans = pairs / k * 2;
    if (pairs % k == 0) {
      ans += (singles >= k);
    } else {
      ans += (singles + (pairs % k) * 2 >= k);
    }
    writeln(ans);
  }
}

void main() { runSolver(); }

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

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

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

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

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

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

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

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

      ans.writeln;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

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

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

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

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

  return ok;
}

import std;

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

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

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

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

        uint total_pairs = 0;
        uint odds = 0;

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

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

import std;

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

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

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

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

        uint total_pairs = 0;
        bool have_odd_one = false;

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

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


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

void main()
{
  int n, x;
  readf!" %d %d "(n, x);
  auto a = readln.splitter.map!(to!int).filter!(ai => ai < x).array;

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

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

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

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

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

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

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

int N, X;
int[] A;

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

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

      const ans = solve;
      writeln(ans ? "Yes" : "No");
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	int n, x;
	while (readf !(" %s %s") (n, x) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto d = new int [x + 1];
		foreach (c; a)
		{
			c = min (c, x);
			d[c] += 1;
			for ( ; c < x && d[c] == c + 1; c++)
			{
				d[c] = 0;
				d[c + 1] += 1;
			}
		}
		writeln (any (d[0..x]) ? "NO" : "YES");
	}
}


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

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

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

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

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

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

                bool con1 = true;
                bool con2 = true;

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

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

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

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


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

string FMT_F = "%.10f";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

DList!string _words;

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

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

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

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

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

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

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

    }
}

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

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


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

__gshared:

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

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

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

struct Dsu(int n) {
    int[n] p, size, count;
    bool[n] cap;

    int get(int x) {
        return x == p[x]? x : (p[x] = get(p[x]));
    }

    void merge(int x, int y) {
        x = get(x);
        y = get(y);
        if (x != y) {
            p[x] = y;
            size[y] += size[x];
            count[y] += count[x] + 1;
        } else
            count[y]++;
    }
}

int n, m, k;
int[1000] _caps;
Dsu!1000 dsu;

void main() {
    while (read(&n, &m, &k)) {
        auto caps = _caps[0 .. k];
        foreach (ref x; caps) {
            read(&x);
            x--;
        }
        iota(0, n).copy(dsu.p[ ]);
        repeat(1, n).copy(dsu.size[ ]);
        memset(dsu.count.ptr, 0x00, dsu.count.sizeof);
        memset(dsu.cap.ptr, 0x00, dsu.cap.sizeof);
        while (m--) {
            int a, b;
            read(&a, &b);
            a--;
            b--;
            dsu.merge(a, b);
        }
        foreach (x; caps)
            dsu.cap[dsu.get(x)] = true;
        int result = 0;
        int best = 0;
        foreach (i; 0 .. n) {
            int x = dsu.get(i);
            if (dsu.cap[x])
                best = max(best, dsu.size[x]);
            int total = dsu.size[x] * (dsu.size[x] - 1) >> 1;
            debug writefln("%s %s %s %s", result, dsu.size[x], total, dsu.count[x]);
            result += total - dsu.count[x];
            dsu.count[x] = total;
        }
        foreach (i; 0 .. n) {
            int x = dsu.get(i);
            if (!dsu.cap[x]) {
                result -= dsu.size[x] * (dsu.size[x] - 1) >> 1;
                foreach (j; 0 .. dsu.size[x]) {
                    result += best;
                    best++;
                }
                dsu.cap[x] = true;
            }
        }
        writeln(result);
        debug 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;
import core.bitop;

void main ()
{
	int n;
	int m;
	int k;
	while (readf (" %s %s %s", &n, &m, &k) > 0)
	{
		auto c = new bool [n];
		foreach (i; 0..k)
		{
			int u;
			readf (" %s", &u);
			u -= 1;
			c[u] = true;
		}

		auto a = new int [] [n];
		foreach (j; 0..m)
		{
			int u;
			int v;
			readf (" %s %s", &u, &v);
			u -= 1;
			v -= 1;
			a[u] ~= v;
			a[v] ~= u;
		}

		auto b = new bool [n];
		int vertices;

		bool recur (int v)
		{
			if (b[v])
			{
				return false;
			}
			b[v] = true;
			vertices += 1;
			bool ok = c[v];
			foreach (u; a[v])
			{
				ok |= recur (u);
			}
			return ok;
		}

		long res = -m;
		int largest = 0;
		int add = 0;
		for (int i = 0; i < n; i++)
		{
			if (!b[i])
			{
				vertices = 0;
				bool ok = recur (i);
				if (ok)
				{
					res += vertices * 1L *
					    (vertices - 1) / 2;
					largest = max (largest, vertices);
				}
				else
				{
					add += vertices;
				}
			}
		}
		add += largest;
		res += add * 1L * (add - 1) / 2;
		res -= largest * 1L * (largest - 1) / 2;

		writeln (res);
	}
}

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

__gshared:

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

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

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

struct Dsu(int n) {
    int[n] p, size, count;
    bool[n] cap;

    int get(int x) {
        return x == p[x]? x : (p[x] = get(p[x]));
    }

    void merge(int x, int y) {
        x = get(x);
        y = get(y);
        if (x != y) {
            p[x] = y;
            size[y] += size[x];
            count[y] += count[x] + 1;
        } else
            count[y]++;
    }
}

int n, m, k;
int[1000] _caps;
Dsu!1000 dsu;

void main() {
    while (read(&n, &m, &k)) {
        auto caps = _caps[0 .. k];
        foreach (ref x; caps) {
            read(&x);
            x--;
        }
        iota(0, n).copy(dsu.p[ ]);
        repeat(1, n).copy(dsu.size[ ]);
        memset(dsu.count.ptr, 0x00, dsu.count.sizeof);
        memset(dsu.cap.ptr, 0x00, dsu.cap.sizeof);
        while (m--) {
            int a, b;
            read(&a, &b);
            a--;
            b--;
            dsu.merge(a, b);
        }
        foreach (x; caps)
            dsu.cap[dsu.get(x)] = true;
        int result = 0;
        int best = 0;
        foreach (i; 0 .. n) {
            int x = dsu.get(i);
            if (dsu.cap[x])
                best = max(best, dsu.size[x]);
            int total = dsu.size[x] * (dsu.size[x] - 1) >> 1;
            debug writefln("%s %s %s %s", result, dsu.size[x], total, dsu.count[x]);
            result += total - dsu.count[x];
            dsu.count[x] = total;
        }
        foreach (i; 0 .. n) {
            int x = dsu.p[i];
            if (!dsu.cap[x]) {
                result -= dsu.size[x] * (dsu.size[x] - 1) >> 1;
                foreach (j; 0 .. dsu.size[x]) {
                    result += best;
                    best++;
                }
            }
        }
        writeln(result);
        debug writeln();
    }
}


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

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int t;
loop:while(read(t))
	{
		foreach(ii;0..t)
		{
			long x,y,p,q;
			read(x,y,p,q);
			long l=0,r=int.max;
			while(l<r)
			{
				long m=(l+r)>>1;
				if(p*m-x<=q*m-y && p*m-x>=0)r=m;
				else l=m+1;
			}
			if(l==int.max)writeln(-1);
			else writeln(l*q-y);
		}
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const X = readLong();
        const Y = readLong();
        const P = readLong();
        const Q = readLong();

        long ans;
        if (P == 0) {
          ans = (X == 0) ? 0 : -1;
        } else if (Q - P == 0) {
          ans = (Y - X == 0) ? 0 : -1;
        } else {
          long mx;
          chmax(mx, (X + P - 1) / P);
          chmax(mx, ((Y - X) + (Q - P) - 1) / (Q - P));
          ans = (mx * P - X) + (mx * (Q - P) - (Y - X));
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}