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

size_t n;
long[5000] staticA;

long solve(long[] arr)
{
  debug writeln("solving ", arr);
  auto res = cast(long) arr.length;
  auto mn = arr.fold!min;
  arr[] -= mn;
  debug writeln("after cropping: ", arr);
  long cmps = mn;
  int nocmps = 0;
  int i = 0;
  while(i < arr.length)
    {
      while(i < arr.length && arr[i] == 0) i++;
      if (i == arr.length)  { debug writeln("returns ", min(arr.length, cmps)); return min(arr.length, cmps); }
      debug assert(arr[i] > 0);
      int starti = i;
      while(i < arr.length && arr[i] > 0) i++;
      if (i > starti)
	cmps += solve(arr[starti .. i]);
      if (cmps >= res) { debug writeln("returns ", res); return res; }
    }
  debug assert(cmps < res);
  debug writeln("returns ", cmps);
  return cmps;
}

void main(string[] args)
{
  n = next!size_t;
  auto a = staticA[0 .. n];
  foreach(ref ai; a) ai = next!long;
  solve(a).writeln;
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}

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; scanf("%d\n", &N);
    int[] A = readln.chomp.split(" ").map!(to!int).array;

    int dfs(int s, int t, int d) {
        //writeln([s, t, d]);
        if (s == t) return 0;
        if (s + 1 == t) {
            return (A[s] > d ? 1 : 0);
        }
        int[] min_x;
        int min_v = int.max;
        for (int i = s; i < t; i++) {
            if (min_v > A[i]) {
                min_v = A[i];
                min_x = [i];
            } else if (min_v == A[i]) {
                min_x ~= i;
            }
        }

        int r = min_v - d;
        int Ret = r;

        Ret += dfs(s, min_x[0], min_v);
        for (int i = 0; i < cast(int)(min_x.length) - 1; i++) {
            if (min_x[i] == min_x[i + 1]) continue;
            Ret += dfs(min_x[i] + 1, min_x[i + 1], min_v);
        }
        Ret += dfs(min_x[$ - 1] + 1, t, min_v);

        //writeln([s, t, d], min_x, [Ret]);
        return min(Ret, t - s);
    }

    writeln(dfs(0, N, 0));
}


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

void main() {
    int n; readf("%d\n", &n);
    auto as = stdin.readln.split.map!(to!int);
    int m; readf("%d\n", &m);
    auto bs = stdin.readln.split.map!(to!int);
    int max = 0, c = 0;
    foreach (a; as) {
        foreach (b; bs) {
            if (b % a == 0) {
                if (max == b / a) {
                    c++;
                } else if (max < b / a) {
                    max = b / a;
                    c = 1;
                }
            }
        }
    }
    writeln(c);
}

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 t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                double[] arr = new double[n];
                foreach (ref i; arr) i = cin.readDouble;
                int m = cin.readInt;
                double[] brr = new double[m];
                foreach (ref i; brr) i = cin.readDouble;
                double maxRatio = -99999.0;
                for (int i = 0; i < m; i++) {
                        for (int j = 0; j < n; j++) {
                                if (brr[i] % arr[j] == 0)
                                        maxRatio = max(maxRatio, brr[i] / arr[j]);
                        }
                }
                int count = 0;
                for (int i = 0; i < m; i++) {
                        for (int j = 0; j < n; j++) {
                                if (abs(brr[i] / arr[j] - maxRatio) < 0.00001) count++;
                        }
                }
                writeln(count);
        }
}

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 t = 1;
        // t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                double[] arr = new double[n];
                foreach (ref i; arr) i = cin.readDouble;
                int m = cin.readInt;
                double[] brr = new double[m];
                foreach (ref i; brr) i = cin.readDouble;
                double maxRatio = -99999.0;
                for (int i = 0; i < m; i++) {
                        for (int j = 0; j < n; j++) {
                                if (brr[i] % arr[j] == 0)
                                        maxRatio = max(maxRatio, brr[i] / arr[j]);
                        }
                }
                int count = 0;
                for (int i = 0; i < m; i++) {
                        for (int j = 0; j < n; j++) {
                                if (brr[i] % arr[j] == 0 && brr[i] / arr[j] == maxRatio) count++;
                        }
                }
                writeln(count);
        }
}


import std.stdio;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

void solve() {
    int N, Q; readf("%d %d\n", &N, &Q);
    auto A = readln.chomp.split(" ").map!(to!int).array;

    // M[k]: minimum IQ required to test all problems of [k, n)
    auto M = new int[N];
    M[N-1] = 1;
    for (int i = N-2; i >= 0; i--) {
        int q = M[i+1];
        if (q >= A[i]) {
            M[i] = q;
        } else {
            M[i] = q + 1;
        }
    }

    char[] buf = new char[N]; buf[] = '0';
    int ans = 0;
    for (int k = 0; k < N; k++) {
        if (Q >= M[k]) {
            ans += N - k;
            buf[k..$] = '1';
            break;
        } else {
            if (Q >= A[k]) {
                ans++;
                buf[k] = '1';
            }
        }
    }
    writeln(buf);
}

void main() {
    int T = readln.chomp.to!int;
    foreach (t; 0 .. T) solve();
}

// cheese-cracker [2022-07-16]

void solve(){
    int n = scan!int;
    long q = scan;
    auto arr = scanArray;
    long k = 0;
    dchar[] res;
    for(int i = n-1; i >= 0; --i){
        if(k >= arr[i]){
            res ~= '1';
        }else{
            if(k < q){
                res ~= '1';
                ++k;
            }else{
                res ~= '0';
            }
        }
    }
    res.reverse;
    writeln(res);
}

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

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm;
import std.container, std.math, std.numeric, std.functional;
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.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons;
import core.bitop;

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

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

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

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

        auto ans = new char[N];
        ans[] = '0';

        int x = 0;
        foreach_reverse (i; 0 .. N) {
          if (x >= A[i]) {
            ans[i] = '1';
          } else {
            if (x < Q) {
              ans[i] = '1';
              ++x;
            }
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.strip.map !(q{a - '0'}).array;
		auto b = readln.strip.map !(q{a - '0'}).array;

		int mex (int lo, int hi)
		{
			bool [3] c;
			foreach (i; lo..hi)
			{
				c[a[i]] = true;
				c[b[i]] = true;
			}
			int res = 0;
			while (c[res])
			{
				res += 1;
			}
			return res;
		}

		auto f = new int [n + 1];
		f[0] = 0;
		f[1] = mex (0, 1);
		foreach (i; 2..n + 1)
		{
			foreach (j; 1..3)
			{
				f[i] = max (f[i], mex (i - j, i) + f[i - j]);
			}
		}
		writeln (f[n]);
	}
}

immutable multi = true;

