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

void main() {
  int t;
  scanf("%d", &t);

  while (t--) {
    int n;
    scanf("%d", &n);

    auto arr = new long[][](n, 2);

    foreach (ref e; arr) scanf("%ld", &e[0]);
    foreach (ref e; arr) scanf("%ld", &e[1]);

    long low = 0, high = arr.fold!((r, x) => r + x[1])(0L);
    while (low < high) {
      auto m = (high + low) / 2;
      if (arr.filter!(a => a[0] > m).map!`a[1]`.sum <= m) {
        high = m;
      } else {
        low = m + 1;
      }
    }
    high.writeln;
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto index = a.MAKE_IDX();
		long at, bt = b.sum;
		ans[ti] = bt;
		foreach (i; index)
		{
			bt -= b[i];
			at.chmax(a[i]);
			ans[ti].chmin(max(at, bt));
		}
	}

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

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

void main() {
  int t;
  scanf("%d", &t);

  while (t--) {
    int n;
    scanf("%d", &n);

    auto arr = new int[][](n, 2);

    foreach (ref e; arr) scanf("%d", &e[0]);
    foreach (ref e; arr) scanf("%d", &e[1]);

    long low = 0, high = arr.fold!((r, x) => r + x[1])(0L);
    while (low < high) {
      auto m = (high + low) / 2;
      if (arr.filter!(a => a[0] > m).map!`a[1]`.sum <= m) {
        high = m;
      } else {
        low = m + 1;
      }
    }
    high.writeln;
  }
}


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

string FMT_F = "%.10f";

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

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

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

//long mod = 10^^9 + 7;
long mod = 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) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto x = RD;
		auto a = RDA;
		a.sort!"a > b"();
		long s;
		foreach (i; 0..n)
		{
			s += a[i];
			if (s < x*(i+1)) break;
			++ans[ti];
		}
	}

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

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.stdlib;

int solve() {
    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;
    A.sort!"a > b";

    long sm = 0;

    foreach (i; 0..N) {
        sm += A[i];
        if (sm < (i + 1) * M) return i;
    }

    return N;
}

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

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n, x;
		readf !(" %s %s") (n, x);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		long cur = 0;
		int res = 0;
		foreach_reverse (i, c; a)
		{
			cur += c;
			if (cur >= (n - i) * 1L * x)
			{
				res = n - i;
			}
		}
		writeln (res);
	}
}

//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 long x = r.next!uint;
    auto a = r.nextA!uint(n);
    sort (a);
    int res;
    long s;
    debug stderr.writeln (a);
    foreach_reverse (z; a) {
      s += z;
      debug stderr.writefln ("s = %d, res = %d, x = %d", s, res, x);
      if (s < x * (res+1)) break;
      ++res;
    }
    writeln (res);
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto x = RD!int;
		auto a = RDA;
		a.sort!"a > b"();
		long s;
		foreach (i; 0..n)
		{
			s += a[i];
			if (s < x*(i+1)) break;
			++ans[ti];
		}
	}

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


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

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

  Tuple!(long, long)[200_000] pointsBucket;
  long[200_000] pointCountBucket;
  auto nt = next!int;
  foreach(tc; 0 .. nt)
    {
      auto n = next!long;
      auto k = next!long;
      auto points = pointsBucket[0 .. cast(size_t) n];
      foreach(i; 0 .. cast(size_t)n)
        points[i][0] = next!long;
      foreach(i; 0 .. cast(size_t)n)
        points[i][1] = next!long;
      auto spoints = sort(points);
      long countInRange(long lx, long hx)
      {
        return spoints.upperBound(tuple(lx, long.min)).lowerBound(tuple(hx, long.max)).length;
      }
      auto pointCount = pointCountBucket[0 .. cast(size_t)n];
      foreach(i; 0 .. cast(size_t)n)
        pointCount[i] = countInRange(points[i][0] - k, points[i][0]);
      int lowindex = 0;
      int maxbelow = 0;
      int curr = 0;
      int best = 0;
      while(curr < n)
        {
          int localbest = cast(int) pointCount[curr];
          while(lowindex < n && points[lowindex][0] < points[curr][0] - k)
            {
              maxbelow = cast(int) max(maxbelow, pointCount[lowindex]);
              lowindex++;
            }
          localbest += maxbelow;
          best = max(localbest, best);
          curr++;
        }
      writeln(best);
    }
}

// INPUT

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

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

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

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

/* Things which don't work on D:
    1. import std gives TLE so it has to be expanded to std.algorithm, std.stdio...
    2. Array Indicing ONLY typecasts integers (UNLESS 64 bit system in which case long) so EITHER cast to INT or SIZE_T
*/

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

void printer(T)(T range) { for(int i = 0; i < range.length; ++i){ write(' ', range[i]); } writeln(); }
alias ll = long;
size_t sz(long t){ return to!size_t(t); }

void play(){
    int n; ll k;
    readf(" %s %s ", &n, &k);
    auto xc = new ll [] (n);
    foreach(i; 0 .. n){
        readf("%s ", xc[i]);
    }
    readln;
    auto xcr = sort(xc);
    /* xc = assumeSorted(xc); */
    ll[] cover, tills;
    foreach(i; 0 .. n){
        auto till = n - xcr.upperBound(xc[i]+k).length;
        tills ~= till;
        cover ~= till - i;
    }
    ll[] maxleft;
    // Deep Copy (HOW TO MAKE IT WORK!)
    maxleft ~= cover;
    for(int j = n - 2; j >= 0; --j){
        maxleft[j] = max(maxleft[j+1], cover[j]);
    }
    for(auto i = 0; i < n; ++i){
        if(tills[i] < n){
            cover[i] += maxleft[sz(tills[i])];
        }
    }
    writeln(cover.maxElement());
}

int main(){
    ll t = 1;
    readf(" %s ", &t);        // Toggle!
    while(t--) play();  // Let's play!
    return 0;
}


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

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

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

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

