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 root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

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

        long ans = 1L * (N - 2) * (N - 3) / 2;

        int[] doIt(int s) {
          auto uf = new int[N];
          uf[] = -1;
          foreach (i; 0 .. M) {
            if (U[i] != s && V[i] != s) {
              uf.connect(U[i], V[i]);
            }
          }
          foreach (u; 0 .. N) {
            if (uf[u] < 0) {
              long sz = -uf[u];
              if (u == uf.root(A)) --sz;
              if (u == uf.root(B)) --sz;
              ans -= sz * (sz - 1) / 2;
            }
          }
          return uf;
        }

        auto ufA = doIt(A);
        auto ufB = doIt(B);
        Tuple!(int, int)[] ts;
        foreach (u; 0 .. N) {
          if (u != A && u != B) {
            ts ~= tuple(ufA.root(u), ufB.root(u));
          }
        }
        ts.sort;
        foreach (grp; ts.group) {
          long sz = grp[1];
          ans += sz * (sz - 1) / 2;
        }
        writeln(ans);
      }
    }
  } 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 t;
    readf("%s", &t);
    readln;

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

        auto g = new int[][] (n+1);
        foreach (_; 0 .. m) {
            int u, v;
            readf("%s %s", &u, &v);
            readln;

            g[u] ~= v;
            g[v] ~= u;
        }

        auto mark = new bool[][] (2, n+1);
        foreach (i; 0 .. 2) { mark[i][] = false; }

        void dfs(int v, int p, int bad) {
            mark[p][v] = true;
            if (v == bad) { return; }

            foreach (u; g[v]) {
                if (mark[p][u]) { continue; }

                dfs(u, p, bad);
            }
        }

        dfs(a, 0, b);
        dfs(b, 1, a);

        debug { mark.each!writeln; }

        auto ans = mark[0].dropOne.count!(p => !p).to!long
            * mark[1].dropOne.count!(p => !p);

        ans.writeln;
    }
}

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

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  debug scope(exit) inputFile.close;
  auto nt = next!int;
  foreach(tc; 0 .. nt)
    {
      auto n = next!int;
      auto m = next!int;
      auto a = next!int - 1;
      auto b = next!int - 1;
      auto nei = new int[][](n);
      foreach(e; 0 .. m)
        {
          auto u = next!int - 1;
          auto v = next!int - 1;
          nei[u] ~= v;
          nei[v] ~= u;
        }
      auto visited = new bool[](n);
      visited[] = false;
      auto size = new int[](n);
      size[] = 0;
      int searched = -1;
      int searchedAncestor = -1;
      void dfs(int nd, int bigAncestor, bool isRoot)
      {
        visited[nd] = true;
        size[nd] = 1;
        if (nd == searched)
          {
            searchedAncestor = bigAncestor;
          }
        if (isRoot)
          {
            foreach(ne; nei[nd])
              if (!visited[ne])
                {
                  dfs(ne, ne, false);
                  size[nd] += size[ne];
                }
          }
        else
          {
            foreach(ne; nei[nd])
              if (!visited[ne])
                {
                  dfs(ne, bigAncestor, false);
                  size[nd] += size[ne];
                }
          }
      }

      searched = b;
      dfs(a, -1, true);
      auto winga = size[a] - size[searchedAncestor] - 1;
      visited[] = false;
      size[] = 0;
      searched = a;
      dfs(b, -1, true);
      auto wingb = size[b] - size[searchedAncestor] - 1;
      writeln(cast(long) winga * cast(long) wingb);
    }
}

// INPUT

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

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

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

import std.stdio;
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]);
  debug scope(exit) inputFile.close;
  bool[200_000] visitedPool;
  int[200_000] sizePool;
  auto nt = next!int;
  foreach(tc; 0 .. nt)
    {
      auto n = next!int;
      auto m = next!int;
      auto a = next!int - 1;
      auto b = next!int - 1;
      auto nei = new int[][](n);
      foreach(e; 0 .. m)
        {
          auto u = next!int - 1;
          auto v = next!int - 1;
          nei[u] ~= v;
          nei[v] ~= u;
        }
      auto visited = visitedPool[0 .. n];
      visited[] = false;
      auto size = sizePool[0 .. n];
      size[] = 0;
      int searched = -1;
      int searchedAncestor = -1;
      void dfs(int nd, int bigAncestor, bool isRoot)
      {
        visited[nd] = true;
        size[nd] = 1;
        if (nd == searched)
          {
            searchedAncestor = bigAncestor;
          }
        if (isRoot)
          {
            foreach(ne; nei[nd])
              if (!visited[ne])
                {
                  dfs(ne, ne, false);
                  size[nd] += size[ne];
                }
          }
        else
          {
            foreach(ne; nei[nd])
              if (!visited[ne])
                {
                  dfs(ne, bigAncestor, false);
                  size[nd] += size[ne];
                }
          }
      }

      searched = b;
      dfs(a, -1, true);
      auto winga = size[a] - size[searchedAncestor] - 1;
      visited[] = false;
      size[] = 0;
      searched = a;
      dfs(b, -1, true);
      auto wingb = size[b] - size[searchedAncestor] - 1;
      writeln(cast(long) winga * cast(long) wingb);
    }
}

// INPUT

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

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

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


import std;

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

class BudgetStack (T, size_t N) {
public:
    const @property size_t length () { return _k; }
    alias opDollar = length;

    inout ref inout(T) opIndex (size_t i) { return _data[i]; }

    auto opSlice (size_t a, size_t b) { return _data[a .. b]; }
    auto opSlice () { return _data[0 .. _k]; }

    BudgetStack opOpAssign (string op: "~") (T val) {
        _data[_k ++] = val;
        return this;
    }
    alias pushBack = opOpAssign!("~");

    void removeBack () { -- _k; }

    const @property empty () { return _k == 0; }
private:
    T[N] _data;
    size_t _k;
}

void main () {
    immutable tests = read!(uint, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        readln;

        immutable v = readln
            .chomp
            .splitter(' ')
            .map!(to!uint)
            .array;

        class MexSuffixes {
        public:
            this () {
                uint[] result = new uint[v.length];

                bool[uint] seenSoFar;
                uint mex = 0;
                foreach (i, val; v.retro.enumerate) {
                    seenSoFar[val] = true;

                    while (mex in seenSoFar)
                        ++ mex;

                    result[$ - 1 - i] = mex;
                }

                _data = result;
            }

            alias _data this;
        private:
            uint[] _data;
        }

        const mexSuffixes = new MexSuffixes();

        size_t[] result;
        for (size_t p = 0; p < v.length ;) {
            immutable stop = mexSuffixes[p];

            //stderr.writeln("Am at position:", p);

            bool[uint] seenSoFar;
            uint mex = 0;
            for (size_t i = p; i < v.length; ++ i) {
                seenSoFar[v[i]] = true;

                while (mex in seenSoFar)
                    ++ mex;

                if (mex == stop) {
                    p = i + 1;
                    result ~= stop;
                    break;
                }
            }
        }

        writefln!"%s\n%(%s %)"(result.length, result);
    }
}

// ""