void solve(int)
{
	int n = readInt!int;
	string[2] tb;
	tb[0] = readString;
	tb[1] = readString;
	auto mx = new int[](n);
	foreach(i, ref mxi; mx)
	{
		if (tb[0][i] != tb[1][i])
		{
			mx[i] = 2;
		}
		else if (tb[0][i] == '0')
		{
			mx[i] = 1;
		}
		else
		{
			mx[i] = 0;
		}
	}
	auto ans = new int[](n);
	int calc(int i)
	{
		if (i == 0) return mx[i];
		if (mx[i] == 2) return 2 + ans[i-1];
		int opt1 = mx[i] + ans[i-1];
		int opt2 = 0;
		if (mx[i] != mx[i-1])
		{
			int prev = (i-2 >= 0)? ans[i-2] : 0;
			opt2 = prev + 2;
		}
		return max(opt1, opt2);
	}
	foreach(i; 0 .. n) ans[i] = calc(i);
	ans[n-1].writeln;
}

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

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

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

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

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

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

int mex(int[] arr)
{
	if (arr.maxElement == 2)
		return 2;
	else if (arr.minElement == arr.maxElement)
		return 1 - arr.minElement;
	else
		return 2;
}

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(j; 0..t){
	int str_l;
	scanf("%d", &str_l);
	getchar();
	auto str1 = readln.strip();
	auto str2 = readln.strip();
	int[] result;
	for (int i = 0; i < str_l; i++)
	{
		if (str1[i] == str2[i])
		{
			result ~= cast(int)(str1[i] - '0');
		}
		else
			result ~= 2;
	}
	int[] mex_res;
	debug{writeln(result);}
	for (int i = 0; i < str_l; i++)
	{
		mex_res ~= mex(result[i..i+1]);
	}
	debug{writeln(mex_res);}
	for (int i = 0; i < str_l; i++)
	{
		if (mex_res[i] == 0)
		{
			if (i == 0)
			{
				if (mex_res[i+1] == 1)
				{
					if (mex(result[i..i+2]) == 2)
						mex_res[i+1]++;
				}
			}
			else if (i == str_l - 1)
			{
				if (mex_res[i-1] == 1)
				{
					if (mex(result[i-1..i+1]) == 2)
						mex_res[i-1]++;
				}
			}
			else
			{
				if (mex_res[i-1] == 1)
				{
					if (mex(result[i-1..i+1]) == 2)
						mex_res[i-1]++;
				}
				else if (mex_res[i+1] == 1)
				{
					if (mex(result[i..i+2]) == 2)
						mex_res[i+1]++;
				}
			}
		}
	}
	writeln(mex_res.sum);
    }
}

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

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split("").map!(x => (1 << x.to!int)).array;
    auto b = readln.strip.split("").map!(x => (1 << x.to!int)).array;
    foreach (i ; 0 .. n)
      a[i] |= b[i];
    long[] mexval = [0L, 1L, 0L, 2L];
    long[][] ans = new long[][](n + 1, 2);
    int[][] bits = new int[][](n + 1, 2);
    ans[0][0] = mexval[a[0]];
    ans[0][1] = 0;
    bits[0][0] = 0;
    bits[0][1] = a[0];
    foreach (i ; 1 .. n) {
      // break sequence
      long ans1 = ans[i - 1][0] + mexval[bits[i - 1][0] | a[i]];
      long ans2 = ans[i - 1][1] + mexval[bits[i - 1][1] | a[i]];
      ans[i][0] = max(ans1, ans2);
      bits[i][0] = 0;
      // continue sequence
      if (ans[i - 1][0] + mexval[a[i]] >= ans[i - 1][1] + mexval[a[i] | bits[i - 1][1]]) {
        ans[i][1] = ans[i - 1][0];
        bits[i][1] = a[i];
      } else {
        ans[i][1] = ans[i - 1][1];
        bits[i][1] = bits[i - 1][1] | a[i];
      }
    }
    writeln(max(ans[n - 1][0] + mexval[bits[n - 1][0]], ans[n - 1][1] + mexval[bits[n - 1][1]]));
  }
}

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 s1 = RD!string;
		auto s2 = RD!string;

		long last = -1;
		foreach (i; 0..n)
		{
			if (last == -1)
			{
				if (s1[i] != s2[i])
				{
					ans[ti] += 2;
					last = -1;
				}
				else if (s1[i] == '0')
				{
					ans[ti] += 1;
					last = 0;
				}
				else
					last = 1;
			}
			else if (last == 0)
			{
				if (s1[i] != s2[i])
				{
					ans[ti] += 2;
					last = -1;
				}
				else if (s1[i] == '0')
				{
					ans[ti] += 1;
					last = 0;
				}
				else
				{
					ans[ti] += 1;
					last = -1;
				}
			}
			else
			{
				if (s1[i] != s2[i])
				{
					ans[ti] += 2;
					last = -1;
				}
				else if (s1[i] == '0')
				{
					ans[ti] += 2;
					last = -1;
				}
				else
					last = 1;
			}
			debug writeln("i:", i, " ", ans[ti]);
		}
	}

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


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

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

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

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

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

immutable L = 26;

string S;
long K;
long[] W;

void main(string[] args) {
	try {
	for (; ; ) {
		S = readToken;
		K = readLong;
		W = new long[L];
		foreach (i; 0 .. L) {
			W[i] = readLong;
		}

		long ans;
		foreach (i, c; S) {
			ans += W[c - 'a'] * (i + 1);
		}
		const wMax = W.reduce!max;
		foreach (k; 0 .. K) {
			ans += wMax * (S.length + 1 + k);
		}
		writeln(ans);

	}
	} catch (EOFException) {}
}

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() {
    string S = readln.chomp;
    int K; scanf("%d\n", &K);
    int[char] W;
    foreach (char c; 'a' .. 'z' + 1) {
        int w; scanf("%d", &w);
        W[c] = w;
    }

    long Ans = 0;
    foreach (i, c; S) {
        Ans += W[c] * (i + 1);
    }

    int Max = 0;
    foreach (char c; 'a' .. 'z' + 1) {
        Max = max(Max, W[c]);
    }

    foreach (i; 0 .. K) {
        Ans += Max * (S.length + i + 1);
    }

    writeln(Ans);
}

//http://codeforces.com/contest/447/problem/B
import std.stdio;

int C_OFFSET = 97;

void main(){
  string s;
  int n;
  int max_id = 0;
  int[26] val;
  readf("%s\n" ,&s);
  readf("%s\n" ,&n);
  for(int i = 0; i < 26; i++){
    int v;
    readf("%s " ,&v);
    val[i] = v;
    if (val[max_id] < v){
      max_id = i;
    }
  }
  writeln(run(s,n,max_id,val));
}

long run(string s, int n, int max_id, int[] val){
  int[] a;
  foreach(char c;s){
    int cval = c - C_OFFSET;
    if(cval >= 0 && cval < 26){
      a ~= c - C_OFFSET;
    }
  }

  for(int i = 0; i < n; i++){
    a ~= max_id;
  }

  return s_prod(a,val);
}