enum L = 100;

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

        auto indeg = new int[N];
        foreach (u; 0 .. N) {
          ++indeg[A[u]];
        }

        auto cyc = new bool[N];
        auto vis = new int[N];
        vis[] = -1;
        foreach (u; 0 .. N) {
          if (!~vis[u]) {
            int v;
            for (v = u; !~vis[v]; v = A[v]) {
              vis[v] = u;
            }
            if (vis[v] == u) {
              for (int w = v; ; ) {
                cyc[w] = true;
                w = A[w];
                if (w == v) {
                  break;
                }
              }
            }
          }
        }
        debug {
          writeln("cyc = ", cyc);
        }

        auto to = A.dup;
        foreach (u; 0 .. N) {
          if (cyc[u]) {
            if (indeg[A[u]] > 1) {
              --indeg[A[u]];
              to[u] = -1;
            }
          }
        }
        foreach (u; 0 .. N) {
          if (!cyc[u]) {
            if (indeg[A[u]] > 1) {
              --indeg[A[u]];
              to[u] = -1;
            }
          }
        }

        int[] us;
        foreach (u; 0 .. N) {
          if (indeg[u] == 0) {
            for (int v = u; ~v; v = to[v]) {
              us ~= v;
            }
          }
        }
        const usLen = cast(int)(us.length);
        foreach (j; 0 .. usLen) {
          to[us[j]] = us[(j + 1) % usLen];
        }

        int ans;
        foreach (u; 0 .. N) {
          if (A[u] == to[u]) {
            ++ans;
          }
        }
        writeln(ans);
        foreach (u; 0 .. N) {
          if (u > 0) write(" ");
          write(to[u] + 1);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

// code by cutx64

module main;

import std.string, std.array, std.container, std.typecons;
import std.stdio, std.format, std.file, std.outbuffer;
import std.algorithm, std.conv, std.functional, std.range, core.bitop, std.random;
// import std.bigint, std.complex, std.bitmanip;
// import std.math, std.mathspecial, std.numeric;

void main() {

  rndGen.seed(19260817);

  int tests; readf!"%s\n"(tests);
  while(tests--) {
    int n; readf!"%s\n"(n);
    auto a = readln.splitter.map!(to!int).array;
    a[] -= 1;
    auto w = new bool[n];
    foreach(c; a) w[c] = true;
    auto b = new int[n];
    b[] -= 1;
    auto vis = new bool[n];
    foreach(v; 0 .. 2) {
      foreach(i, c; a){
        if (w[i] == v) {
          if (!vis[c]) {
            b[i] = c;
            vis[c] = true;
          }
        }
      }
    }
    auto c = n.iota.filter!(i => b[i] == -1).array;
    auto d = n.iota.filter!(i => !vis[i]).array;
    int k = c.length.to!(int);
    while (true) {
      d.randomShuffle;
      if (k.iota.all!(j => c[j] != d[j])) break;
    }
    foreach(j; 0 .. k) {
      b[c[j]] = d[j];
    }
    n.iota.map!(i => a[i] == b[i]).sum.writeln;
    writefln!"%(%s %)"(b.map!(q{a + 1}));
  }

} // main

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

void main ()
{
	rndGen.seed (125626);

	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		a[] -= 1;

		auto wanted = new bool [n];
		foreach (ref cur; a)
		{
			wanted[cur] = true;
		}

		auto b = new int [n];
		b[] = -1;
		auto vis = new bool [n];
		foreach (value; 0..2)
		{
			foreach (i, ref cur; a)
			{
				if (wanted[i] == value)
				{
					if (!vis[cur])
					{
						b[i] = cur;
						vis[cur] = true;
					}
				}
			}
		}

		auto c = n.iota.filter !(i => b[i] == -1).array;
		auto d = n.iota.filter !(i => !vis[i]).array;
		auto k = c.length.to !(int);
		if (k == 1 && c.front == d.front)
		{
			assert (false);
		}
		while (true)
		{
			randomShuffle (d);
			if (k.iota.all !(j => c[j] != d[j]))
			{
				break;
			}
		}

		foreach (j; 0..k)
		{
			b[c[j]] = d[j];
		}

		writeln (n.iota.map !(i => a[i] == b[i]).sum);
		writefln !("%(%s %)") (b.map !(q{a + 1}));
	}
}

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;

int[] inv(int[] a)
{
  auto b = new int[](a.length);
  foreach (i, x ; a) {
    b[x] = cast(int)i;
  }
  return b;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(x => x.to!int - 1).array;
    int[][int] freq;
    bool[int] used;
    foreach (i, x ; a) {
      if (!(x in freq))
        freq[x] = new int[](0);
      freq[x] ~= cast(int)i;
    }
    int[] result = new int[](n);
    result[] = -1;
    foreach (i, gifters ; freq) {
      foreach(gifter ; gifters) {
        if (gifter in used)
          continue;
        if (!(gifter in freq)) {
          result[i] = gifter;
          used[gifter] = true;
          break;
        }
      }
      if (result[i] == -1) {
        foreach(gifter ; gifters) {
          if (gifter in used)
            continue;
          result[i] = gifter;
          used[gifter] = true;
          break;
        }
      }
    }
    int[] avail;
    foreach (i ; 0 .. n) {
      if (!(i in used))
        avail ~= i;
    }
    int[] slots;
    foreach (i, x ; result) {
      if (x == -1)
        slots ~= cast(int)i;
    }

    if (slots.length == 1 && slots[0] == avail[0]) {
      foreach (i, x ; result) {
        if (x != -1) {
          avail ~= result[i];
          result[i] = -1;
          slots ~= cast(int)i;
          break;
        }
      }
    }

    assert(avail.length == slots.length);

    while (true) {
      bool good = true;
      foreach (i ; 0 .. avail.length) {
        if (avail[i] == slots[i]) {
          good = false;
          break;
        }
      }
      if (good)
        break;
      avail.randomShuffle;
    }

    foreach (i ; 0 .. avail.length) {
      result[slots[i]] = avail[i];
    }

    writeln(n - cast(int)slots.length);
    writeln(inv(result).map!(x => x + 1).map!text.joiner(" "));
  }
}

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

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