void main() { runSolver(); }

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

  auto solve() {
    enum int MAX = 2 * 10^^5 + 1;

    auto subSolve() {
      auto N = scan!int;
      auto A = scan!int(N);
      auto indeciesRaw = new int[][](N + 1, 0);
      foreach(i, a; A) {
        indeciesRaw[a] ~= cast(int)i;
      }
      auto indecies = indeciesRaw.map!assumeSorted.array;

      int[] ans;
      int l = 0;
      while(l < N) {
        // [l].deb;
        int mex;
        int offset;
        foreach(n; 0..MAX) {
          if (indecies[n].empty) break;

          auto u = indecies[n].upperBound(l - 1);
          if (u.empty) break;

          mex = n + 1;
          offset = max(offset, u.front);
          // [n, offset].deb;
        }

        l = max(offset, l) + 1;
        ans ~= mex;
        // [mex, l].deb;
      }

      ans.length.writeln;
      ans.toAnswerString.writeln;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

bool[] enumeratePrimes(int max)
{
  auto primes = new bool[](max + 1);
  primes[] = true;
  primes[0] = false;
  primes[1] = false;
  foreach (i; 2..max+1) {
    if (primes[i]) {
      auto x = i*2;
      while (x <= max) {
        primes[x] = false;
        x += i;
      }
    }
  }

  return primes;
}

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

void solve(){
    auto n = scan!int;
    auto arr = scanArray!int;
    auto imap = new int[][](n+2);

    for(int i = n-1; i >= 0; --i){
        imap[arr[i]] ~= i;
    }
    show(imap);
    int[] res;

    int lastix = 0;
    while(lastix < n && imap[0].length){
        int nextix = 0;
        for(int k = 0; k <= n+1; ++k){
            if(!imap[k].length){
                res ~= k;
                break;
            }
            nextix = max(imap[k].back, nextix);
        }
        assert(nextix >= lastix);
        for(int i = lastix; i <= nextix; ++i){
            imap[arr[i]].popBack;
        }
        lastix = nextix + 1;
    }
    for(int i = lastix; i < n; ++i){
        res ~= 0;
    }
    writeln(res.length);
    res.each!(a => write(a, " "));
    writeln;
}

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

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

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

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

		void rem ()
		{
			pos[a.front] -= 1;
			a.popFront ();
		}

		int [] answer;
		while (!a.empty)
		{
			int cur = 0;
			while (pos[cur] > 0)
			{
				cur += 1;
			}
			answer ~= cur;

			if (cur == 0)
			{
				rem ();
			}
			else
			{
				auto vis = new bool [cur];
				vis[] = true;
				int total = cur;
				while (total > 0)
				{
					auto x = a.front;
					if (x < cur)
					{
						total -= vis[a.front];
						vis[a.front] = false;
					}
					rem ();
				}
			}
		}

		writeln (answer.length);
		writefln !("%(%s %)") (answer);
	}
}

import std;

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

class BudgetStack (T, size_t maxSize) {
public:
    ref inout(T) opIndex (size_t i) inout { return _data[i]; }

    const @property length () { return _k; }
    alias opDollar = length;

    BudgetStack push (T a) { _data[_k ++] = a; return this; }
    alias opOpAssign (string s: "~") = push;

    void pop () { -- _k; }

    T front () { return _data[0]; }
    T back () { return _data[_k - 1]; }

    bool empty () const { return _k == 0; }

    T[] opSlice () { return _data[0 .. _k]; }
    T[] opSlice (size_t i, size_t j) { return _data[i .. j]; }
private:
    T[maxSize] _data;
    size_t _k;
}

void main () {
    immutable tests = read!(uint, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        readln();

        immutable vec = readln().chomp
            .splitter(' ')
            .map!(to!uint)
            .array;

        alias GroupT = Tuple!(uint[uint], "freq", uint, "mex");

        GroupT[] groups;
        { // Building the array as groups of MEX given sequences
            immutable combine = (ref uint[uint] frec_l, in uint[uint] frec_r) {
                foreach (k, v; frec_r)
                    frec_l[k] += v;
            };

            uint[uint][] range = (){
                static assert(true);
                auto result = new BudgetStack!(uint[uint], 200_000);

                foreach (val; vec) {
                    while (result.length >= 2 && val !in result[$ - 1] && val !in result[$ - 2]) {
                        combine(result[$ - 2], result[$ - 1]);
                        result.pop();
                    }

                    if (result.empty())
                        result.push([val: 1]);
                    else {
                        if (val in result.back())
                            result.push([val: 1]);
                        else
                            result.back()[val] += 1;
                    }

                }

                return result[];
            }();

            groups = range
                .map!(freq => GroupT(freq, MEX(freq)))
                .array;
        }

        uint ctz;
        { // Count how many values we can cut from the end of the vector
            auto input = vec.retro;

            bool removingWouldBreakMex (in GroupT g, in uint val) {
                return g.mex > val && g.freq[val] == 1;
            }

            void removeFromFreq (ref GroupT g, in uint val) {
                if (g.freq[val] == 1)
                    g.freq.remove(val);
                else
                    g.freq[val] -= 1;
            }

            ref GroupT firstWhichContains (GroupT[] g, in uint val) {
                return g.retro.find!(t => val in t.freq).front;
            }

            uint count (in GroupT g) {
                return g.freq.byValue.sum;
            }

            foreach (val; input) {
                auto g = firstWhichContains(groups, val);
                if (removingWouldBreakMex(g, val))
                    break;
                ++ ctz;
                removeFromFreq(g, val);
            }

            while (!groups.empty && groups.back.mex == 0) {
                ctz += count(groups.back);
                groups.popBack();
            }
        }

        immutable length = groups.length + ctz;
        writeln(length);

        chain(
            groups.map!"a.mex",
            0u.repeat(ctz)
        ).writefln!"%(%s %)";
    }
}

uint MEX (in uint[uint] freq) {
    return iota(uint.min, uint.max)
        .find!(val => val !in freq)
        .front;
}
// ""

import std;

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

class BudgetStack (T, size_t N) {
public:
    const @property size_t length () { return _k; }
    alias opDollar = length;

    inout ref inout(T) opIndex (size_t i) { return _data[i]; }

    auto opSlice (size_t a, size_t b) { return _data[a .. b]; }
    auto opSlice () { return _data[0 .. _k]; }

    BudgetStack opOpAssign (string op: "~") (T val) {
        _data[_k ++] = val;
        return this;
    }
    alias insertBack = opOpAssign!("~");

    void removeBack () { -- _k; }

    const @property empty () { return _k == 0; }
private:
    T[N] _data;
    size_t _k;
}

void main () {
    immutable tests = read!(uint, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        readln;

        immutable v = readln
            .chomp
            .splitter(' ')
            .map!(to!uint)
            .array;

        auto ans = new BudgetStack!(uint[uint], 200_000);

        foreach (val; v) {
            while (ans.length >= 2 && val !in ans[$ - 1] && val !in ans[$ - 2]) {
                reduce(ans[$ - 2], ans[$ - 1]);
                ans.removeBack();
            }

            if (ans.empty()) {
                ans ~= [val: 1u];
                continue;
            }

            if (val in ans[$ - 1])
                ans ~= [val: 1u];
            else
                ans[$ - 1][val] += 1;

        }

        assert(ans.length > 0);
        if (0 in ans[$ - 1]) {
            writeln(ans.length);
            writefln!"%(%s %)"(ans[].map!MEX);
        } else {
            immutable last_size = ans[$ - 1].countNumbers;
            ans.removeBack();

            writeln(ans.length + last_size);
            chain(ans[].map!MEX, 0u.repeat(last_size))
                .writefln!"%(%s %)";
        }
    }
}
// ""

void reduce (ref uint[uint] lhs, in uint[uint] rhs) {
    foreach (k, v; rhs)
        lhs[k] += v;
}

uint MEX (in uint[uint] freq) {
    return iota(0, uint.max)
        .filter!(num => num !in freq)
        .front;
}

uint countNumbers (in uint[uint] freq) {
    return freq.byValue.sum;
}

import std;

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

void main () {
    immutable tests = read!(uint, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        readln();

        immutable uint[] v =
            readln.chomp
            .splitter(' ')
            .map!(to!uint)
            .array;

        bool[uint][200_000] ans;
        size_t k;

        foreach (val; v) {
            while (k >= 2 && val !in ans[k - 1] && val !in ans[k - 2]) {
                -- k;
            }

            if (k == 0)
                ans[k ++] = [val: true];
            else {
                if (val in ans[k - 1])
                    ans[k ++] = [val: true];
                else
                    ans[k - 1][val] = true;
            }
        }

        writeln(k);
        writefln!"%(%s %)"(ans[0 .. k].map!MEX);
    }
}
// ""