long s_prod(int[] a, int[] val){
  long sum = 0;
  foreach(i,x; a){
    sum += (i+1)*val[x];
  }
  return sum;
}

// TEST CASE AREA
void test_case(){
  long[][] rs;
  rs ~= [run("abc",3,1,[1,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]),41];

  array_assert(rs);
}

void array_assert(long[][] rs){
  int i = 1;
  bool failed = false;

  writefln("TEST");

  foreach(long[] r;rs){
    if(r[0] != r[1]){
      failed = true;
      writefln("%s Failed %s is NOT %s",i,r[0],r[1]);
    }
    i++;
  }

  if(!failed){
    writefln("OK");
  }
}


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

void solve(){
    long n = scan;
    long k = scan;
    auto arr = scanArray;
    arr.sort;
    long summ = 0;
    long[] take;
    for(int i = 0; i < k; ++i){
        take ~= arr.back;
        arr.popBack;
        take ~= arr.back;
        arr.popBack;
    }
    take.sort;
    long maxc = 0;
    long c = 1;
    for(int i = 1; i < 2*k; ++i){
        if(take[i-1] == take[i]){
            ++c;
        }else{
            maxc = max(c, maxc);
            c = 1;
        }
    }
    maxc = max(maxc, c);
    long left = max(2*k - maxc, 0);
    long same = max(maxc - left, 0);
    show(left, same);
    summ = same/2 + arr.sum;
    writeln(summ);
}

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; 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; } }
alias ll = long, tup = Tuple!(long, "x",  long, "y");

immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto k = readInt!int;
  auto a = ma(n, readInt!int);
  sort(a);
  auto upper = a[$ - 2 * k .. $];
  auto lower = a[0 .. $ - 2 * k];
  int[int] cnt;
  int mostAps = 0;
  foreach(ai; upper)
    {
      cnt[ai]++;
      if (cnt[ai] > mostAps)
	{
	  mostAps = cnt[ai];
	}
    }
  debug writeln("upper ", upper);
  debug writeln("most aps ", mostAps);
  auto other = cast(int) upper.length - mostAps;
  int rem = max(mostAps - other, 0);
  (lower.sum + rem/2).writeln;
}

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

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

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

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

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

import std.algorithm, 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 a = readln.splitter.map!(to!int).array.sort.array;
    long ans;
    foreach (i ; 0 .. n - 2 * k)
      ans += a[i];
    auto b = a[$ - 2 * k .. $];
    if (b.length >= 2) {
      if (b[k] == b[k - 1]) {
        long same = b.count(b[k]);
        long lohi = b.length - same;
        if (same > lohi) {
          ans += (same - lohi) / 2;
        }
      }
    }
    writeln(ans);
  }
}


import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160_010;
void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	short[MA][] minp = new short[MA][](MN);
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			foreach_reverse (l; 0..r+1) {
				y[l] = max(y[l], minp[l][d[i][r]]);
				u[l][r] = max(u[l][r], minp[r][d[i][l]]);
				if (r > 0) {
					u[l][r] = max(u[l][r], u[l][r-1]);
				}
				u[l][r] = max(u[l][r], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
			minp[r][d[i][r]] = cast(short)(i+1);
		}
	}
	writeln(ans);
}

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			foreach_reverse (l; 0..r+1) {
				y[l] = max(y[l], minp[l][d[i][r]]);
				u[l][r] = max(u[l][r], minp[r][d[i][l]]);
				if (r > 0) {
					u[l][r] = max(u[l][r], u[l][r-1]);
				}
				u[l][r] = max(u[l][r], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
			minp[r][d[i][r]] = i+1;
		}
	}
	writeln(ans);
}

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	foreach (ref a; minp) {
		a[] = MN;
	}
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			minp[j][k] = min(minp[j][k], i);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			foreach_reverse (l; 0..r+1) {
				int p = minp[l][d[i][r]];
				if (p <= i && l < r) {
					y[l] = max(y[l], p+1);
				}
				p = minp[r][d[i][l]];
				if (p < i || (l < r && p == i)) {
					u[l][r] = max(u[l][r], p+1);
				}
				u[l][r] = max(u[l][r], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
		}
	}
	writeln(minp[0][2], ans);
}

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	foreach (ref a; minp) {
		a[] = MN;
	}
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			minp[j][k] = min(minp[j][k], i);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			int p = minp[r][d[i][r]];
			if (p < i) {
				y[r] = u[r][r] = p+1;
			}
			ans = max(ans, (i-u[r][r]+1));
			foreach_reverse (l; 0..r) {
				int pl = minp[l][d[i][r]];
				if (pl <= i) {
					y[l] = max(y[l], pl+1);
				}
				int pr = minp[r][d[i][l]];
				if (pr <= i) {
					u[l][r] = pr+1;
				}
				u[l][r] = max(u[l][r], u[l][r-1], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
		}
	}
	writeln(ans);
}

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	foreach (ref a; minp) {
		a[] = MN;
	}
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			minp[j][k] = min(minp[j][k], i);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			int p = minp[r][d[i][r]];
			if (p < i) {
				y[r] = u[r][r] = p+1;
			}
			ans = max(ans, (i-u[r][r]+1));
			foreach_reverse (l; 0..r) {
				int pl = minp[l][d[i][r]];
				if (pl <= i) {
					y[l] = max(y[l], pl+1);
				}
				int pr = minp[r][d[i][l]];
				if (pr <= i) {
					u[l][r] = pr+1;
				}
				u[l][r] = max(u[l][r], u[l][r-1], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
		}
		foreach (r; 0..m) {
			foreach (l; 0..r+1) {
				writeln(i, l, r, u[l][r]);
			}
		}
	}
	writeln(ans);
}

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	foreach (ref a; minp) {
		a[] = MN;
	}
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			minp[j][k] = min(minp[j][k], i);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			foreach_reverse (l; 0..r+1) {
				int p = minp[l][d[i][r]];
				if (p <= i && l < r) {
					y[l] = max(y[l], p+1);
				}
				p = minp[r][d[i][l]];
				if (p < i || (l < r && p == i)) {
					u[l][r] = max(u[l][r], p+1);
				}
				u[l][r] = max(u[l][r], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
		}
	}
	writeln(ans);
}

import std.range, std.stdio, std.algorithm, std.bigint, std.conv;

immutable MN = 410;
immutable MA = 160010;