void solve()
{
	int n = readInt!int;
	auto a = new int[](n);
	auto b = new int[](n);
	b[] = -1;
	auto inds = new int[][](n);
	foreach(i, ref ai; a)
	{
		ai = readInt!int - 1;
		inds[ai] ~= cast(int)i;
	}
	int[] toGive;
	int good = 0;
	foreach(i, ind; inds)
	{
		if (ind.length > 0)
		{
			b[ind[0]] = a[ind[0]];
			assert(a[ind[0]] == cast(int)i);
			good++;
		}
		else toGive ~= cast(int)i;
	}
	foreach(i; 0 .. n)
	{
		if (b[i] == -1) { b[i] = toGive[0]; toGive = toGive[1 .. $]; }
	}
	int[] inc;
	foreach(i; 0 .. n)
	{
		if (b[i] == i) inc ~= cast(int) i;
	}
	good.writeln;
	if (inc.length == 0)
	{
		b[] += 1;
		b.each!(bi => bi.write(" ")); writeln;
	}
	else if (inc.length == 1)
	{
		auto i = inc[0];
		int o = -1;
		foreach(j; 0 .. n) if (j != i && a[j] == a[i] && b[j] == a[j])
		{
			swap(b[i], b[j]);
			break;
		}
		b[] += 1;
		b.each!(bi => bi.write(" ")); writeln;
	}
	else
	{
		int toput = 1;
		foreach(i; 0 .. n)
		{
			if (b[i] == i)
			{
				b[i] = inc[toput];
				toput++;
				if (toput == inc.length) toput = 0;
			}
		}
		b[] += 1;
		b.each!(bi => bi.write(" ")); writeln;
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

  while (t--) {
    int n;
    read(n);

    auto arr = list!int;

    auto received = new bool[n];
    auto answer   = new int[n];
    int[int] who;

    int k = 0;

    foreach (int i, e; arr) {
      if (!received[e - 1]) {
        received[e - 1] = true;
        answer[i] = e;
        who[e] = i;
        k++;
      }
    }

    writeln(k);

    auto rem = new DList!int;
    foreach (int i; 0 .. n) {
      if (!received[i]) {
        rem.insertBack(i);
      }
    }

    foreach (int i, e; arr) {
      if (answer[i] != 0) continue;

      if (rem.front == i) {
        rem.insertBack(rem.front);
        rem.removeFront();

        if (rem.front == i) {
          rem.removeFront();
          rem.insertBack(arr[i] - 1);
          answer[who[arr[i]]] = i + 1;
        }
      }

      answer[i] = rem.front + 1;
      who[rem.front + 1] = i;
      rem.removeFront();
    }

    writefln!"%(%d %)"(answer);
  }
}

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

		auto b = new bool[](n);
		foreach (i; 0..n)
		{
			b[a[i]] = true;
		}
		ans[ti].length = n;

		int[] arr;
		auto used = new bool[](n);
		foreach (i; 0..n)
		{
			if (b[i])
				++cnt[ti];
			else
				arr ~= i;
		}
		void f(int i)
		{
			int x;
			if (used[a[i]])
			{
				if (arr[0] != i)
				{
					x = arr[0];
					arr.popFront;
				}
				else
				{
					x = arr[1];
					arr ~= arr.front;
					arr = arr[2..$];
				}
			}
			else
				x = a[i];
			ans[ti][i] = x+1;
			used[x] = true;
		}
		foreach (i; 0..n)
		{
			if (!b[i])
				f(i);
		}
		foreach (i; 0..n)
		{
			if (b[i])
				f(i);
		}
	}

	foreach (ti, e; ans)
	{
		writeln(cnt[ti]);
		ans[ti].map!(to!string).join(" ").writeln;
	}
	stdout.flush;
	debug readln;
}

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;

int[] inv(int[] a)
{
  auto b = new int[](a.length);
  foreach (i, x ; a) {
    b[x] = cast(int)i;
  }
  return b;
}

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(x => x.to!int - 1).array;
    int[][int] freq;
    bool[int] used;
    foreach (i, x ; a)
      freq[x] = freq.get(x, new int[](0)) ~ [cast(int)i];
    int[] result = new int[](n);
    result[] = -1;
    foreach (i, gifters ; freq) {
      foreach(gifter ; gifters) {
        if (gifter in used)
          continue;
        if (!(gifter in freq)) {
          result[i] = gifter;
          used[gifter] = true;
          break;
        }
      }
      if (result[i] == -1) {
        foreach(gifter ; gifters) {
          if (gifter in used)
            continue;
          result[i] = gifter;
          used[gifter] = true;
          break;
        }
      }
    }
    bool[int] avail;
    foreach (i ; 0 .. n) {
      if (!(i in used))
        avail[i] = true;
    }
    int[] slots;
    foreach (i, x ; result) {
      if (x == -1)
        slots ~= cast(int)i;
    }

    if (slots.length == 1 && slots[0] in avail) {
      foreach (i, x ; result) {
        if (x != -1) {
          avail[result[i]] = true;
          result[i] = -1;
          slots ~= cast(int)i;
          break;
        }
      }
    }

    foreach (slot ; slots) {
      foreach (k, v ; avail) {
        if (k != slot) {
          result[slot] = k;
          avail.remove(k);
          break;
        }
      }
    }
    writeln(n - cast(int)slots.length);
    writeln(inv(result).map!(x => x + 1).map!text.joiner(" "));
  }
}

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

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