uint
MEX (in bool[uint] aa) {
    return iota(uint.min, uint.max)
        .filter!(a => a !in aa)
        .front;
}

void main() { runSolver(); }

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

  auto solve() {
    auto isPrime = enumeratePrimes(200_000);
    auto primes = (100_001).iota.filter!(i => isPrime[i]).array;
    auto others = primes.filter!(p => isPrime[2 + p]).array;

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

      auto maximums = new int[](N);
      int tMax;
      foreach_reverse(int i, a; A) {
        tMax = max(tMax, a);
        maximums[i] = tMax;
      }
      // maximums.deb;

      int[] ans;
      int l;
      int shift;
      while(l < N) {
        const maxi = maximums[l];
        auto used = new bool[](maxi + 2);
        int c = 0;

        // maxi.deb;
        foreach(int i, a; A[l..$]) {
          if (used[a]) continue;

          used[a] = true;
          if (c == a) {
            shift = i;
            while(used[c]) c++;
          }
          if (c == maxi + 1) {
            ans ~= c;
            break;
          }
        }

        if (c < maxi + 1) {
          ans ~= c;
        }
        l += shift + 1;
      }

      ans.length.writeln;
      ans.toAnswerString.writeln;
    }

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

  outputForAtCoder(&solve);
}

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

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

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

bool[] enumeratePrimes(int max)
{
  auto primes = new bool[](max + 1);
  primes[] = true;
  primes[0] = false;
  primes[1] = false;
  foreach (i; 2..max+1) {
    if (primes[i]) {
      auto x = i*2;
      while (x <= max) {
        primes[x] = false;
        x += i;
      }
    }
  }

  return primes;
}


import std.algorithm;
import std.format;
import std.stdio;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			scanf (" %d", &a[i]);
		}
		int t;
		scanf (" %d", &t);
		auto r = new int [t];
		auto b = new bool [n];
		foreach (i; 0..t)
		{
			scanf (" %d", &r[i]);
			r[i]--;
			b[r[i]] = true;
		}
		reverse (a);
		reverse (b);
		auto s = new int [n + 1];
		int pos = 0;
		bool ok = true;
		foreach (i; 0..n)
		{
			if (b[i] || (s[pos] != a[i]))
			{
				pos++;
				s[pos] = a[i];
				a[i] = -a[i];
			}
			else if (s[pos] == a[i])
			{
				pos--;
			}
			else
			{
				ok = false;
				break;
			}
		}
		ok &= (pos == 0);
		writefln ("%s", ok ? "YES" : "NO");
		if (ok)
		{
			reverse (a);
			writefln ("%(%s %)", a);
		}
	}
}

import std.algorithm;
import std.format;
import std.stdio;

void main ()
{
	int n;
	while (scanf (" %d", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			scanf (" %d", &a[i]);
		}
		int t;
		scanf (" %d", &t);
		auto r = new int [t];
		auto b = new bool [n];
		foreach (i; 0..t)
		{
			scanf (" %d", &r[i]);
			r[i]--;
			b[r[i]] = true;
		}
		reverse (a);
		reverse (b);
		auto s = new int [n + 1];
		int pos = 0;
		bool ok = true;
		foreach (i; 0..n)
		{
			if (b[i] || (s[pos] != a[i]))
			{
				pos++;
				s[pos] = a[i];
				a[i] = -a[i];
			}
			else if (s[pos] == a[i])
			{
				pos--;
			}
			else
			{
				ok = false;
				break;
			}
		}
		ok &= (pos == 0);
		writefln ("%s", ok ? "YES" : "NO");
		if (ok)
		{
			reverse (a);
			foreach (i; 0..n)
			{
				printf ("%d%c", a[i], i + 1 < n ? ' ' : '\n');
			}
		}
	}
}

import std.algorithm;
import std.format;
import std.stdio;

int [] read_array (int n)
{
	auto res = new int [n];
	auto rs = readln ();
	rs ~= ' ';
	foreach (i; 0..n)
	{
		while (rs[0] < '0')
		{
			rs = rs[1..$];
		}
		while (rs[0] >= '0')
		{
			res[i] = res[i] * 10 + (rs[0] - '0');
			rs = rs[1..$];
		}
	}
	return res;
}

void main ()
{
	int n;
	while (scanf (" %d ", &n) > 0)
	{
		auto a = read_array (n);
		int t;
		scanf (" %d", &t);
		auto r = read_array (t);
		auto b = new bool [n];
		foreach (i; 0..t)
		{
			r[i]--;
			b[r[i]] = true;
		}
		reverse (a);
		reverse (b);
		auto s = new int [n + 1];
		int pos = 0;
		bool ok = true;
		foreach (i; 0..n)
		{
			if (b[i] || (s[pos] != a[i]))
			{
				pos++;
				s[pos] = a[i];
				a[i] = -a[i];
			}
			else if (s[pos] == a[i])
			{
				pos--;
			}
			else
			{
				ok = false;
				break;
			}
		}
		ok &= (pos == 0);
		writefln ("%s", ok ? "YES" : "NO");
		if (ok)
		{
			reverse (a);
			foreach (i; 0..n)
			{
				printf ("%d%c", a[i], i + 1 < n ? ' ' : '\n');
			}
		}
	}
}

import core.memory;
import std.algorithm;
import std.container;
import std.exception;
import std.format;
import std.math;
import std.stdio;
import std.string;
import std.typecons;

int [] read_array (int n)
{
	auto res = new int [n];
	auto rs = readln ();
	rs ~= ' ';
	foreach (i; 0..n)
	{
		while (rs[0] < '0')
		{
			rs = rs[1..$];
		}
		while (rs[0] >= '0')
		{
			res[i] = res[i] * 10 + (rs[0] - '0');
			rs = rs[1..$];
		}
	}
	return res;
}

void main ()
{
	GC.disable ();
	int n;
	while (scanf (" %d ", &n) > 0)
	{
		auto a = read_array (n);
		int t;
		scanf (" %d", &t);
		auto r = read_array (t);
		auto b = new bool [n];
		foreach (i; 0..t)
		{
			r[i]--;
			b[r[i]] = true;
		}
		reverse (a);
		reverse (b);
		auto s = new int [n + 1];
		int pos = 0;
		bool ok = true;
		foreach (i; 0..n)
		{
			if (b[i] || (s[pos] != a[i]))
			{
				pos++;
				s[pos] = a[i];
				a[i] = -a[i];
			}
			else if (s[pos] == a[i])
			{
				pos--;
			}
			else
			{
				ok = false;
				break;
			}
		}
		ok &= (pos == 0);
		writefln ("%s", ok ? "YES" : "NO");
		if (ok)
		{
			reverse (a);
			foreach (i; 0..n)
			{
				printf ("%d%c", a[i], i + 1 < n ? ' ' : '\n');
			}
		}
	}
}


import std.stdio;

immutable int MOD = 1_000_000_007;

void main ()
{
    int n;
    while (readf (" %s", &n) > 0)
    {
        auto a = new int [] [n];
        foreach (i; 1..n)
        {
            int x;
            readf (" %s", &x);
            x--;
            a[x] ~= i;
        }

        auto f = new long [n];
        f[] = 1;

        foreach_reverse (v; 0..n)
        {
            foreach (u; a[v])
            {
                f[v] = (f[v] * (f[u] + 1)) % MOD;
            }
        }

        auto g = new long [n];
        g[] = 1;

        foreach (v; 0..n)
        {
            long [] lo = [1];
            foreach (u; a[v])
            {
                lo ~= (lo[$ - 1] * (f[u] + 1)) % MOD;
            }

            long [] hi = [1];
            foreach_reverse (u; a[v])
            {
                hi ~= (hi[$ - 1] * (f[u] + 1)) % MOD;
            }

            foreach (i, u; a[v])
            {
                long cur = (g[v] * lo[i]) % MOD;
                cur = (cur * hi[a[v].length - 1 - i]) % MOD;
                g[u] = (g[u] * (cur + 1)) % MOD;
            }
        }

        auto h = new long [n];
        h[] = (f[] * g[]) % MOD;
        writefln ("%(%s %)", h);
    }
}

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