void main () {
	int n, m;
	int[MN][] d = new int[MN][](MN);
	int[MA][] minp = new int[MA][](MN);
	foreach (a; minp) {
		a[] = MN;
	}
	readf("%d %d\n", &n, &m);
	foreach (i; 0..n) {
		string[] s = split(readln());
		foreach (j; 0..m) {
			auto k = to!int(s[j]);
			minp[j][k] = min(minp[j][k], i);
			d[i][j] = k;
		}
	}
	long ans = 0;
	int[MN][] u = new int[MN][](MN);
	int[MN] y;
	foreach (i; 0..n) {
		y[] = 0;
		foreach (r; 0..m) {
			foreach_reverse (l; 0..r+1) {
				int p = minp[l][d[i][r]];
				if (p <= i && l < r) {
					y[l] = max(y[l], p+1);
				}
				p = minp[r][d[i][l]];
				if (p < i || (l < r && p == i)) {
					u[l][r] = max(u[l][r], p+1);
				}
				u[l][r] = max(u[l][r], u[l+1][r], y[l]);
				ans = max(ans, (i-u[l][r]+1)*(r-l+1));
			}
		}
	}
	writeln(ans);
}


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

int main()
{
    int t = readInt!int;
    foreach(ti; 0 .. t)
    {
        int n = readInt!int;
        int[] a = new int[](n);
        int[] even;
        int[] odd;
        foreach(ref ai; a)
        {
            ai = readInt!int;
            if (ai & 1) odd ~= ai;
            else even ~= ai;
        }
        long count = 0;
        foreach(i, oi; odd)
        {
            foreach(j; i + 1 .. odd.length)
            {
                if (gcd(oi, odd[j]) > 1)
                {
                    count++;
                }
            }
        }
        count += even.length * (even.length - 1) / 2;
        count += even.length * odd.length;
        count.writeln;
    }
    return 0;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
    currChar = getchar();
}
char topChar()
{
    return cast(char) currChar;
}
void popChar()
{
    currChar = getchar();
}
auto readInt(T)()
{
    T num = 0;
    int sgn = 0;
    while (topChar.isWhite) popChar;
    while (topChar == '-' || topChar == '+') { sgn ^= (topChar == '-'); popChar; }
    while (topChar.isDigit) { num *= 10; num += (topChar - '0'); popChar; }
    if (sgn) return -num; return num;
}
string readString()
{
    string res = "";
    while (topChar.isWhite) popChar;
    while (!topChar.isWhite) { res ~= topChar; popChar; }
    return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
    long rep;
    this(long num)
    {
        rep = num;
    }
    Z!m opBinary(string operator)(Z!m rhs)
    {
        static if (operator == "+")
        {
            long result = rhs.rep + this.rep;
            if (result >= m) result -= m;
            return Z!m(result);
        }
        else static if (operator == "-")
        {
            long result = this.rep - rhs.rep;
            if (result < 0) result += m;
            return Z!m(result);
        }
        else static if (operator == "*")
        {
            long result = this.rep * rhs.rep;
            if (result >= m) result %= m;
            return Z!m(result);
        } else static assert(text("Operator ", operator, " not supported"));
    }
    Z!m opBinary(string operator)(long exponent) if (operator == "^^")
    {
        assert(exponent >= 0);
        Z!m base = this;
        Z!m result = 1;
        while (exponent)
        {
            if (exponent & 1)
                result = result * base;
            base = base * base;
            exponent >>= 1;
        }
        return result;
    }
    invariant
    {
        assert(rep >= 0 && rep < m);
    }
}

// Vicfred
// https://codeforces.com/contest/1535/problem/B
//
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

long gcd(long a, long b) {
    return b == 0L ? a : gcd(b, a%b);
}

void main() {
    int t = readln.chomp.to!int;

while(t--) {
    int n = readln.chomp.to!int;
    long[] a = readln.split.map!(to!long).array;

    long[] b;
    foreach(item; a) {
        if(item % 2 == 0)
            b = b ~ item;
    }
    foreach(item; a) {
        if(item % 2 == 1)
            b = b ~ item;
    }

    int ans = 0;
    for(int i = 0; i < n; ++i)
        for(int j = i + 1; j < n; ++j)
            if(gcd(b[i],2 * b[j]) > 1)
                ans += 1;
    ans.writeln;
}
}

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

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!int).array;
    long result = 0;
    foreach (i ; 0 .. a.length) {
      foreach (j ; i + 1 .. a.length) {
        if (gcd(a[i], a[j]) > 1)
          result++;
        else if (a[i] % 2 == 0 || a[j] % 2 == 0)
          result++;
      }
    }
    writeln(result);
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto lo = a.filter !(x => (x & 1) == 0).array;
		auto hi = a.filter !(x => (x & 1) == 1).array;
		auto b = lo ~ hi;
		int res = 0;
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n)
			{
				if (gcd (b[i], b[j] * 2) > 1)
				{
					res += 1;
				}
			}
		}
		writeln (res);
	}
}

// Vicfred
// https://codeforces.com/contest/1535/problem/B
//
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

long gcd(long a, long b) {
    return b == 0L ? a : gcd(b, a%b);
}

void main() {
    int t = readln.chomp.to!int;

while(t--) {
    int n = readln.chomp.to!int;
    long[] a = readln.split.map!(to!long).array;

    long[] b;
    foreach(item; a) {
        if(item % 2 == 0)
            b = b ~ item;
    }
    foreach(item; a) {
        if(item % 2 == 1)
            b = b ~ item;
    }
    int ans = 0;
    for(int i = 0; i < n; ++i)
        for(int j = i + 1; j < n; ++j)
            if(gcd(i,j) > 1)
                ans += 1;
    ans.writeln;
}
}


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 gojo(Int)(Int a, Int b, out Int x, out Int y) {
  if (b != 0) { Int g = gojo(b, a % b, y, x); y -= (a / b) * x; return g; }
  x = 1; y = 0; return a;
}

void main() {
  try {
    for (; ; ) {
      const T = readLong();
      const N = readInt();
      auto A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }

      auto X = new long[N + 1];
      foreach (i; 0 .. N) {
        X[i + 1] = X[i] + A[(i + 1) % N];
      }
      const M = X[N];
      debug {
        writeln("X = ", X);
      }

      long z0, z1;
      const D = gojo(M, T, z0, z1);

      alias Entry = Tuple!(long, "val", int, "i");
      auto es = new Entry[N];
      foreach (i; 0 .. N) {
        es[i] = Entry(X[i] % D, i);
      }
      es.sort;

      auto ans = new long[N];
      for (int j = 0, k; j < N; j = k) {
        for (k = j; k < N && es[j].val == es[k].val; ++k) {}
        debug {
          writeln(es[j .. k]);
        }
        const r = es[j].val;
        auto fs = new Entry[k - j];
        foreach (l; 0 .. k - j) {
          const i = es[j + l].i;
          /*
            X[i] == r + M a (mod T)
            X[i] + T b = r + M a
            (M / D) a - (T / D) b = (X[i] - r) / D
            (M / D) z0 + (T / D) z1 = 1
          */
          long a = (z0 * (((X[i] - r) / D) % (T / D))) % (T / D);
          if (a < 0) {
            a += T / D;
          }
          fs[l] = Entry(a, i);
        }
        fs.sort!"(a.val != b.val) ? (a.val < b.val) : (a.i > b.i)";
        debug {
          writeln("  fs = ", fs);
        }
        foreach (l; 0 .. k - j - 1) {
          ans[fs[l].i] = fs[l + 1].val - fs[l].val;
        }
        ans[fs[k - j - 1].i] = T / D + fs[0].val - fs[k - j - 1].val;
      }
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln;

      debug {
        auto app = new bool[cast(int)(T)];
        auto brt = new long[N];
        foreach (h; 0 .. T) {
          foreach (i; 0 .. N) {
            const x = (X[i] + M * h) % T;
            if (!app[cast(int)(x)]) {
              app[cast(int)(x)] = true;
              ++brt[i];
            }
          }
        }
        writeln("brt = ", brt);
      }
    }
  } 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 gojo(Int)(Int a, Int b, out Int x, out Int y) {
  if (b != 0) { Int g = gojo(b, a % b, y, x); y -= (a / b) * x; return g; }
  x = 1; y = 0; return a;
}