void solve()
{
	int n = readInt!int;
	auto a = new int[](n);
	auto b = new int[](n);
	b[] = -1;
	auto inds = new int[][](n);
	foreach(i, ref ai; a)
	{
		ai = readInt!int - 1;
		inds[ai] ~= cast(int)i;
	}
	int[] toGive;
	int good = 0;
	foreach(i, ind; inds)
	{
		if (ind.length > 0)
		{
			b[ind[0]] = a[ind[0]];
			assert(a[ind[0]] == cast(int)i);
			good++;
		}
		else toGive ~= cast(int)i;
	}
	foreach(i; 0 .. n)
	{
		if (b[i] == -1) { b[i] = toGive[0]; toGive = toGive[1 .. $]; }
	}
	int[] inc;
	foreach(i; 0 .. n)
	{
		if (b[i] == i) inc ~= cast(int) i;
	}
	good.writeln;
	if (inc.length == 0)
	{
		b[] += 1;
		b.each!(bi => bi.write(" ")); writeln;
	}
	else if (inc.length == 1)
	{
		auto i = inc[0];
		int o = -1;
		foreach(j; 0 .. n) if (j != i && a[j] == a[i] && b[j] == a[j])
		{
			swap(b[i], b[j]);
			break;
		}
		b[] += 1;
		b.each!(bi => bi.write(" ")); writeln;
	}
	else
	{
		foreach(i; 0 .. n)
		{
			if (b[i] == i)
			{
				b[i] = inc[(i + 1)%(cast(int)inc.length)];
			}
		}
		b[] += 1;
		b.each!(bi => bi.write(" ")); writeln;
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

  while (t--) {
    int n;
    read(n);

    auto arr = list!int;

    auto received = new bool[n];
    auto answer   = new int[n];
    int[int] who;

    foreach (int i, e; arr) {
      if (!received[e - 1]) {
        received[e - 1] = true;
        answer[i] = e;
        who[e] = i;
      }
    }

    auto rem = new DList!int;
    foreach (int i; 0 .. n) {
      if (!received[i]) {
        rem.insertBack(i);
      }
    }

    foreach (int i, e; arr) {
      if (answer[i] != 0) continue;

      if (rem.front == i) {
        rem.insertBack(rem.front);
        rem.removeFront();

        if (rem.front == i) {
          rem.removeFront();
          rem.insertBack(arr[i] - 1);
          answer[who[arr[i]]] = i + 1;
        }
      }

      answer[i] = rem.front + 1;
      who[rem.front + 1] = i;
      rem.removeFront();
    }

    writefln!"%(%d %)"(answer);
  }
}

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

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

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

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

enum L = 100;

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

        auto indeg = new int[N];
        foreach (u; 0 .. N) {
          ++indeg[A[u]];
        }

        auto cyc = new bool[N];
        auto vis = new int[N];
        vis[] = -1;
        foreach (u; 0 .. N) {
          if (!~vis[u]) {
            int v;
            for (v = u; !~vis[v]; v = A[v]) {
              vis[v] = u;
            }
            if (vis[v] == u) {
              for (int w = v; ; ) {
                cyc[w] = true;
                w = A[w];
                if (w == v) {
                  break;
                }
              }
            }
          }
        }
        debug {
          writeln("cyc = ", cyc);
        }

        auto to = A.dup;
        foreach (u; 0 .. N) {
          if (cyc[u]) {
            if (indeg[A[u]] > 1) {
              --indeg[A[u]];
              to[u] = -1;
            }
          }
        }
        foreach (u; 0 .. N) {
          if (indeg[A[u]] > 1) {
            --indeg[A[u]];
            to[u] = -1;
          }
        }

        int[] us;
        foreach (u; 0 .. N) {
          if (indeg[u] == 0) {
            for (int v = u; ~v; v = to[v]) {
              us ~= v;
            }
          }
        }
        const usLen = cast(int)(us.length);
        foreach (j; 0 .. usLen) {
          to[us[j]] = us[(j + 1) % usLen];
        }

        int ans;
        foreach (u; 0 .. N) {
          if (A[u] == to[u]) {
            ++ans;
          }
        }
        writeln(ans);
        foreach (u; 0 .. N) {
          if (u > 0) write(" ");
          write(to[u] + 1);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}


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

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

    while (q--) {
        int b, w;
        readf("%s %s", &b, &w);
        readln;

        Tuple!(int, int)[] ans;
        if (b == w) {
            foreach (i; 0 .. b) {
                ans ~= tuple(1, 2*i + 1);
                ans ~= tuple(1, 2*i + 2);
            }
        } else {

            int start = 2;
            if (b > w) {
                swap(b, w);
                start = 3;
            }

            ans ~= tuple(2, start);
            w -= 1;

            int reach = 0;
            int cur = start+1;
            while (b > 0) {
                b -= 1;
                ans ~= tuple(2, cur);
                cur += 1;

                w -= 1;
                ans ~= tuple(2, cur);
                cur += 1;

                reach += 2;
            }

            if (reach < w) {
                writeln("NO");
                continue;
            }

            foreach (pos; cur.iota.drop(1 + start).stride(2)) {
                foreach (rw; [1, 3]) {
                    if (w == 0) { break; }

                    ans ~= tuple(rw, pos);
                    w -= 1;
                }
            }
        }

        writeln("YES");
        ans.each!(t => writeln(t[0], ' ', t[1]));
    }
}

import std.stdio;
import std.algorithm;

int[2][200005] ans;

void solve() {
    int b, w;
    readf(" %s %s", b, w);
    int x = min(b, w);
    int y = max(b, w);
    int maxY = x * 4 - (x - 1);
    if (y > maxY) {
        writeln("NO");
        return;
    }
    int k = 0;
    foreach(i; 0..(x*2-1)) {
        ans[k][0] = 2;
        ans[k][1] = 2 + i;
        k++;
    }
    foreach(j; [1, 3]) {
        for (int i = 0; i < x && k < (b+w); i++) {
            ans[k][0] = j;
            ans[k][1] = 2 + (i*2);
            k++;
        }
    }
    if (k < b + w) {
        ans[k][0] = 2;
        ans[k][1] = 1;
        k++;
    }
    if (k < b + w) {
        ans[k][0] = 2;
        ans[k][1] = 2 + ((x - 1) * 2) + 1;
        k++;
    }

    writeln("YES");
    int shift = (x == w) ? 0 : 1;
    foreach(a; ans[0..k]) {
        writeln(a[0]+shift, " ", a[1]);
    }
}

void main() {
    int q;
    readf(" %s", q);
    foreach(_; 0..q) {
        solve();
    }
}

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

string FMT_F = "%.10f";

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; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } return r; }
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; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * y / gcd(x, y); }