immutable int MOD = 1_000_000_007;
immutable int NA  =            -1;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [] [n];
		auto p = new int [n];
		p[0] = NA;
		foreach (i; 1..n)
		{
			int x;
			readf (" %s", &x);
			x--;
			assert (x < i);
			a[x] ~= i;
			p[i] = x;
		}

		auto f = new long [n];
		f[] = 1;

		foreach_reverse (v; 0..n)
		{
			foreach (u; a[v])
			{
				f[v] = (f[v] * (f[u] + 1)) % MOD;
			}
		}

		debug {writefln ("%(%s %)", f);}

		auto g = new long [n];
		g[] = 1;

		foreach (v; 0..n)
		{
			long [] lo = [1];
			foreach (u; a[v])
			{
				lo ~= (lo[$ - 1] * (f[u] + 1)) % MOD;
			}

			long [] hi = [1];
			foreach_reverse (u; a[v])
			{
				hi ~= (hi[$ - 1] * (f[u] + 1)) % MOD;
			}

			debug {writeln (v, ' ', lo, ' ', hi);}

			foreach (i, u; a[v])
			{
				long cur = (g[v] * lo[i]) % MOD;
				cur = (cur * hi[a[v].length - 1 - i]) % MOD;
				g[u] = (g[u] * (cur + 1)) % MOD;
			}
		}

		debug {writefln ("%(%s %)", g);}

		auto h = new long [n];
		h[] = (f[] * g[]) % MOD;
		writefln ("%(%s %)", h);
	}
}

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

immutable int MOD = 1_000_000_007;
immutable int NA  =            -1;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [] [n];
		auto p = new int [n];
		p[0] = NA;
		foreach (i; 1..n)
		{
			int x;
			readf (" %s", &x);
			x--;
			assert (x < i);
			a[x] ~= i;
			p[i] = x;
		}

		auto f = new long [n];
		f[] = 1;

		foreach_reverse (v; 0..n)
		{
			foreach (u; a[v])
			{
				f[v] = (f[v] * (f[u] + 1)) % MOD;
			}
		}

		debug {writefln ("%(%s %)", f);}

		auto g = new long [n];
		g[] = 1;

		foreach (v; 0..n)
		{
			auto lo = [1];
			foreach (u; a[v])
			{
				lo ~= (lo[$ - 1] * (f[u] + 1)) % MOD;
			}

			auto hi = [1];
			foreach_reverse (u; a[v])
			{
				hi ~= (hi[$ - 1] * (f[u] + 1)) % MOD;
			}

			debug {writeln (v, ' ', lo, ' ', hi);}

			foreach (i, u; a[v])
			{
				int cur = (g[v] * lo[i]) % MOD;
				cur = (cur * hi[a[v].length - 1 - i]) % MOD;
				g[u] = (g[u] * (cur + 1)) % MOD;
			}
		}

		debug {writefln ("%(%s %)", g);}

		auto h = new long [n];
		h[] = (f[] * g[]) % MOD;
		writefln ("%(%s %)", h);
	}
}


import std.algorithm;
import std.exception;
import std.math;
import std.stdio;
import std.string;

immutable int LET = 26;

struct node
{
	int [LET] p;
}

int main ()
{
	string s;
	while (readf (" ") >= 0 &&
	       (s = strip (readln ())) != "" && !stdin.eof ())
	{
		string buf;
		buf = readln ();
		buf = strip (buf);
		enforce (buf.length == LET);
		auto b = new bool [LET];
		foreach (i; 0..LET)
		{
			b[i] = (buf[i] == '1');
		}
		int k;
		readf (" %s", &k);
		int n = s.length;

		int res = 0;
		auto t = new node [0];
		reserve (t, n * (n - 1) / 2 + 1);
		t ~= node ();
		foreach (i; 0..n)
		{
			int v = 0;
			int z = 0;
			foreach (j; i..n)
			{
				int c = s[j] - 'a';
				z += !b[c];
				if (z > k)
				{
					break;
				}
				if (!t[v].p[c])
				{
					debug {writefln ("%s", s[i..j + 1]);}
					t ~= node ();
					t[v].p[c] = t.length - 1;
					res++;
				}
				v = t[v].p[c];
			}
		}

		writefln ("%s", res);
	}
	return 0;
}

import std.algorithm;
import std.exception;
import std.math;
import std.stdio;
import std.string;

immutable int LET = 26;

struct node
{
	int [LET] p;
}

int main ()
{
	string s;
	while (readf (" ") >= 0 &&
	       (s = strip (readln ())) != "" && !stdin.eof ())
	{
		string buf;
		buf = readln ();
		buf = strip (buf);
		enforce (buf.length == LET);
		auto b = new bool [LET];
		foreach (i; 0..LET)
		{
			b[i] = (buf[i] == '1');
		}
		int k;
		readf (" %s", &k);
		int n = s.length;

		int res = 0;
		auto t = new node [0];
		t ~= node ();
		foreach (i; 0..n)
		{
			int v = 0;
			int z = 0;
			foreach (j; i..n)
			{
				int c = s[j] - 'a';
				z += !b[c];
				if (z > k)
				{
					break;
				}
				if (!t[v].p[c])
				{
					debug {writefln ("%s", s[i..j + 1]);}
					t ~= node ();
					t[v].p[c] = t.length - 1;
					res++;
				}
				v = t[v].p[c];
			}
		}

		writefln ("%s", res);
	}
	return 0;
}

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

__gshared:

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

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

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

struct Node {
    int len;
    Node*[char] next;
    Node* link;
    int[int] dp;

    this(this) {
        next = next.dup;
        dp = dp.dup;
    }

    Node* append(char c, Node* last) {
        auto cur = createNode(Node(last.len + 1));
        Node** p;
        while ((p = c in last.next) is null) {
            last.next[c] = cur;
            last = last.link;
            if (last is null) {
                cur.link = &this;
                return cur;
            }
        }
        auto q = *p;
        if (q.len == last.len + 1) {
            cur.link = q;
            return cur;
        }
        auto clone = createNode(*q);
        clone.len = last.len + 1;
        cur.link = q.link = clone;
        do {
            *p = clone;
            last = last.link;
            if (last is null)
                break;
            p = c in last.next;
        } while (p !is null && *p == q);
        return cur;
    }

    int calc(int badTaken) {
        if (badTaken > k)
            return 0;
        if (auto p = badTaken in dp)
            return *p;
        int result = 1;
        foreach (c, node; next)
            result += node.calc(badTaken + (good[c - 'a'] == '0'));
        dp[badTaken] = result;
        return result;
    }
}

char[1501] _s;
char[ ] s;
char[27] good;
int k;
int nodesSize;
Node[3000] nodes;

auto createNode()(auto ref Node node) {
    nodes[nodesSize] = node;
    return &nodes[nodesSize++];
}

void main() {
    while (true) {
        s = _s[ ];
        readln(s);
        if (s.empty)
            break;
        s = s[0 .. $ - 1];
        auto temp = good[ ];
        readln(temp);
        read(&k);

        Node root;
        auto last = &root;
        nodesSize = 0;
        foreach (c; s)
            last = root.append(c, last);
        writeln(root.calc(0) - 1);
    }
}

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