void main() {
  try {
    for (; ; ) {
      const T = readLong();
      const N = readInt();
      auto A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }

      auto X = new long[N + 1];
      foreach (i; 0 .. N) {
        X[i + 1] = X[i] + A[(i + 1) % N];
      }
      const M = X[N];
      debug {
        writeln("X = ", X);
      }

      long z0, z1;
      const D = gojo(M, T, z0, z1);

      alias Entry = Tuple!(long, "val", int, "i");
      auto es = new Entry[N];
      foreach (i; 0 .. N) {
        es[i] = Entry(X[i] % D, i);
      }
      es.sort;

      auto ans = new long[N];
      for (int j = 0, k; j < N; j = k) {
        for (k = j; k < N && es[j].val == es[k].val; ++k) {}
        debug {
          writeln(es[j .. k]);
        }
        const r = es[j].val;
        auto fs = new Entry[k - j];
        foreach (l; 0 .. k - j) {
          const i = es[j + l].i;
          /*
            X[i] == r + M a (mod T)
            X[i] + T b = r + M a
            (M / D) a - (T / D) b = (X[i] - r) / D
            (M / D) z0 + (T / D) z1 = 1
          */
          // long a = (z0 * ((X[i] - r) / D)) % (T / D);
          long a = cast(long)((z0 * BigInt((X[i] - r) / D)) % (T / D));
          if (a < 0) {
            a += T / D;
          }
          fs[l] = Entry(a, i);
        }
        fs.sort!"(a.val != b.val) ? (a.val < b.val) : (a.i > b.i)";
        debug {
          writeln("  fs = ", fs);
        }
        foreach (l; 0 .. k - j - 1) {
          ans[fs[l].i] = fs[l + 1].val - fs[l].val;
        }
        ans[fs[k - j - 1].i] = T / D + fs[0].val - fs[k - j - 1].val;
      }
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln;

      debug {
        auto app = new bool[cast(int)(T)];
        auto brt = new long[N];
        foreach (h; 0 .. T) {
          foreach (i; 0 .. N) {
            const x = (X[i] + M * h) % T;
            if (!app[cast(int)(x)]) {
              app[cast(int)(x)] = true;
              ++brt[i];
            }
          }
        }
        writeln("brt = ", brt);
      }
    }
  } 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 gojo(Int)(Int a, Int b, out Int x, out Int y) {
  if (b != 0) { Int g = gojo(b, a % b, y, x); y -= (a / b) * x; return g; }
  x = 1; y = 0; return a;
}

void main() {
  try {
    for (; ; ) {
      const T = readLong();
      const N = readInt();
      auto A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }

      auto X = new long[N + 1];
      foreach (i; 0 .. N) {
        X[i + 1] = X[i] + A[(i + 1) % N];
      }
      const M = X[N];
      debug {
        writeln("X = ", X);
      }

      long z0, z1;
      const D = gojo(M, T, z0, z1);

      alias Entry = Tuple!(long, "val", int, "i");
      auto es = new Entry[N];
      foreach (i; 0 .. N) {
        es[i] = Entry(X[i] % D, i);
      }
      es.sort;

      auto ans = new long[N];
      for (int j = 0, k; j < N; j = k) {
        for (k = j; k < N && es[j].val == es[k].val; ++k) {}
        debug {
          writeln(es[j .. k]);
        }
        const r = es[j].val;
        auto fs = new Entry[k - j];
        foreach (l; 0 .. k - j) {
          const i = es[j + l].i;
          /*
            X[i] == r + M a (mod T)
            X[i] + T b = r + M a
            (M / D) a - (T / D) b = (X[i] - r) / D
            (M / D) z0 + (T / D) z1 = 1
          */
          long a = (z0 * ((X[i] - r) / D)) % (T / D);
          if (a < 0) {
            a += T / D;
          }
          fs[l] = Entry(a, i);
        }
        fs.sort!"(a.val != b.val) ? (a.val < b.val) : (a.i > b.i)";
        debug {
          writeln("  fs = ", fs);
        }
        foreach (l; 0 .. k - j - 1) {
          ans[fs[l].i] = fs[l + 1].val - fs[l].val;
        }
        ans[fs[k - j - 1].i] = T / D + fs[0].val - fs[k - j - 1].val;
      }
      foreach (i; 0 .. N) {
        if (i > 0) write(" ");
        write(ans[i]);
      }
      writeln;

      debug {
        auto app = new bool[cast(int)(T)];
        auto brt = new long[N];
        foreach (h; 0 .. T) {
          foreach (i; 0 .. N) {
            const x = (X[i] + M * h) % T;
            if (!app[cast(int)(x)]) {
              app[cast(int)(x)] = true;
              ++brt[i];
            }
          }
        }
        writeln("brt = ", brt);
      }
    }
  } 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 int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto a = RDA!int;
		auto s = a.sum;
		ans[ti] = min(s, m);
	}

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

//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 ();
    const m = r.next!uint ();
    auto a = r.nextA!uint (n);
    const s = sum (a[1 .. $]);
    int delta = min (m - a[0], s);
    writeln (a[0] + delta);
  }
}

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

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

void solve(){
    foreach(_; 0 .. scan!int){
        int n = scan!int, m = scan!int;
        long[] as = scan!long(n);

        min(m, as.sum).writeln;
    }
}

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


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

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

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

    int cur = 0;
    int[] ans;
    foreach (e; arr) {
        cur += e;
        int d = cur / m;
        int r = cur % m;
        ans ~= d;
        cur = r;
    }

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

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

  int n; long m; rd(n, m);
  auto as=readln.split.to!(long[]);

  long s=0;
  long[] ans;
  foreach(a; as){
    s+=a;
    ans~=s/m;
    s%=m;
  }

  writefln("%(%s %)", ans);
}

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

import std.stdio, 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;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1].to!long;
    auto A = readln.split.map!(to!long).array;

    auto ans = new long[](N);
    long P = 0;

    foreach (i; 0..N) {
        ans[i] += A[i] / M;
        A[i] %= M;
        P += A[i];
        if (P >= M) ans[i] += 1, P %= M;
    }

    ans.map!(to!string).join(" ").writeln;
}


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