//long mod = 10^^9 + 7;
long mod = 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 main()
{
	auto q = RD!int;
	auto ans = new long[2][][](q);
	foreach (i; 0..q)
	{
		auto b = RD;
		auto w = RD;
		if (max(b, w)-1 > min(b, w)*3)
		{
			continue;
		}

		long x, y;
		if (b > w)
		{
			x = 2;
			y = 3;
			ans[i] ~= [[x, y], [x+1, y]];
			--b;
			--w;
			++x;
		}
		else
		{
			x = y = 2;
			ans[i] ~= [[x, y], [x+1, y]];
			--w;
			--b;
			++x;
		}

		auto dir = [[1, 0], [0, 1], [0, -1]];
		while (b != 0 || w != 0)
		{
			if ((x+y)%2 == 0)
			{
				auto m = cast(int)min(3, max(1, b-w));
				foreach (j; 0..m)
				{
					auto dx = dir[j][0];
					auto dy = dir[j][1];
					ans[i] ~= [x+dx, y+dy];
					--b;
				}
				++x;
			}
			else
			{
				auto m = cast(int)min(3, max(1, w-b));
				foreach (j; 0..m)
				{
					auto dx = dir[j][0];
					auto dy = dir[j][1];
					ans[i] ~= [x+dx, y+dy];
					--w;
				}
				++x;
			}
		}
	}

	foreach (e; ans)
	{
		if (e.length == 0)
			writeln("NO");
		else
		{
			writeln("YES");
			foreach (ee; e)
			{
				writeln(ee[0], " ", ee[1]);
			}
		}
	}
	stdout.flush();
	debug readln();
}

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

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

    while (q--) {
        int b, w;
        readf("%s %s", &b, &w);
        readln;

        Tuple!(int, int)[] ans;
        if (b == w) {
            foreach (i; 0 .. b) {
                ans ~= tuple(1, 2*i + 1);
                ans ~= tuple(1, 2*i + 2);
            }
        } else {

            int start = 2;
            if (b > w) {
                swap(b, w);
                start = 3;
            }

            ans ~= tuple(2, start);
            w -= 1;

            int reach = 0;
            int cur = start+1;
            while (b > 0) {
                b -= 1;
                ans ~= tuple(2, cur);
                cur += 1;

                w -= 1;
                ans ~= tuple(2, cur);

                reach += 2;
            }

            if (reach < w) {
                writeln("NO");
                continue;
            }

            foreach (pos; cur.iota.drop(1 + start).stride(2)) {
                foreach (rw; [1, 3]) {
                    if (w == 0) { break; }

                    ans ~= tuple(rw, pos);
                    w -= 1;
                }
            }
        }

        writeln("YES");
        ans.each!(t => writeln(t[0], ' ', t[1]));
    }
}

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

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

    foreach (strw; (q*2 + 2).iota.drop(2).stride(2)) {
        int b, w;
        readf("%s %s", &b, &w);
        readln;

        Tuple!(int, int)[] ans;
        if (b == w) {
            foreach (i; 0 .. b) {
                ans ~= tuple(strw, 2*i + 1);
                ans ~= tuple(strw, 2*i + 2);
            }
        } else {

            int start = 2;
            if (b > w) {
                swap(b, w);
                start = 3;
            }

            ans ~= tuple(strw, start);
            w -= 1;

            int reach = 0;
            int cur = start+1;
            while (b > 0) {
                b -= 1;
                ans ~= tuple(strw, cur);
                cur += 1;

                w -= 1;
                ans ~= tuple(strw, cur);

                reach += 2;
            }

            if (reach < w) {
                writeln("NO");
                continue;
            }

            foreach (pos; cur.iota.drop(1 + start).stride(2)) {
                foreach (rw; [strw-1, strw+1]) {
                    if (w == 0) { break; }

                    ans ~= tuple(rw, pos);
                    w -= 1;
                }
            }
        }

        writeln("YES");
        ans.each!(t => writeln(t[0], ' ', t[1]));
    }
}


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

void main() {
    int n = readln.chomp.to!int;
    int[string] db;

    foreach (i; 0..n) {
        string name = readln.chomp;
        if (name in db) {
            writeln(name, db[name]);
            db[name]++;
        } else {
            db[name] = true;
            writeln("OK");
            db[name] = 1;
        }
    }
}

import std.stdio;
import core.stdc.stdio;

string readline()
{
	string result = readln();
	if (result[$-1] == '\n') result.length--;
	return result;
}

int main(string[] argv)
{
	int n;
	scanf("%d\n", &n);
	int[string] db;
	foreach (int i; 0..n)
	{
		string name = readline();
		if (name in db)
		{
			db[name]++; write(name, db[name], '\n');
		} else {
			write("OK\n");
			db[name] = 0;
		}
	}
	return 0;
}

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

void main()
{
  auto n = stdin.readln.strip.to!int;
  int [string] names;
  for(int i=0; i<n; i++) {
    auto name = stdin.readln.strip;
    if (name in names) {
      names[name]++;
      write(name);
      writeln(names[name]);
    } else {
      writeln("OK");
      names[name]=0;
    }
  }
 }

import std.stdio;
import core.stdc.stdio;

string readline()
{
	string result = readln();
	if (result[$-1] == '\n') result.length--;
	return result;
}

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int[string] db;
	foreach (int i; 0..n)
	{
		string name = readline();
		if (name in db)
		{
			db[name]++; write(name, db[name], '\n');
		} else {
			write("OK\n");
			db[name] = 0;
		}
	}
	return 0;
}

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

void main() {
    int n = readln.chomp.to!int;
    bool[string] db;

    foreach (i; 0..n) {
        string name = readln.chomp;
        if (name in db) {
            writeln(name ~ "1");
        } else {
            db[name] = true;
            writeln("OK");
        }
    }
}


void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan;

      auto pts = S.map!(c => (c - 'a' + 1).to!long).array;
      const a = S.length % 2 == 0 ? pts.sum : pts.sum - min(pts[0], pts[$ - 1]);
      const b = pts.sum - a;

      const winner = a > b ? "Alice" : "Bob";
      return "%s %s".format(winner, abs(a - b));
    }

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

  outputForAtCoder(&solve);
}

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

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

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

import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        string s = readln.strip;
        if (s.length == 1)
            writeln("Bob ", cast(int) s[0] - cast(int) 'a' + 1);
        else
        {
            if (s.length % 2 == 0)
                writeln("Alice ", s.map!(x => cast(int) x - cast(int) 'a' + 1).sum);
            else
            {
                if (cast(int) s[0] >= cast(int) s[$ - 1])
                    writeln("Alice ", s[0 .. $ -1].map!(x => cast(int) x - cast(int) 'a' + 1).sum - cast(int) s[$ - 1] - 1 + cast(int) 'a');
                else
                    writeln("Alice ", s[1 .. $].map!(x => cast(int) x - cast(int) 'a' + 1).sum - cast(int) s[0] - 1 + cast(int) 'a');
            }
        }
    }
}

void main() { runSolver(); }

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

  auto solve() {
    auto subSolve() {
      auto S = scan;

      auto pts = S.map!(c => (c - 'a' + 1).to!long).array.sort;
      const a = S.length % 2 == 0 ? pts.sum : pts[1..$].sum;
      const b = S.length % 2 == 0 ? 0 : pts[0..1].sum;

      const winner = a > b ? "Alice" : "Bob";
      return "%s %s".format(winner, abs(a - b));
    }

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

  outputForAtCoder(&solve);
}

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

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

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


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