__gshared:

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

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

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

struct Node {
    int len;
    Node*[26] next;
    Node* link;
    int[int] dp;

    Node* append(int c, Node* last) {
        auto cur = createNode(Node(last.len + 1));
        for (; last !is null && last.next[c] is null; last = last.link)
            last.next[c] = cur;
        if (last is null) {
            cur.link = &this;
            return cur;
        }
        auto q = last.next[c];
        if (q.len == last.len + 1) {
            cur.link = q;
            return cur;
        }
        auto clone = createNode(*q);
        clone.len = last.len + 1;
        cur.link = q.link = clone;
        for (; last !is null && last.next[c] == q; last = last.link)
            last.next[c] = clone;
        return cur;
    }

    int calc(int badTaken) {
        if (badTaken > k)
            return 0;
        if (auto p = badTaken in dp)
            return *p;
        int result = 1;
        foreach (i, node; next)
            if (node !is null)
                result += node.calc(badTaken + (good[i] == '0'));
        dp[badTaken] = result;
        return result;
    }
}

char[1501] _s;
char[ ] s;
char[27] good;
int k;
int nodesSize;
Node[3000] nodes;

auto createNode()(auto ref Node node) {
    nodes[nodesSize] = node;
    return &nodes[nodesSize++];
}

void main() {
    while (true) {
        s = _s[ ];
        readln(s);
        if (s.empty)
            break;
        s = s[0 .. $ - 1];
        auto temp = good[ ];
        readln(temp);
        read(&k);

        Node root;
        auto last = &root;
        nodesSize = 0;
        foreach (c; s)
            last = root.append(c - 'a', last);
        writeln(root.calc(0) - 1);
    }
}

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

__gshared:

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

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

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

struct Node {
    int len;
    Node*[char] next;
    Node* link;
    int[int] dp;

    Node* append(char c, Node* last) {
        auto cur = createNode(Node(last.len + 1));
        Node** p;
        while ((p = c in last.next) is null) {
            last.next[c] = cur;
            last = last.link;
            if (last is null) {
                cur.link = &this;
                return cur;
            }
        }
        auto q = *p;
        if (q.len == last.len + 1) {
            cur.link = q;
            return cur;
        }
        auto clone = createNode(*q);
        clone.len = last.len + 1;
        cur.link = q.link = clone;
        do {
            *p = clone;
            last = last.link;
            if (last is null)
                break;
            p = c in last.next;
        } while (p !is null && *p == q);
        return cur;
    }

    int calc(int badTaken) {
        if (badTaken > k)
            return 0;
        if (auto p = badTaken in dp)
            return *p;
        int result = 1;
        foreach (c, node; next)
            result += node.calc(badTaken + (good[c - 'a'] == '0'));
        dp[badTaken] = result;
        return result;
    }
}

char[1501] _s;
char[ ] s;
char[27] good;
int k;
int nodesSize;
Node[3000] nodes;

auto createNode()(auto ref Node node) {
    nodes[nodesSize] = node;
    return &nodes[nodesSize++];
}

void main() {
    while (true) {
        s = _s[ ];
        readln(s);
        if (s.empty)
            break;
        s = s[0 .. $ - 1];
        auto temp = good[ ];
        readln(temp);
        read(&k);

        Node root;
        auto last = &root;
        nodesSize = 0;
        foreach (c; s)
            last = root.append(c, last);
        writeln(root.calc(0) - 1);
    }
}

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

__gshared:

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

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

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

struct Node {
    int len;
    Node*[char] next;
    Node* link;
    int[int] dp;

    Node* append(char c, Node* last) {
        auto cur = createNode(Node(last.len + 1));
        for (; last !is null && c !in last.next; last = last.link)
            last.next[c] = cur;
        if (last is null) {
            cur.link = &this;
            return cur;
        }
        auto q = last.next[c];
        if (q.len == last.len + 1) {
            cur.link = q;
            return cur;
        }
        auto clone = createNode(*q);
        clone.len = last.len + 1;
        cur.link = q.link = clone;
        for (; last !is null && last.next.get(c, null) == q; last = last.link)
            last.next[c] = clone;
        return cur;
    }

    int calc(int badTaken) {
        if (badTaken > k)
            return 0;
        if (auto p = badTaken in dp)
            return *p;
        int result = 1;
        foreach (c, node; next)
            result += node.calc(badTaken + (good[c - 'a'] == '0'));
        dp[badTaken] = result;
        return result;
    }
}

char[1501] _s;
char[ ] s;
char[27] good;
int k;
int nodesSize;
Node[3000] nodes;

auto createNode()(auto ref Node node) {
    nodes[nodesSize] = node;
    return &nodes[nodesSize++];
}

void main() {
    while (true) {
        s = _s[ ];
        readln(s);
        if (s.empty)
            break;
        s = s[0 .. $ - 1];
        auto temp = good[ ];
        readln(temp);
        read(&k);

        Node root;
        auto last = &root;
        nodesSize = 0;
        foreach (c; s)
            last = root.append(c, last);
        writeln(root.calc(0) - 1);
    }
}

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

__gshared:

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

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

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

struct Node {
    int len;
    bool cloned;
    Node*[char] next;
    Node* link;
    int[int] dp;

    Node* append(char c, Node* last) {
        auto cur = createNode(Node(last.len + 1));
        Node** p;
        while ((p = c in last.next) is null) {
            last.next[c] = cur;
            last = last.link;
            if (last is null) {
                cur.link = &this;
                return cur;
            }
        }
        auto q = *p;
        if (q.len == last.len + 1) {
            cur.link = q;
            return cur;
        }
        auto clone = createNode(*q);
        clone.cloned = true;
        clone.len = last.len + 1;
        cur.link = q.link = clone;
        do {
            *p = clone;
            last = last.link;
            if (last is null)
                break;
            p = c in last.next;
        } while (p !is null && *p == q);
        return cur;
    }

    int calc(int badTaken) {
        if (badTaken > k)
            return 0;
        if (auto p = badTaken in dp)
            return *p;
        int result = !cloned;
        foreach (k, v; next)
            result += v.calc(badTaken + (good[k - 'a'] == '0'));
        dp[badTaken] = result;
        return result;
    }
}

char[1501] _s;
char[ ] s;
char[27] good;
int k;
int nodesSize;
Node[3000] nodes;

auto createNode()(auto ref Node node) {
    nodes[nodesSize] = node;
    return &nodes[nodesSize++];
}

void main() {
    while (true) {
        s = _s[ ];
        readln(s);
        if (s.empty)
            break;
        s = s[0 .. $ - 1];
        auto temp = good[ ];
        readln(temp);
        read(&k);

        Node root;
        auto last = &root;
        nodesSize = 0;
        foreach (c; s)
            last = root.append(c, last);
        writeln(root.calc(0) - 1);
    }
}

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

__gshared:

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

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

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

struct Node {
    int len;
    Node*[char] next;
    Node* link;
    int[int] dp;

    Node* append(char c, Node* last) {
        auto cur = createNode(Node(last.len + 1));
        Node** p;
        while ((p = c in last.next) is null) {
            last.next[c] = cur;
            last = last.link;
            if (last is null) {
                cur.link = &this;
                return cur;
            }
        }
        auto q = *p;
        if (q.len == last.len + 1) {
            cur.link = q;
            return cur;
        }
        auto clone = createNode(*q);
        clone.len = last.len + 1;
        cur.link = q.link = clone;
        do {
            last.next[c] = clone;
            last = last.link;
            if (last is null)
                break;
            p = c in last.next;
        } while (p !is null && *p == q);
        return cur;
    }

    int calc(int badTaken) {
        if (badTaken > k)
            return 0;
        if (auto p = badTaken in dp)
            return *p;
        int result = 1;
        foreach (c, node; next)
            result += node.calc(badTaken + (good[c - 'a'] == '0'));
        dp[badTaken] = result;
        return result;
    }
}