void readV(T...)(ref T t){auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(typeof(v));r.popFront;}}
void readA(T)(size_t n,ref T t){t=new T(n);auto r=readln.splitter;foreach(ref v;t){v=r.front.to!(ElementType!T);r.popFront;}}
void readM(T...)(size_t n,ref T t){foreach(ref v;t)v=new typeof(v)(n);foreach(i;0..n){auto r=readln.splitter;foreach(ref v;t){v[i]=r.front.to!(ElementType!(typeof(v)));r.popFront;}}}
void readS(T)(size_t n,ref T t){t=new T(n);foreach(ref v;t){auto r=readln.splitter;foreach(ref j;v.tupleof){j=r.front.to!(typeof(j));r.popFront;}}}

void main()
{
  int n; readV(n);

  if (n <= 5) {
    writeln(-1);
  } else {
    writeln("1 2");
    writeln("1 3");
    writeln("1 4");
    foreach (i; 5..n+1) writeln("2 ", i);
  }

  foreach (i; 1..n)
    writeln(i, " ", i+1);
}

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

void dame(int n)
{
	if (n < 6) {
		writeln(-1);
		return;
	}
	writeln("1 2");
	writeln("1 3");
	writeln("1 4");
	writeln("4 5");
	writeln("4 6");
	int m = n - 6;
	int ite = 7;
	int prev = 1;
	foreach (i; 0..m) {
		writefln("%d %d", prev, ite);
		prev = ite;
		++ite;
	}
}

void ok(int n) {
	foreach (i; 1..n) {
		writeln(1, " ", i + 1);
	}
}

void main()
{
	int n = readln.chomp.to!int;
	n.dame;
	n.ok;
}


import std.stdio, std.string;

string[string] words;

void main() {

	short n, m;

	scanf("%hd%hd", &n, &m);

	foreach (i; 0 .. m) {
		auto word1 = readln(' ').strip;
		auto word2 = readln.strip;
		words[word1] = (word2.length < word1.length) ? word2 : word1;
	}

	foreach (idx, lecture; readln.split) {
		write(words[lecture]);
		write((idx == n - 1) ? '\n' : ' ');
	}
}

import std.stdio, std.string;

string[string] words;

void main() {

	short n, m;

	scanf("%hd%hd", &n, &m);

	foreach (i; 0 .. m) {
		auto tmp = readln(' ').strip;
		words[tmp] = readln.strip;
	}

	foreach (idx, lecture; readln.split) {
		write((lecture.length <= words[lecture].length) ? lecture : words[lecture]);
		write((idx == n - 1) ? '\n' : ' ');
	}
}

import std.string : strip, split;
import std.stdio : scanf, readln, write;

string[string] words;

void main() {

	short n, m;

	scanf("%hd%hd", &n, &m);

	foreach (i; 0 .. m) {
		auto word1 = readln(' ').strip;
		auto word2 = readln.strip;
		if (word2.length < word1.length)
			words[word1] = word2;
	}

	foreach (idx, lecture; readln.split) {
		write(lecture in words ? words[lecture] : lecture);
		write((idx == n - 1) ? '\n' : ' ');
	}
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.ascii;
import std.algorithm;
import std.range;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int n,m;
    readf!"%d %d"(n,m);
    readln;
    string[string] aa;
    string[] l;
    while(m--){
        l=readln.split;
        aa[l[0]]=l[1];
    }
    auto f(ref string a){
        string b=aa[a];
        if(b.length<a.length) return b;
        return a;
    }
    readln.split.map!f.join(" ").writeln;
}

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

void main() {
    int n, m;
    readf("%d %d\n", &n, &m);
    string[string] dic;

    foreach(i; 0..m) {
        string a, b;
        readf("%s %s\n", &a, &b);
        if (a.length > b.length) {
            dic[a] = b;
        } else {
            dic[a] = a;
        }
    }

    string[] c = readln.chomp.split;
    c.map!(a => dic[a]).array.join(" ").writeln;
}

import std.stdio;
import std.string;

T read(T)()
{
    T t;
    readf(" %s", &t);
    return t;
}

int main(string[] args)
{
    int n = read!int;
    int m = read!int;

    string s = readln;
    string[string] dic;
    foreach (i; 0..m)
    {
        s = readln;
        auto t = s.split;
        dic[t[0]] = t[1];
    }

    bool first = true;
    foreach (w; readln.split)
    {
        if (first)
            first = false;
        else
            write(" ");

        s = dic[w];
        if (s.length < w.length)
            write(s);
        else
            write(w);
    }
    writeln;

    return 0;
}

import std.stdio, std.string;

string[string] word;

void main() {

	short n, m;

	scanf("%hd%hd", &n, &m);

	foreach (i; 0 .. m) {
		auto word1 = readln(' ').strip;
		auto word2 = readln.strip;
		word[word1] = (word2.length < word1.length) ? word2 : word1;
	}

	foreach (idx, lecture; readln.split) {
		write(word[lecture]);
		write((idx == n - 1) ? '\n' : ' ');
	}
}


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 = multi;
struct TestCase
{
  mixin prettyPrinting;

  int n;
  @Dim(q{n}) int[] a;

  void solve(long tc = -1)
  {
    int turn = 0;
    int fi = -1;
    while(true)
      {
        int maxi = -1, maxa = 0;
        foreach(i; 0 .. n)
          {
            if (i != fi)
              {
                if (a[i] > maxa)
                  {
                    maxi = i;
                    maxa = a[i];
                  }
              }
          }
        if (maxa == 0 || maxi == -1)
          {
            writeln(turn == 0? "HL" : "T");
            break;
          }
        a[maxi]--;
        fi = maxi;
        turn++;
        turn %= 2;
      }
  }
}

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

		long x = a[0];
		long y;
		foreach (i; 1..n)
		{
			y += a[i];
		}
		if (x > y)
		{
			ans[ti] = true;
		}
		else
		{
			auto d = y - x;
			if (d % 2)
				ans[ti] = true;
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto s = a.sum;
		auto m = a.maxElement;
		writeln (s % 2 == 1 || m + m > s ? "T" : "HL");
	}
}


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

long distsq(int x, int y) {
    return (cast(long)x * x) + (cast(long)y * y);
}

struct pnt {
    int x, y;
    long da, db;
}

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

    int n, ax, ay, bx, by;
    readf(" %s %s %s %s %s\n", &n, &ax, &ay, &bx, &by);
    pnt[] parr = new pnt[n + 1];
    foreach (i ; 0 .. n) {
        readf(" %s %s\n", &parr[i].x, &parr[i].y);
        parr[i].da = distsq(parr[i].x - ax, parr[i].y - ay);
        parr[i].db = distsq(parr[i].x - bx, parr[i].y - by);
    }
    parr[n] = pnt(ax, ay, 0, distsq(ax - bx, ay - by));
    parr.sort!"a.da < b.da";
    long ans = long.max;
    foreach (i ; 0 .. n + 1) {
        long r12 = parr[i].da;
        long r22 = (i < n) ? parr[i + 1 .. $].maxElement!"a.db".db : 0;
        ans = min(ans, r12 + r22);
    }
    writeln(ans);

    return 0;
}

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