immutable mod = 10^^9 + 7;

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

    auto dp = new int[][](n + 1, n + 2);
    dp[0][0] = 1;

    foreach (i ; 1 .. n + 1) {
        char c;
        scan(c);

        foreach_reverse (j ; 0 .. n + 1) {
            if (c == 'f') {
                if (j-1 >= 0) dp[i][j] = dp[i-1][j-1];
            }
            else {
                dp[i][j] = (dp[i-1][j] + dp[i][j+1]) % mod;
            }
        }
    }

    debug {
        writefln("%(%(%s %)\n%)", dp);
    }

    int ans;

    foreach (j ; 0 .. n + 1) {
        (ans += dp[n-1][j]) %= mod;
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

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

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

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

    char[] arr;
    foreach (_; 0 .. n) {
        arr ~= readln.chomp.front;
    }

    debug { arr.writeln; }

    auto dp = new int[][] (n+1, n+1);
    dp[1][0] = 1;
    foreach (i; 2 .. n+1) {
        int sm = 0;
        foreach_reverse (j; 0 .. n+1) {
            sm = (sm + dp[i-1][j]) % MD;
            if (arr[i-2] == 'f') {
                if (j > 0) { dp[i][j] = (dp[i][j] + dp[i-1][j-1]) % MD; }
            } else {
                dp[i][j] = (dp[i][j] + sm) % MD;
            }
        }
    }

    debug { dp.writeln; }

    auto ans = dp[n].fold!((r, v) => (r + v) % MD)(0);
    ans.writeln;
}

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

immutable mod = 10^^9 + 7;

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

    auto dp = new int[][](n + 1, n + 1);
    dp[0][0] = 1;

    auto s = new int[](n + 1);
    s[0] = 1;

    foreach (i ; 1 .. n + 1) {
        char c;
        scan(c);

        if (c == 's') {
            foreach (j ; 0 .. n + 1) {
                dp[i][j] += s[j];
            }
        }
        else {
            foreach (j ; 0 .. n + 1) {
                if (j-1 >= 0) (dp[i][j] += dp[i-1][j-1]) %= mod;
            }
        }

        s[] = dp[i].dup;
        foreach_reverse (j ; 0 .. n) {
            (s[j] += s[j+1]) %= mod;
        }
    }

    int ans;

    foreach (j ; 0 .. n + 1) {
        (ans += dp[n-1][j]) %= mod;
    }

    debug {
        iota(n+1).each!(i => writeln(dp[i][0 .. 10]));
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    enum spec = ' ' ~ replicate("%s ", vars.length);
    return readf(spec, getAddrTuple(vars).expand) == vars.length;
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

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

enum mod = 10^^9 + 7;

int n;
char[5000] prog;
int[5001][ ] dp;

int dyn(int pos, int level, bool canDedent) {
    if (pos == n)
        return 1;
    if (~dp[pos][level])
        return dp[pos][level];
    const isLoop = prog[pos] == 'f';
    int result = dyn(pos + 1, level + isLoop, !isLoop);
    if (level && canDedent)
        result = (result + dyn(pos, level - 1, canDedent)) % mod;
    return (dp[pos][level] = result);
}

void main() {
    dp = uninitializedArray!(int[5001][ ])(5000);
    while (read(n)) {
        prog[0 .. n].each!read();
        memSet(dp, 0xFF);
        writeln(dyn(0, 0, false));
    }

    stdout.flush();
    _Exit(0);
}

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    enum spec = ' ' ~ replicate("%s ", vars.length);
    return readf(spec, getAddrTuple(vars).expand) == vars.length;
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

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

enum mod = 10^^9 + 7;

int n;
char[5000] prog;
int[5001][ ] dp;

int dyn(int first, int last) {
    if (first == last)
        return 1;
    if (~dp[first][last])
        return dp[first][last];
    int result = 0;
    if (prog[first] == 's')
        result = dyn(first + 1, last);
    else
        foreach (end; first + 1 .. last)
            if (prog[end] == 's')
                result = (result + dyn(first + 1, end + 1) * dyn(end + 1, last)) % mod;
    return (dp[first][last] = result);
}

void main() {
    dp = uninitializedArray!(int[5001][ ])(5000);
    while (read(n)) {
        prog[0 .. n].each!read();
        memSet(dp, 0xFF);
        writeln(dyn(0, n));
    }

    stdout.flush();
    _Exit(0);
}

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

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

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

    char[] arr;
    foreach (_; 0 .. n) {
        arr ~= readln.chomp.front;
    }

    debug { arr.writeln; }

    auto dp = new int[][] (n+1, n+1);
    dp[1][0] = 1;
    foreach (i; 2 .. n+1) {
        foreach (j; 0 .. n+1) {
            if (arr[i-2] == 'f') {
                if (j > 0) { dp[i][j] = (dp[i][j] + dp[i-1][j-1]) % MD; }
            } else {
                dp[i][j] = (dp[i][j] + dp[i-1][j]) % MD;
                if (j > 0) { dp[i][j-1] = (dp[i][j-1] + dp[i-1][j]) % MD; }
            }
        }
    }

    debug { dp.writeln; }

    auto ans = dp[n].fold!((r, v) => (r + v) % MD)(0);
    ans.writeln;
}

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

immutable mod = 10^^9 + 7;

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

    auto dp = new int[][](n + 1, 5000 + 1);
    dp[0][0] = 1;

    foreach (i ; 0 .. n) {
        char c;
        scan(c);

        if (c == 's') {
            foreach (j ; 0 .. 5000 + 1) {
                if (j-1 >= 0) (dp[i+1][j-1] += dp[i][j]) %= mod;
                (dp[i+1][j] += dp[i][j]) %= mod;
            }
        }
        else {
            foreach (j ; 0 .. 5000 + 1) {
                if (j+1 <= 5000) (dp[i+1][j+1] += dp[i][j]) %= mod;
            }
        }
    }

    int ans;

    foreach (j ; 0 .. 5000 + 1) {
        (ans += dp[n-1][j]) %= mod;
    }

    debug {
        iota(n+1).each!(i => writeln(dp[i][0 .. 10]));
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


module _;
void main() {
	import std.stdio, std.conv, std.string;
	int n =readln.strip.to!int;
	int[char] cnt;
	foreach(i; 0..n) {
		cnt[readln[0]]++;
	}
	int ans = 0;
	foreach(k; cnt.byKey) {
		ans += cnt[k]*(cnt[k]-1)/2;
		int half = cnt[k]/2;
		ans -= half * (cnt[k]-half);
	}
	writeln(ans);
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		int [char] s;
		foreach (i; 0..n)
		{
			auto t = readln.strip;
			s[t[0]] += 1;
		}
		int res = 0;
		foreach (k, v; s)
		{
			int a = v / 2;
			int b = v - a;
			res += a * (a - 1) / 2;
			res += b * (b - 1) / 2;
		}
		writeln (res);
	}
}

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