char[1501] _s;
char[ ] s;
char[27] good;
int k;
int nodesSize;
Node[3000] nodes;

auto createNode()(auto ref Node node) {
    nodes[nodesSize] = node;
    return &nodes[nodesSize++];
}

void main() {
    while (true) {
        s = _s[ ];
        readln(s);
        if (s.empty)
            break;
        s = s[0 .. $ - 1];
        auto temp = good[ ];
        readln(temp);
        read(&k);

        Node root;
        auto last = &root;
        nodesSize = 0;
        foreach (c; s)
            last = root.append(c, last);
        writeln(root.calc(0) - 1);
    }
}

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

__gshared:

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

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

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

struct Node {
    int len;
    Node*[char] next;
    Node* link;
    int[int] dp;

    Node* append(char c, Node* last) {
        auto cur = createNode(Node(last.len + 1));
        Node** p;
        while ((p = c in last.next) is null) {
            last.next[c] = cur;
            last = last.link;
            if (last is null) {
                cur.link = &this;
                return cur;
            }
        }
        auto q = *p;
        if (q.len == last.len + 1) {
            cur.link = q;
            return cur;
        }
        auto clone = createNode(*q);
        clone.len = last.len + 1;
        cur.link = q.link = clone;
        do {
            *p = clone;
            last = last.link;
            if (last is null)
                break;
            p = c in last.next;
        } while (p !is null && *p == q);
        return cur;
    }

    int calc(int badTaken) {
        if (badTaken > k)
            return 0;
        if (auto p = badTaken in dp)
            return *p;
        int result = 1;
        foreach (k, v; next)
            result += v.calc(badTaken + (good[k - 'a'] == '0'));
        dp[badTaken] = result;
        return result;
    }
}

char[1501] _s;
char[ ] s;
char[27] good;
int k;
int nodesSize;
Node[3000] nodes;

auto createNode()(auto ref Node node) {
    nodes[nodesSize] = node;
    return &nodes[nodesSize++];
}

void main() {
    while (true) {
        s = _s[ ];
        readln(s);
        if (s.empty)
            break;
        s = s[0 .. $ - 1];
        auto temp = good[ ];
        readln(temp);
        read(&k);

        Node root;
        auto last = &root;
        nodesSize = 0;
        foreach (c; s)
            last = root.append(c, last);
        writeln(root.calc(0) - 1);
    }
}


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

int main()
{
	string line = readln();
	line = line.replace("{", "").replace("}", "");
	auto let = line.split(",");
	int[string] letters;
	int distinct = 0;
	foreach (string s; let)
	{
		string p = s.strip();
		if (p.length == 0)
			continue;
		if (!(p in letters))
		{
			distinct++;
			letters[p] = 1;
		}
	}
	write(distinct);
	return 0;
}

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

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

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

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

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

void main(string[] args) {
	// try {
	for (string line; (line = readln) != null; ) {
		auto ss = line.chomp.removechars("{} ").split(",");
debug{
writeln("ss = ",ss);
}
		bool[string] app;
		foreach (s; ss) {
			app[s] = true;
		}
		writeln(app.keys.length);
	}
	// } catch (EOFException) {}
}

import std.stdio: writeln, stdin;
import std.string: strip;
import std.algorithm.iteration: uniq;
import std.algorithm.sorting: sort;
import std.regex;
import std.array;

void main()
{
  auto h = (stdin.readln.strip)[1..$-1].split(regex(` *, *`));
  h.sort;
  writeln (h.uniq.array.length);
}

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

void main() {
	string s = readln.chomp;
	bool[char] chars;
	foreach (c; s) {
		if ('a' <= c && c <= 'z') {
			if (!(c in chars)) {
				chars[c] = true;
			}
		}
	}

	chars.length.writeln;
}


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

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

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

void solve() {
    auto N = read!ulong;
    auto m = bsf(2*N);
    auto X = 1L<<m;
    auto Y = (2L*N) / X;

    bool check(ulong k) {
        if (k < 2L) return false;
        if (k >= int.max) return false;
        return N >= k * (k + 1L) / 2L;
    }

    if (check(X)) {
        writeln(X);
    } else if (check(Y)) {
        writeln(Y);
    } else {
        writeln(-1);
    }
}

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

long solve (long n)
{
	if (!(n & (n - 1)))
	{
		return -1;
	}
	long p2 = 1;
	while (!(n & 1))
	{
		p2 <<= 1;
		n >>= 1;
	}
	if (p2 > (n >> 1))
	{
		return n;
	}
	else
	{
		return p2 * 2;
	}
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(long);
		writeln (solve (n));
	}
}

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

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

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

void solve() {
    auto N = read!ulong;
    auto m = bsf(2*N);
    auto X = 1L<<m;
    auto Y = (2L*N) / X;

    bool check(ulong k) {
        if (k < 2) return false;
        return N >= k * (k + 1L) / 2L;
    }

    if (check(X)) {
        writeln(X);
    } else if (check(Y)) {
        writeln(Y);
    } else {
        writeln(-1);
    }
}

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

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

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

void solve() {
    auto N = read!long;
    auto m = bsf(2*N);
    auto X = 1L<<m;
    auto Y = (2*N) / X;

    bool check(long k) {
        if (k < 2) return false;
        return N >= k * (k + 1L) / 2L;
    }

    if (check(X)) {
        writeln(X);
    } else if (check(Y)) {
        writeln(Y);
    } else {
        writeln(-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.ascii, std.typecons;

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

    immutable int MX = 210;

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

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

        auto lft = new int[][] (n+10, MX);
        auto lftpos = new int[][] (MX);
        auto rtcnt = new int[] (MX);

        foreach (i, e; arr) {
            foreach (v; 0 .. MX) { lft[i][v] = i > 0 ? lft[i-1][v] : 0; }
            lft[i][e] += 1;

            lftpos[e] ~= i.to!int;
        }

        int ans = 1;
        foreach_reverse (r, e; arr) {
            rtcnt[e] += 1;

            int le = lftpos[e][rtcnt[e]-1];

            if (le >= r) { continue; }

            int mxy = 0;
            foreach (v; 0 .. MX) {
                mxy = max(mxy, lft[r-1][v] - lft[le][v]);
            }

            ans = max(ans, mxy + 2 * rtcnt[e]);
        }

        ans.writeln;
    }
}

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.ascii, std.typecons;

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

    immutable int MX = 30;

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

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

        auto lft = new int[][] (n+10, MX);
        auto rt = new int[][] (n+10, MX);

        foreach (i, e; arr) {
            foreach (v; 0 .. MX) { lft[i][v] = i > 0 ? lft[i-1][v] : 0; }

            lft[i][e] += 1;
        }

        foreach (v; 0 .. MX) { rt[n][v] = 0; }
        foreach_reverse (i, e; arr) {
            foreach (v; 0 .. MX) { rt[i][v] = rt[i+1][v]; }

            rt[i][e] += 1;
        }

        int ans = 0;
        foreach (i; 0 .. n) {
            foreach (j; i+1 .. n+1) {
                int cur = 0;
                foreach (v; 0 .. MX) {
                    cur = max(cur, lft[j-1][v] - (i > 0 ? lft[i-1][v] : 0));
                }

                int add = 0;
                foreach (v; 0 .. MX) {
                    add = max(add, min((i > 0 ? lft[i-1][v] : 0), rt[j][v]));
                }

                ans = max(ans, cur + 2*add);
            }
        }

        ans.writeln;
    }
}

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