long distsq(int x, int y) {
    return (cast(long)x * x) + (cast(long)y * y);
}

struct pnt {
    int x, y;
    long da, db;
}

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

    int n, ax, ay, bx, by;
    readf(" %s %s %s %s %s\n", &n, &ax, &ay, &bx, &by);
    pnt[] parr = new pnt[n];
    foreach (i ; 0 .. n) {
        readf(" %s %s\n", &parr[i].x, &parr[i].y);
        parr[i].da = distsq(parr[i].x - ax, parr[i].y - ay);
        parr[i].db = distsq(parr[i].x - bx, parr[i].y - by);
    }
    parr.sort!"a.da < b.da";
    long ans = long.max;
    foreach (i ; 0 .. n - 1) {
        long r12 = parr[i].da;
        long r22 = parr[i + 1 .. $].maxElement!"a.db".db;
        ans = min(ans, r12 + r22);
    }
    ans = min(ans, parr[0 .. $].maxElement!"a.db".db);
    ans = min(ans, parr[n - 1].da);
    writeln(ans);

    return 0;
}

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

long distsq(int x, int y) {
    return (cast(long)x * x) + (cast(long)y * y);
}

struct pnt {
    int x, y;
    long da, db;
}

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

    int n, ax, ay, bx, by;
    readf(" %s %s %s %s %s\n", &n, &ax, &ay, &bx, &by);
    pnt[] parr = new pnt[n];
    pnt*[] ppa = new pnt*[n];
    pnt*[] ppb = new pnt*[n];
    foreach (i ; 0 .. n) {
        readf(" %s %s\n", &parr[i].x, &parr[i].y);
        parr[i].da = distsq(parr[i].x - ax, parr[i].y - ay);
        parr[i].db = distsq(parr[i].x - bx, parr[i].y - by);
    }
    foreach (i ; 0 .. n) {
        ppa[i] = &parr[i];
        ppb[i] = &parr[i];
    }
    ppa.sort!"a.da < b.da";
    ppb.sort!"a.db < b.db";
    long ans = long.max;
    ans = min(ans, ppa[n-1].da);
    ans = min(ans, ppb[n-1].db);
    int idx = n - 1;
    foreach (i ; 0 .. n - 1) {
        long r12 = ppa[i].da;
        ppa[i].db = 0;
        while (idx > 0 && ppb[idx].db == 0)
            --idx;
        long r22 = ppb[idx].db;
        ans = min(ans, r12 + r22);
    }
    writeln(ans);

    return 0;
}


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

void main() {
    immutable int MAX = 1500;
    immutable long MOD = 10^^9+7;

    auto modinv = new long[](MAX);
    modinv[0] = modinv[1] = 1;
    foreach(i; 2..MAX) {
        modinv[i] = modinv[MOD % i] * (MOD - MOD / i) % MOD;
    }

    auto f_mod = new long[](MAX);
    auto f_modinv = new long[](MAX);
    f_mod[0] = f_mod[1] = 1;
    f_modinv[0] = f_modinv[1] = 1;

    foreach(i; 2..MAX) {
        f_mod[i] = (i * f_mod[i-1]) % MOD;
        f_modinv[i] = (modinv[i] * f_modinv[i-1]) % MOD;
    }

    long nck(int n, int k) {
        return f_mod[n] * f_modinv[n-k] % MOD * f_modinv[k] % MOD;
    }

    auto N = readln.chomp.to!int;
    auto A = N.iota.map!(_ => readln.chomp.to!int).array;

    int acm = A.sum;
    int empty = N;
    long ans = 1;
    foreach (i; iota(N-1, -1, -1)) {
        ans = ans * nck(acm-1, A[i]-1) % MOD;
        acm -= A[i];
    }
    ans.writeln;
}

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

void solve(int[] a, int n)
{
    static const int mod = 1000000007;
    auto t = reduce!((a, b) => a + b)(a);
    auto c = new int[][](t + 1, t + 1);
    foreach (i; 0 .. t + 1)
    {
        fill(c[i], 0);
    }
    foreach (i; 0 .. t + 1)
    {
        c[i][0] = 1;
    }
    foreach (i; 1 .. t + 1)
    {
        foreach (j; 1 .. i + 1)
        {
            c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;
        }
    }
    long ans = 1;
    for (int i = n - 1; i >= 0; -- i)
    {
        ans = (ans * c[t - 1][a[i] - 1]) % mod;
        t -= a[i];
    }
    writeln(ans);
}

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

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

void solve(int[] a, int n)
{
    static const int mod = 1000000007;
    auto t = reduce!((a, b) => a + b)(a);
    auto c = new int[][](t + 1, t + 1);
    foreach (i; 0 .. t + 1)
    {
        fill(c[i], 0);
    }
    foreach (i; 0 .. t + 1)
    {
        c[i][0] = 1;
    }
    foreach (i; 1 .. t + 1)
    {
        foreach (j; 1 .. i + 1)
        {
            c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % mod;
        }
    }
    auto ans = 1;
    for (int i = n - 1; i >= 0; -- i)
    {
        ans = (ans * c[t - 1][a[i] - 1]) % mod;
        t -= a[i];
    }
    writeln(ans);
}

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


import std;

T
read (alias T, string end = "") () {
    T x;
    readf!("%s" ~ end)(x);
    return x;
}

/** Returns how many increments must be done to `a` to reach a value
 * that satisfies `value | b == b`
 */
uint
distance (in uint a, in uint b) {
    enforce(a < b);

    foreach (shift; iota(30, -1, -1))
        if ((a & 1 << shift) != 0 && (b & 1 << shift) == 0) {
            while (!((b & 1 << shift) != 0 && (a & 1 << shift) == 0))
                ++ shift;
            immutable end = 1 << shift;
            immutable start = ~(~0 << shift) & a;

            /*
            writefln!"a:     %032b"(a);
            writefln!"b:     %032b"(b);
            writefln!"start: %032b"(start);
            writefln!"end:   %032b"(end);
            writeln("----");
            */

            return end - start;
        }
    return 0;
}

void main () {
    immutable tests = read!(uint, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        import comp = std.algorithm.comparison;

        immutable a = read!(uint, " ");
        immutable b = read!(uint, "\n");

        if (a >= b) {
            writeln(a - b);
            continue;
        }

        uint min = b - a;

        for (uint i = 0, newB = b; i < min; ++ i, ++ newB) {
            immutable to_reach = a | newB;
            immutable steps = 1 + i + to_reach - newB;

            min = comp.min(min, steps);
        }

        for (uint i = 0, newB = b; i < min; ++ i, ++ newB) {
            immutable steps = 1 + i + distance(a, newB);
            min = comp.min(min, steps);
        }

        writeln(min);
    }
}
// ""

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