int f (int x) {
  return (x * (x - 1) ) / 2;
}

void main() {
  int n = readln.strip.to!int;
  int[26] c;
  foreach (i; 0 .. n) {
    auto s = readln;
    ++c[s[0].to!int - 97];
  }
  int res;
  foreach (i; 0 .. 26) {
    int m = c[i] >> 1;
    res += f (m) + f (c[i] - m);
  }
  writeln (res);
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string ;
import std.math: abs ;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!long;

void main() {
  GC.disable();

  int n;
  readf(" %s\n", n);
  int[26] counter;
  counter[] = 0;
  foreach(i; 0..n) {
    string s  = readln().strip;
      counter[ s[0] - 'a' ] ++;
  }

  int total = 0;
  foreach(i; 0..26) {
    int c = counter[i];
    int c1 = c/2;
    int c2= c - c1;
    total += c1 * (c1-1)/2 + c2*(c2-1)/2;
  }

  writeln(total);

}

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

string FMT_F = "%.10f";

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; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
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; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * y / gcd(x, y); }

//long mod = 10^^9 + 7;
long mod = 998244353;
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 main()
{
	auto N = RD!int;
	auto cnt = new long[](30);
	foreach (i; 0..N)
	{
		auto s = RD!string;
		++cnt[s[0]-'a'];
	}

	long ans;
	foreach (e; cnt)
	{
		auto x = (e+1) / 2;
		auto y = e / 2;
		ans += x * (x-1) / 2;
		ans += y * (y-1) / 2;
	}

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

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

string FMT_F = "%.10f";

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; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
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; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * y / gcd(x, y); }

//long mod = 10^^9 + 7;
long mod = 998244353;
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 main()
{
	auto N = RD!int;
	auto cnt = new long[](30);
	foreach (i; 0..N)
	{
		auto s = RD!string;
		++cnt[s[0]-'a'];
	}
	cnt.sort!"a > b"();
	auto x = (cnt[0]+1) / 2;
	auto y = cnt[0] / 2;
	long ans;
	ans += x * (x-1) / 2;
	ans += y * (y-1) / 2;

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


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

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(long)).array;
		long [] s;
		s ~= 0;
		foreach (c; a)
		{
			s ~= s.back + c;
		}
		auto r = s.assumeSorted ();

		auto b = readln.splitter.map !(to !(long)).array;
		foreach (x; b)
		{
			auto p = r.lowerBound (x);
			auto pos = p.length;
			writeln (pos, " ", x - p.back);
		}
	}
}

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

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

  auto dub=new long[](n+1);
  foreach(i; 0..n) dub[i+1]=dub[i]+as[i];
  dub~=1_000_000_000_000_000_000;
  int x=0;
  foreach(b; bs){
    while(dub[x+1]<b) x++;
    // dub[x] < b <= dub[x+1]
    writeln(x+1, " ", b-dub[x]);
  }
}

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.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		if ((x+y) % 2)
			ans[ti] = [-1, -1];
		else
		{
			auto a = min(x, (x+y)/2);
			ans[ti] = [a, (x+y)/2 - a];
		}
	}

	foreach (e; ans)
		writeln(e[0], " ", e[1]);
	stdout.flush;
	debug readln;
}

immutable multi = true;

void solve(int tc)
{
	auto x = readInt!int;
	auto y = readInt!int;
	int dist(int x0, int y0, int x1, int y1)
	{
		return abs(x1 - x0) + abs(y1 - y0);
	}
	auto hs = (x + y) / 2;
	if (hs*2 != x + y) return writeln(-1, " ", -1);
	// ox + oy = hs
	// oy = hs - ox
	foreach(ox; 0 .. x + 1)
	{
		auto oy = hs - ox;
		if (dist(x, y, ox, oy) == hs) return writeln(ox, " ", oy);
	}
	return writeln(-1, " ", -1);
}

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

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

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

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

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


void main() { runSolver(); }

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

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

      int[long] numCounts;
      foreach(a; A.sort.reverse) {
        if((a * X) in numCounts) {
          numCounts[a * X]--;
          if (numCounts[a * X] == 0) numCounts.remove(a * X);
        }
        else numCounts[a]++;
      }

      return numCounts.values.sum;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		long[long] cnt;
		foreach (i; 0..n)
			++cnt[a[i]];

		foreach (key; cnt.keys.sort)
		{
			auto y = key * x;
			auto z = min(cnt.get(y, 0), cnt[key]);
			cnt[key] -= z;
			cnt[y] -= z;
			ans[ti] += cnt[key];
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, x;
		readf !(" %s %s") (n, x);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		int j = 0;
		int res = 0;
		foreach (i; 0..n)
		{
			if (a[i] == 0)
			{
				continue;
			}
			while (j < n && a[j] < a[i] * 1L * x)
			{
				j += 1;
			}
			if (j < n && a[j] == a[i] * 1L * x)
			{
				a[j] = 0;
			}
			else
			{
				res += 1;
			}
		}
		writeln (res);
	}
}

void main() { runSolver(); }

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

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

      int[long] numCounts;
      foreach(a; A) {
        if (a % X == 0 && ((a / X) in numCounts)) {
          numCounts[a / X]--;
          if (numCounts[a / X] == 0) numCounts.remove(a / X);
        }
        else if((a * X) in numCounts) {
          numCounts[a * X]--;
          if (numCounts[a * X] == 0) numCounts.remove(a * X);
        }
        else numCounts[a]++;
      }

      return numCounts.values.sum;
    }

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

  outputForAtCoder(&solve);
}

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

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

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


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

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

void solve() {
    int N = read!int;
    auto B = readarray!int;

    int k_lb = 0, k_ub = N + 1;
    for (int x = 1; x <= N; x++) {
        int i = x - 1;
        int b = B[i];
        if (x < b) {
            k_lb = max(k_lb, x);
            k_ub = min(k_ub, b - 1);
        } else if (x > b) {
            k_lb = max(k_lb, b);
            k_ub = min(k_ub, x - 1);
        } else {
            assert(false);
        }
    }

    int k = k_lb;
    Array!int L, U;
    auto G = new int[][N+2];
    for (int x = 1; x <= N; x++) {
        int i = x - 1;
        int b = B[i];
        if (x <= k) {
            G[b] ~= x;
        } else {
            G[b] ~= x;
        }
    }

    foreach (c; 0 .. N + 2) {
        G[c].sort!((i, j) => G[i].length < G[j].length);
    }

    int[] as;
    DList!int Q;
    if (! G[0].empty) { Q.insert(0); }
    else if (! G[N+1].empty) { Q.insert(N+1); }
    else assert(false);
    while (! Q.empty) {
        auto c = Q.front; Q.removeFront;
        as ~= c;
        foreach (v; G[c]) {
            Q.insert(v);
        }
    }

    writeln(k);
    writefln("%(%s %)", as[1..$]);
}

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