enum MAX_C = 200;

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!int;
        auto as = readln.split.to!(int[]);

        if (N == 1) {
            writeln(1);
            continue;
        } else if (N == 2) {
            writeln(as[0] == as[1] ? 2 : 1);
            continue;
        }

        auto cs = new int[][](N, MAX_C);
        foreach (i, ref a; as) {
            a -= 1;
            if (i) foreach (j; 0..MAX_C) cs[i][j] = cs[i-1][j];
            ++cs[i][a];
        }
        long res;
        foreach (i; 0..MAX_C) res = max(res, cs[N-1][i]);
        foreach (n; 0..MAX_C) {
            foreach (c; 1..cs[N-1][n]/2+1) {
                int i, j, l, r;

                if (cs[0][n] == c) {
                    i = 0;
                } else {
                    r = N-1;
                    while (l+1 < r) {
                        auto m = (l+r)/2;
                        if (cs[m][n] < c) {
                            l = m;
                        } else {
                            r = m;
                        }
                    }
                    i = r;
                }

                l = 0; r = N-1;
                while (l+1 < r) {
                    auto m = (l+r)/2;
                    if (cs[N-1][n] - cs[m][n] < c) {
                        r = m;
                    } else {
                        l = m;
                    }
                }
                j = l;

                int max_d;
                foreach (d; 0..MAX_C) max_d = max(max_d, cs[j][d] - cs[i][d]);

                res = max(res, c*2 + max_d);
            }
        }
        writeln(res);
    }
}

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

immutable int limit = 201;

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto s = new int [limit];
		foreach (i; 0..n)
		{
			s[a[i]] += 1;
		}

		auto c = new int [n + 3];
		int res = 0;
		foreach (u; 0..limit)
		{
			if (s[u] == 0)
			{
				continue;
			}
			auto t = s.dup;
			c[0] = 0;
			c[1] = 0;
			c[2] = 0;
			foreach (v; 0..limit)
			{
				c[t[v]] += 1;
			}
			debug {writeln (t); writeln (c);}
			int pos = n;
			while (!c[pos])
			{
				pos -= 1;
			}

			void decrease (ref int x)
			{
				c[x] -= 1;
				x -= 1;
				c[x] += 1;
				while (!c[pos])
				{
					pos -= 1;
				}
			}

			int lo = 0;
			int hi = n - 1;
			int add = 0;
			res = max (res, pos + add);
			while (true)
			{
				while (lo < hi && a[lo] != u)
				{
					decrease (t[a[lo]]);
					lo += 1;
				}

				while (lo < hi && a[hi] != u)
				{
					decrease (t[a[hi]]);
					hi -= 1;
				}

				if (lo >= hi)
				{
					break;
				}

				decrease (t[a[lo]]);
				lo += 1;
				decrease (t[a[hi]]);
				hi -= 1;
				debug {writeln (lo, " ", hi, " ", pos);}
				add += 2;
				res = max (res, pos + add);
			}
		}
		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 M = 26;
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int(-1);

		auto b = new int[][](n+1, M);
		foreach (i; 0..n)
		{
			b[i+1][] += b[i][];
			++b[i+1][a[i]];
		}
		auto c = new int[][](n+1, M);
		foreach_reverse (i; 0..n)
		{
			c[i][] += c[i+1][];
			++c[i][a[i]];
		}

		foreach (num; 0..M)
		{
			int l, r = n;
			while (r-l > 0)
			{
				auto c1 = b[l][num];
				auto c2 = c[r][num];
				if (c1 == c2)
				{
					auto tmp = b[r].dup;
					tmp[] -= b[l][];
					auto p = tmp.MIN_POS!"a > b";
					ans[ti].chmax(c1+c2+tmp[p]);
					++l;
				}
				else if (c1 < c2)
					++l;
				else
					--r;
			}
		}
	}

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


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

DList!string _words;

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

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

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

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

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

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

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

    }
}

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

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

void main()
{
  auto t = next!int;
  foreach(tc; 0 .. t)
    {
      auto n = next!long;
      auto path = next!string;
      long[Tuple!(long, long)] lastPosition;
      auto acc = tuple!(long, long)(0, 0);
      lastPosition[acc] = 0;
      long lp, cp;
      foreach(i; 1 .. n + 1)
        {
          switch(path[(i - 1).ind])
            {
            case 'L':
              acc[0]--;
              break;
            case 'R':
              acc[0]++;
              break;
            case 'U':
              acc[1]++;
              break;
            case 'D':
              acc[1]--;
              break;
            default:
              assert(0);
            }
          if (acc in lastPosition)
            {
              if (cast(long) i - lastPosition[acc] < cp - lp || cp == lp)
                {
                  cp = cast(long) i;
                  lp = lastPosition[acc];
                }
            }
          lastPosition[acc] = cast(long) i;
        }
      if (lp == cp)
        {
          writeln(-1);
        }
      else
        {
          writeln(lp + 1, " ", cp);
        }
    }
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.typecons;
import std.algorithm.mutation;
import std.container.array;

string[] tokens;

string readToken()
{
    while (tokens.empty)
    {
        tokens = readln.split;
    }
    auto token = tokens.front;
    tokens.popFront;
    return token;
}

int readInt()
{
    return readToken.to!int;
}

void main()
{
    int T = readInt;
    while (T--)
    {
        int n = readInt;
        auto s = readToken;
        int[Tuple!(int, int)] tbl;
        tbl[tuple(0, 0)] = 0;
        int x = 0, y = 0;
        auto best = tuple(n + 1, 0, 0);
        for (int i = 0; i < n; ++i)
        {
            final switch (s[i])
            {
            case 'L':
                x--;
                break;
            case 'R':
                x++;
                break;
            case 'D':
                y--;
                break;
            case 'U':
                y++;
            }
            int idx = tbl.get(tuple(x, y), -1);
            if (idx != -1)
                best = min(best, tuple(i - idx + 1, idx + 1, i + 1));
            tbl[tuple(x, y)] = i + 1;
        }
        if (best[0] <= n)
        {
            writeln(best[1], " ", best[2]);
        }
        else
        {
            writeln(-1);
        }

    }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new int[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s = RD!string;
		int[int[2]] set;
		set[[0, 0]] = 0;
		int[2] cnt;
		int len = int.max;
		foreach (i; 0..n)
		{
			if (s[i] == 'L')
				--cnt[0];
			else if (s[i] == 'R')
				++cnt[0];
			else if (s[i] == 'U')
				--cnt[1];
			else
				++cnt[1];

			int[2] x = cnt.dup;
			auto pos = set.get(x, -1);
			if (pos != -1)
			{
				if (i - pos < len)
				{
					len = i - pos;
					ans[ti] = [pos+1, i+1];
				}
			}
			auto y = set.get(cnt, 0);
			set[cnt] = max(y, i+1);
		}
		debug writeln(set);
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln(-1);
		else
			writeln(e[0], " ", e[1]);
	}
	stdout.flush;
	debug readln;
}


void main() { runSolver(); }

void problem() {
  auto QN = 1;

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

      auto xt = SegTree!("min(a, b)", int)(new int[](N + 1), int.max/2);
      auto yt = SegTree!("min(a, b)", int)(new int[](N + 1), int.max/2);

      foreach(qi; 0..Q) {
        auto q = scan!int;
        if (q == 1 || q == 2) {
          auto x = scan!int;
          auto y = scan!int;
          if (q == 1) {
            xt.update(x, xt.get(x) + 1);
            yt.update(y, yt.get(y) + 1);
            // xt.get(x).deb;
          } else {
            xt.update(x, xt.get(x) - 1);
            yt.update(y, yt.get(y) - 1);
            // xt.get(x).deb;
          }
        } else {
          auto x1 = scan!int;
          auto y1 = scan!int;
          auto x2 = scan!int;
          auto y2 = scan!int;

          // [x1, xt.get(x1)].deb;
          // [y1, y2, yt.get(y1)].deb;
          // [xt.sum(x1, x2), yt.sum(y1, y2)].deb;

          auto ans = max(xt.sum(x1, x2 + 1), yt.sum(y1, y2 + 1));
          writeln(ans == 0 ? "No" : "Yes");
        }
      }
    }

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

  outputForAtCoder(&solve);
}

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

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

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