enum int INF = 1<<28;

void solve() {
    int A, B; readf("%d %d\n", &A, &B);

    int ans = min(B - A, (A|B) - B + 1);

    for (int x = A; x <= B; x++) {
        uint y = 0;
        for (int k = 31; k >= 0; k--) {
            bool fa = (x & (1 << k)) > 0;
            bool fb = (B & (1 << k)) > 0;
            if (fa) {
                if (fb) {
                    y |= 1 << k;
                } else {
                    y |= 1 << k;
                    break;
                }
            } else {
                if (fb) {
                    y |= 1 << k;
                }
            }
        }
        int cost = (x - A) + (y - B) + (x | y) - y + 1;
        ans = min(ans, cost);
    }

    writeln(ans);
}

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

enum int INF = 1<<28;

void solve() {
    int A, B; readf("%d %d\n", &A, &B);

    /*
    writefln("%020b", A);
    writefln("%020b", B);
    */

    int ans = B - A;

    ans = min(ans, (A | B) - B + 1);

    int C = A & (~B);
    if (C > 0) {
        int k = C.bsr;
        ans = min(ans, (B & ~((1<<(k+1)) - 1)) - (A & ((1<<(k+1)) - 1)) + 1);
        ans = min(ans, (A & ((1<<(k+1)) - 1)) - (B & ((1<<(k+1)) - 1)) + 1);
    }
    writeln(ans);
}

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

enum int INF = 1<<28;

void solve() {
    int A, B; readf("%d %d\n", &A, &B);

    /*
    writefln("%020b", A);
    writefln("%020b", B);
    */

    int ans = B - A;

    ans = min(ans, (A | B) - B + 1);

    int C = A & (~B);
    if (C > 0) {
        int k = C.bsr;
        ans = min(ans, (B & ~(1<<k)) - (A & ((1<<(k+1)) - 1)) + 1);
        ans = min(ans, (A & ((1<<(k+1)) - 1)) - (B & ((1<<(k+1)) - 1)) + 1);
    }
    writeln(ans);
}

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

import std.stdio;
import core.bitop;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

enum int INF = 1<<28;

void solve() {
    int A, B; readf("%d %d\n", &A, &B);

    /*
    writefln("%020b", A);
    writefln("%020b", B);
    */

    int ans = B - A;

    ans = min(ans, (A | B) - B + 1);

    int C = A & (~B);
    if (C > 0) {
        int k = C.bsr;
        ans = min(ans, (B & ~(1<<k)) - (A & ((1<<(k+1)) - 1)) + 1);
    }

    int ka = A.bsr;
    ans = min(ans, (A & ((1<<(ka+1)) - 1)) - (B & ((1<<(ka+1)) - 1)) + 1);
    writeln(ans);
}

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}


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

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

    auto s = readln.chomp;

    int taken = 0, unclosed = 0;
    dchar[] ans;
    foreach (e; s) {
        if (e == '(' && taken * 2 < k) {
            ans ~= e;
            ++taken;
            ++unclosed;
        } else if (e == ')' && unclosed > 0) {
            ans ~= e;
            --unclosed;
        }
    }

    ans.writeln;
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const K = readInt();
      const S = readToken();

      alias Entry = Tuple!(int, "h", int, "i", int, "j");
      Entry[] es;

      DList!int stack;
      int now;
      foreach (i; 0 .. N) {
        if (S[i] == '(') {
          stack ~= i;
          ++now;
        } else {
          const j = stack.back;
          stack.removeBack;
          --now;
          es ~= Entry(now, j, i);
        }
      }
      es.sort;
      debug {
        writeln("es = ", es);
      }

      auto used = new bool[N];
      foreach (k; 0 .. K / 2) {
        used[es[k].i] = used[es[k].j] = true;
      }
      string ans;
      foreach (i; 0 .. N) {
        if (used[i]) {
          ans ~= S[i];
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto S = readln.chomp;

    auto st = new int[](N*2);
    int p = -1;
    int cnt = 0;
    int front = 0;

    foreach (i; 0..N) {
        if (S[i] == '(') {
            st[++p] = i;
        } else if (cnt < N - K) {
            cnt += 2;
            p -= 1;
        } else {
            st[++p] = i;
        }
    }

    foreach (i; 0..p+1) {
        write(S[st[i]]);
    }

    writeln;
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto s = '[' ~ readln.strip ~ ']';
		n += 2;
		k += 2;
		auto next = n.iota.array;
		next[] += 1;
		auto prev = n.iota.array;
		prev[] -= 1;
		int pos = 0;
		while (k < n)
		{
			int cur = next[pos];
			debug {writeln (pos, " ", cur, " ", k, " ", n);}
			if (s[pos] == '(' && s[cur] == ')')
			{
				int lo = prev[pos];
				int hi = next[cur];
				next[lo] = hi;
				prev[hi] = lo;
				n -= 2;
				pos = lo;
			}
			else
			{
				pos = next[pos];
			}
		}

		pos = 0;
		while (true)
		{
			pos = next[pos];
			if (s[pos] == ']')
			{
				break;
			}
			write (s[pos]);
		}
		writeln;
	}
}

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

void main()
{
    int n, k;
    readf("%d %d\n",  &n, &k);
    auto s = readln[0 .. $ - 1];
    string a;
    foreach(i, c; s) {
        if (!a.empty && a.back == '(' && c == ')') {
            n -= 2;
            a.popBack;
        } else {
            a ~= c;
        }
        if (n == k) {
            a ~= s[i + 1 .. $];
            break;
        }
    }
    writeln(a);
}

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

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

    auto s = readln.chomp;

    int left = k, v = 0;
    dchar[] ans;
    foreach (e; s) {
        if (e == '(' && left > 1) {
            ans ~= e;
            ++v;
            --left;
        } else if (e == ')' && v > 0 && left > 0) {
            ans ~= e;
            --v;
            --left;
        }
    }

    ans.writeln;
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto s = '[' ~ readln.strip ~ ']';
		n += 2;
		k += 2;
		auto next = n.iota.array;
		next[] += 1;
		auto prev = n.iota.array;
		prev[] -= 1;
		int pos = 0;
		while (k < n)
		{
			int cur = next[pos];
			writeln (pos, " ", cur, " ", k, " ", n);
			if (s[pos] == '(' && s[cur] == ')')
			{
				int lo = prev[pos];
				int hi = next[cur];
				next[lo] = hi;
				prev[hi] = lo;
				n -= 2;
				pos = lo;
			}
			else
			{
				pos = next[pos];
			}
		}

		pos = 0;
		while (true)
		{
			pos = next[pos];
			if (s[pos] == ']')
			{
				break;
			}
			write (s[pos]);
		}
		writeln;
	}
}