immutable int NA = -1;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto b = readln.splitter.map !(to !(int)).array;
		auto s = new int [] [n + 2];
		foreach (int i, ref c; b)
		{
			s[c] ~= i + 1;
		}

		int [] a;
		int cur = 0;
		bool up = false;
		int k = 0;
		if (s[cur].empty)
		{
			cur = n + 1;
			up = true;
		}

		while (true)
		{
			int next = NA;
			foreach (v; s[cur])
			{
				if (up)
				{
					k = max (k, v);
				}
				if (!s[v].empty)
				{
					next = v;
				}
			}

			foreach (v; s[cur])
			{
				if (v != next)
				{
					a ~= v;
				}
			}
			s[cur] = null;
			if (next == NA)
			{
				break;
			}
			a ~= next;

			up ^= true;
			cur = next;
		}

		writeln (k);
		writefln !("%(%s %)") (a.map !(q{a}));
	}
}

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

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

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

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

int N;
int[] B;
int K;
int[] A;

void solve() {
  auto minL = new int[N + 1];
  auto maxR = new int[N + 1];
  minL[0] = N + 2;
  foreach (i; 0 .. N) {
    minL[i + 1] = min(minL[i], B[i]);
  }
  maxR[N] = -1;
  foreach_reverse (i; 0 .. N) {
    maxR[i] = max(B[i], maxR[i + 1]);
  }
  {
    int[] ks;
    foreach (k; 0 .. N + 1) {
      if (minL[k] > k && k >= maxR[k]) {
        ks ~= k;
      }
    }
    debug {
      writeln("ks = ", ks);
    }
    assert(ks.length == 1);
    K = ks[0];
  }

  auto graph = new int[][N + 2];
  foreach (i; 0 .. N) {
    graph[B[i]] ~= i + 1;
  }
  auto us = [0, N + 1];
  for (int j = 0; j < us.length; ++j) {
    graph[us[j]].sort!((v, w) => (graph[v].length < graph[w].length));
    foreach (v; graph[us[j]]) {
      us ~= v;
    }
  }
  assert(us.length == N + 2);
  A = us[2 .. $];
}

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

        solve;

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

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

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

void solve() {
    int N = read!int;
    auto B = readarray!int;

    int k_lb = 0, k_ub = N + 1;
    for (int x = 1; x <= N; x++) {
        int i = x - 1;
        int b = B[i];
        if (x < b) {
            k_lb = max(k_lb, x);
            k_ub = min(k_ub, b - 1);
        } else if (x > b) {
            k_lb = max(k_lb, b);
            k_ub = min(k_ub, x - 1);
        } else {
            assert(false);
        }
    }

    int k = k_lb;
    Array!int L, U;
    auto G = new int[][N+2];
    for (int x = 1; x <= N; x++) {
        int i = x - 1;
        int b = B[i];
        if (x <= k) {
            G[b] ~= x;
        } else {
            G[b] ~= x;
        }
    }

    foreach (c; 0 .. N + 1) {
        G[c].sort!((i, j) => G[i].length < G[j].length);
    }

    int[] as;
    DList!int Q;
    if (! G[0].empty) { Q.insert(0); }
    else if (! G[N+1].empty) { Q.insert(N+1); }
    else assert(false);
    while (! Q.empty) {
        auto c = Q.front; Q.removeFront;
        as ~= c;
        foreach (v; G[c]) {
            Q.insert(v);
        }
    }

    writeln(k);
    writefln("%(%s %)", as[1..$]);
}

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

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

void solve() {
    int N = read!int;
    auto B = readarray!int;

    int k_lb = 0, k_ub = N + 1;
    for (int x = 1; x <= N; x++) {
        int i = x - 1;
        int b = B[i];
        if (x < b) {
            k_lb = max(k_lb, x);
            k_ub = min(k_ub, b - 1);
        } else if (x > b) {
            k_lb = max(k_lb, b);
            k_ub = min(k_ub, x - 1);
        } else {
            assert(false);
        }
    }

    int k = k_lb;
    Array!int L, U;
    auto G = new int[][N+2];
    for (int x = 1; x <= N; x++) {
        int i = x - 1;
        int b = B[i];
        if (x <= k) {
            G[b] ~= x;
        } else {
            G[b] ~= x;
        }
    }

    int[] as;
    DList!int Q;
    if (! G[0].empty) { Q.insert(0); }
    else if (! G[N+1].empty) { Q.insert(N+1); }
    else assert(false);
    while (! Q.empty) {
        auto c = Q.front; Q.removeFront;
        as ~= c;
        foreach (v; G[c]) {
            Q.insert(v);
        }
    }

    writeln(k);
    writefln("%(%s %)", as[1..$]);
}

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

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

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

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

int N;
int[] B;
int K;
int[] A;

void solve() {
  auto minL = new int[N + 1];
  auto maxR = new int[N + 1];
  minL[0] = N + 2;
  foreach (i; 0 .. N) {
    minL[i + 1] = min(minL[i], B[i]);
  }
  maxR[N] = -1;
  foreach_reverse (i; 0 .. N) {
    maxR[i] = max(B[i], maxR[i + 1]);
  }
  {
    int[] ks;
    foreach (k; 0 .. N + 1) {
      if (minL[k] > k && k >= maxR[k]) {
        ks ~= k;
      }
    }
    debug {
      writeln("ks = ", ks);
    }
    assert(ks.length == 1);
    K = ks[0];
  }

  auto graph = new int[][N + 2];
  foreach (i; 0 .. N) {
    graph[B[i]] ~= i + 1;
  }
  auto us = [0, N + 1];
  for (int j = 0; j < us.length; ++j) {
    foreach (v; graph[us[j]]) {
      us ~= v;
    }
  }
  assert(us.length == N + 2);
  A = us[2 .. $];
}

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

        solve;

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