struct SegTree(alias pred = "a + b", T = long) {
  alias predFun = binaryFun!pred;
  int size;
  T[] data;
  T monoid;

  this(T[] src, T monoid = T.init) {
    this.monoid = monoid;

    for(int i = 2; i < 2L^^32; i *= 2) {
      if (src.length <= i) {
        size = i;
        break;
      }
    }

    data = new T[](size * 2);
    foreach(i, s; src) data[i + size] = s;
    foreach_reverse(b; 1..size) {
      data[b] = predFun(data[b * 2], data[b * 2 + 1]);
    }
  }

  void update(int index, T value) {
    int i = index + size;
    data[i] = value;
    while(i > 0) {
      i /= 2;
      data[i] = predFun(data[i * 2], data[i * 2 + 1]);
    }
  }

  T get(int index) {
    return data[index + size];
  }

  T sum(int a, int b, int k = 1, int l = 0, int r = -1) {
    if (r < 0) r = size;

    if (r <= a || b <= l) return monoid;
    if (a <= l && r <= b) return data[k];

    T leftValue = sum(a, b, 2*k, l, (l + r) / 2);
    T rightValue = sum(a, b, 2*k + 1, (l + r) / 2, r);
    return predFun(leftValue, rightValue);
  }
}

import std;
import std.outbuffer;

const int MAXN = 100005;

int n,q;

struct Bit
{
    int[MAXN] t;

    int lowbit(int x) {
        return x & (-x);
    }

    void update(int x, int k) {
        while (x <= n) {
            t[x] += k;
            x += lowbit(x);
        }
    }

    int ask(int x) {
        int res = 0;
        while (x > 0) {
            res += t[x];
            x -= lowbit(x);
        }
        return res;
    }

    int query(int l, int r) {
        return ask(r) - ask(l - 1);
    }
}

Bit bx, by;

int[MAXN] cntRows, cntCols;

void main()
{
    OutBuffer buf = new OutBuffer();
    scanf("%d %d", &n, &q);
    getchar();
    outer: foreach(_; 0..q)
    {
        int op, x1, x2, y1, y2;
        scanf("%d ", &op);
        if (op == 3) {
            scanf("%d %d %d %d\n", &x1, &y1, &x2, &y2);
            if (bx.query(x1,x2) == x2 - x1 + 1 || by.query(y1, y2) == y2 - y1 + 1)
                buf.printf("Yes\n");
            else
                buf.printf("No\n");
        }
        else {
            scanf("%d %d\n", &x1, &y1);
            if (op == 1) {
                if (cntRows[x1]++ == 0)
                    bx.update(x1,1);
                if (cntCols[y1]++ == 0)
                    by.update(y1,1);
            }
            else if (op == 2) {
                if (cntRows[x1]-- == 1)
                    bx.update(x1,-1);
                if (cntCols[y1]-- == 1)
                    by.update(y1,-1);
            }
        }
    }
    writeln(buf);
}

import std;
import core.stdc.stdio;

const int MAXN = 100005;

int n,q;

struct Bit
{
    int[MAXN] t;

    int lowbit(int x) {
        return x & (-x);
    }

    void update(int x, int k) {
        while (x <= n) {
            t[x] += k;
            x += lowbit(x);
        }
    }

    int ask(int x) {
        int res = 0;
        while (x > 0) {
            res += t[x];
            x -= lowbit(x);
        }
        return res;
    }

    int query(int l, int r) {
        return ask(r) - ask(l - 1);
    }
}

Bit bx, by;

int[MAXN] cntRows, cntCols;

void main()
{
    scanf("%d %d", &n, &q);
    getchar();
    outer: foreach(_; 0..q)
    {
        int op, x1, x2, y1, y2;
        scanf("%d ", &op);
        if (op == 3) {
            scanf("%d %d %d %d\n", &x1, &y1, &x2, &y2);
            if (bx.query(x1,x2) == x2 - x1 + 1 || by.query(y1, y2) == y2 - y1 + 1)
                printf("Yes\n");
            else
                printf("No\n");
        }
        else {
            scanf("%d %d\n", &x1, &y1);
            if (op == 1) {
                if (cntRows[x1]++ == 0)
                    bx.update(x1,1);
                if (cntCols[y1]++ == 0)
                    by.update(y1,1);
            }
            else if (op == 2) {
                if (cntRows[x1]-- == 1)
                    bx.update(x1,-1);
                if (cntCols[y1]-- == 1)
                    by.update(y1,-1);
            }
        }
    }
}

import std;
import core.stdc.stdio;

void main()
{
    int n, q;
    scanf("%d %d", &n, &q);
    getchar();
    auto freeRows = redBlackTree(iota(n+1));
    auto freeCols = redBlackTree(iota(n+1));
    int[] cntRows = new int[](n+1);
    int[] cntCols = new int[](n+1);
    outer: foreach(_; 0..q)
    {
        int qtype, x1, x2, y1, y2;
        scanf("%d ", &qtype);
        if (qtype == 3) {
            scanf("%d %d %d %d\n", &x1, &y1, &x2, &y2);
            auto l1 = freeRows.lowerBound(x2 + 1).array;
            auto u1 = freeRows.upperBound(x1 - 1).array;
            auto l2 = freeCols.lowerBound(y2 + 1).array;
            auto u2 = freeCols.upperBound(y1 - 1).array;
            if (l1[$-1]==u1[0] || l2[$-1]==u2[0])
                printf("No\n");
            else
                printf("Yes\n");
        }
        else {
            scanf("%d %d\n", &x1, &y1);
            if (qtype == 1) {
                if (cntRows[x1] == 0)
                    freeRows.removeKey(x1);
                cntRows[x1]++;
                if (cntCols[y1] == 0)
                    freeCols.removeKey(y1);
                cntCols[y1]++;
            }
            else {
                cntRows[x1]--;
                cntCols[y1]--;
                if (cntRows[x1] == 0)
                    freeRows.insert(x1);
                if (cntCols[y1] == 0)
                    freeCols.insert(y1);
            }
        }
    }
}

import std;
import core.stdc.stdio;

void main()
{
    int n, q;
    scanf("%d %d", &n, &q);
    getchar();
    auto freeRows = redBlackTree(iota(n));
    auto freeCols = redBlackTree(iota(n));
    int[] cntRows = new int[](n+1);
    int[] cntCols = new int[](n+1);
    outer: foreach(_; 0..q)
    {
        int qtype, x1, x2, y1, y2;
        scanf("%d ", &qtype);
        if (qtype == 3) {
            scanf("%d %d %d %d\n", &x1, &y1, &x2, &y2);
            auto ll = freeRows.lowerBound(x2 + 1);
            auto uu = freeRows.upperBound(x1 - 1);
            bool t1 = setIntersection(ll, uu).array.length == 0;
            ll = freeCols.lowerBound(y2 + 1);
            uu = freeCols.upperBound(y1 - 1);
            bool t2 = setIntersection(ll, uu).array.length == 0;
            if (t1 || t2)
                printf("Yes\n");
            else
                printf("No\n");
        }
        else {
            scanf("%d %d\n", &x1, &y1);
            if (qtype == 1) {
                if (cntRows[x1] == 0)
                    freeRows.removeKey(x1);
                cntRows[x1]++;
                if (cntCols[y1] == 0)
                    freeCols.removeKey(y1);
                cntCols[y1]++;
            }
            else {
                cntRows[x1]--;
                cntCols[y1]--;
                if (cntRows[x1] == 0)
                    freeRows.insert(x1);
                if (cntCols[y1] == 0)
                    freeCols.insert(y1);
            }
        }
    }
}