Mihai has just learned about the MEX concept and since he liked it so much, he decided to use it right away.Given an array $$$a$$$ of $$$n$$$ non-negative integers, Mihai wants to create a new array $$$b$$$ that is formed in the following way:While $$$a$$$ is not empty:   Choose an integer $$$k$$$ ($$$1 \leq k \leq |a|$$$).  Append the MEX of the first $$$k$$$ numbers of the array $$$a$$$ to the end of array $$$b$$$ and erase them from the array $$$a$$$, shifting the positions of the remaining numbers in $$$a$$$. But, since Mihai loves big arrays as much as the MEX concept, he wants the new array $$$b$$$ to be the lexicographically maximum. So, Mihai asks you to tell him what the maximum array $$$b$$$ that can be created by constructing the array optimally is.An array $$$x$$$ is lexicographically greater than an array $$$y$$$ if in the first position where $$$x$$$ and $$$y$$$ differ $$$x_i > y_i$$$ or if $$$|x| > |y|$$$ and $$$y$$$ is a prefix of $$$x$$$ (where $$$|x|$$$ denotes the size of the array $$$x$$$).The MEX of a set of non-negative integers is the minimal non-negative integer such that it is not in the set. For example, MEX({$$${1, 2, 3}$$$}) $$$= 0$$$ and MEX({$$${0, 1, 2, 4, 5}$$$}) $$$= 3$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of elements in the array $$$a$$$. The second line of each test case contains $$$n$$$ non-negative integers $$$a_1, \ldots, a_n$$$ ($$$0 \leq a_i \leq n$$$), where $$$a_i$$$ is the $$$i$$$-th integer from the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print $$$m$$$ — the length of the maximum array $$$b$$$ Mihai can create, followed by $$$m$$$ integers denoting the elements of the array $$$b$$$.

NoteIn the first test case, the lexicographically maximum array $$$b$$$ is obtained by selecting $$$k=5$$$, resulting in the $$$MEX$$$ of the whole array $$$a$$$. It is lexicographically maximum because an array starting with a smaller number than $$$4$$$ is lexicographically smaller, and choosing a $$$k<5$$$ would result in an array starting with a number smaller than $$$4$$$.In the second test case, there are two ways to obtain the maximum array: first selecting $$$k=6$$$, then $$$k=2$$$, or first selecting $$$k=7$$$ and then $$$k=1$$$.

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


As you know, Vova has recently become a new shaman in the city of Ultima Thule. So, he has received the shaman knowledge about the correct bracket sequences. The shamans of Ultima Thule have been using lots of different types of brackets since prehistoric times. A bracket type is a positive integer. The shamans define a correct bracket sequence as follows:  An empty sequence is a correct bracket sequence.  If {a1, a2, ..., al} and {b1, b2, ..., bk} are correct bracket sequences, then sequence {a1, a2, ..., al, b1, b2, ..., bk} (their concatenation) also is a correct bracket sequence.  If {a1, a2, ..., al} — is a correct bracket sequence, then sequence  also is a correct bracket sequence, where v (v > 0) is an integer. For example, sequences {1, 1,  - 1, 2,  - 2,  - 1} and {3,  - 3} are correct bracket sequences, and {2,  - 3} is not.Moreover, after Vova became a shaman, he learned the most important correct bracket sequence {x1, x2, ..., xn}, consisting of n integers. As sequence x is the most important, Vova decided to encrypt it just in case.Encrypting consists of two sequences. The first sequence {p1, p2, ..., pn} contains types of brackets, that is, pi = |xi| (1 ≤ i ≤ n). The second sequence {q1, q2, ..., qt} contains t integers — some positions (possibly, not all of them), which had negative numbers in sequence {x1, x2, ..., xn}.Unfortunately, Vova forgot the main sequence. But he was lucky enough to keep the encryption: sequences {p1, p2, ..., pn} and {q1, q2, ..., qt}. Help Vova restore sequence x by the encryption. If there are multiple sequences that correspond to the encryption, restore any of them. If there are no such sequences, you should tell so.

The first line of the input contains integer n (1 ≤ n ≤ 106). The second line contains n integers: p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains integer t (0 ≤ t ≤ n), followed by t distinct integers q1, q2, ..., qt (1 ≤ qi ≤ n). The numbers in each line are separated by spaces.

Print a single string "NO" (without the quotes) if Vova is mistaken and a suitable sequence {x1, x2, ..., xn} doesn't exist. Otherwise, in the first line print "YES" (without the quotes) and in the second line print n integers x1, x2, ..., xn (|xi| = pi; xqj < 0). If there are multiple sequences that correspond to the encrypting, you are allowed to print any of them.

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');
			}
		}
	}
}


Ivan is reading a book about tournaments. He knows that a tournament is an oriented graph with exactly one oriented edge between each pair of vertices. The score of a vertex is the number of edges going outside this vertex. Yesterday Ivan learned Landau's criterion: there is tournament with scores d1 ≤ d2 ≤ ... ≤ dn if and only if  for all 1 ≤ k < n and .Now, Ivan wanna solve following problem: given a set of numbers S = {a1, a2, ..., am}, is there a tournament with given set of scores? I.e. is there tournament with sequence of scores d1, d2, ..., dn such that if we remove duplicates in scores, we obtain the required set {a1, a2, ..., am}? Find a tournament with minimum possible number of vertices.

The first line contains a single integer m (1 ≤ m ≤ 31). The next line contains m distinct integers a1, a2, ..., am (0 ≤ ai ≤ 30) — elements of the set S. It is guaranteed that all elements of the set are distinct.

If there are no such tournaments, print string "=(" (without quotes). Otherwise, print an integer n — the number of vertices in the tournament. Then print n lines with n characters — matrix of the tournament. The j-th element in the i-th row should be 1 if the edge between the i-th and the j-th vertices is oriented towards the j-th vertex, and 0 otherwise. The main diagonal should contain only zeros.

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)); }

/*
  \sum d_i = n (n - 1) / 2
  30 >= (\sum d_i) / n = (n - 1) / 2
*/

enum LIM_N = 70;
enum LIM_S = LIM_N * LIM_N / 2 + 1;

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

      auto dp = new bool[][][](M + 1, LIM_N, LIM_S);
      dp[0][0][0] = true;
      foreach (i; 0 .. M) {
        foreach (n; 0 .. LIM_N - 1) {
          foreach (s; 0 .. LIM_S - A[i]) {
            if (dp[i][n][s] || dp[i + 1][n][s]) {
              dp[i + 1][n + 1][s + A[i]] = true;
            }
          }
        }
        foreach (n; 0 .. LIM_N) {
          dp[i + 1][n][0 .. n * (n - 1) / 2] = false;
        }
      }

      foreach (N; 0 .. LIM_N) {
        if (dp[M][N][N * (N - 1) / 2]) {
          int[] deg;
          for (int i = M, n = N, s = N * (N - 1) / 2; i--; ) {
            do {
              deg ~= A[i];
              n -= 1;
              s -= A[i];
            } while (!dp[i][n][s]);
          }
          deg.reverse;
          debug {
            writeln("deg = ", deg);
          }
          auto ans = new bool[][](N, N);
          foreach (u; 0 .. N) {
            assert(0 <= deg[u] && deg[u] <= N - u - 1);
            alias Entry = Tuple!(int, int);
            Entry[] es;
            foreach (v; u + 1 .. N) {
              es ~= Entry(deg[v], v);
            }
            es.sort;
            foreach (j; 0 .. N - u - 1) {
              const v = es[j][1];
              if (j < deg[u]) {
                ans[u][v] = true;
              } else {
                ans[v][u] = true;
                --deg[v];
              }
            }
          }
          writeln(N);
          foreach (u; 0 .. N) {
            foreach (v; 0 .. N) {
              write(ans[u][v] ? 1 : 0);
            }
            writeln;
          }
          goto found;
        }
      }
      writeln("=(");
     found:
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

/*
  \sum d_i = n (n - 1) / 2
  30 >= (\sum d_i) / n = (n - 1) / 2
*/

enum LIM_N = 70;
enum LIM_S = LIM_N * LIM_N / 2 + 1;

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

      auto dp = new bool[][][](M + 1, LIM_N, LIM_S);
      dp[0][0][0] = true;
      foreach (i; 0 .. M) {
        foreach (n; 0 .. LIM_N - 1) {
          foreach (s; 0 .. LIM_S - A[i]) {
            if (dp[i][n][s] || dp[i + 1][n][s]) {
              dp[i + 1][n + 1][s + A[i]] = true;
            }
          }
        }
        foreach (n; 0 .. LIM_N) {
          dp[i + 1][n][0 .. n * (n - 1) / 2] = false;
        }
      }

      foreach (N; 0 .. LIM_N) {
        if (dp[M][N][N * (N - 1) / 2]) {
          int[] deg;
          for (int i = M, n = N, s = N * (N - 1) / 2; i--; ) {
            do {
              deg ~= A[i];
              n -= 1;
              s -= A[i];
            } while (!dp[i][n][s]);
          }
          deg.reverse;
          debug {
            writeln("deg = ", deg);
          }
          auto ans = new bool[][](N, N);
          foreach (u; 0 .. N) {
            assert(u + 1 + deg[u] <= N);
            foreach (v; u + 1 .. u + 1 + deg[u]) {
              ans[u][v] = true;
            }
            foreach (v; u + 1 + deg[u] .. N) {
              ans[v][u] = true;
              --deg[v];
            }
          }
          writeln(N);
          foreach (u; 0 .. N) {
            foreach (v; 0 .. N) {
              write(ans[u][v] ? 1 : 0);
            }
            writeln;
          }
          goto found;
        }
      }
      writeln("=(");
     found:
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

/*
  \sum d_i = n (n - 1) / 2
  30 >= (\sum d_i) / n = (n - 1) / 2
*/

enum LIM_N = 70;
enum LIM_S = LIM_N * LIM_N / 2 + 1;

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

      auto dp = new bool[][][](M + 1, LIM_N, LIM_S);
      dp[0][0][0] = true;
      foreach (i; 0 .. M) {
        foreach (n; 0 .. LIM_N - 1) {
          foreach (s; 0 .. LIM_S - A[i]) {
            if (dp[i][n][s] || dp[i + 1][n][s]) {
              dp[i + 1][n + 1][s + A[i]] = true;
            }
          }
        }
        foreach (n; 0 .. LIM_N) {
          dp[i + 1][n][0 .. n * (n - 1) / 2] = false;
        }
      }

      foreach (N; 0 .. LIM_N) {
        if (dp[M][N][N * (N - 1) / 2]) {
          int[] deg;
          for (int i = M, n = N, s = N * (N - 1) / 2; i--; ) {
            do {
              deg ~= A[i];
              n -= 1;
              s -= A[i];
            } while (!dp[i][n][s]);
          }
          deg.reverse;
          debug {
            writeln("deg = ", deg);
          }
          auto ans = new bool[][](N, N);
          foreach (u; 0 .. N) {
            debug {
              writeln("deg = ", deg);
            }
            assert(0 <= deg[u] && deg[u] <= N - u - 1);
            foreach (v; u + 1 .. u + 1 + deg[u]) {
              ans[u][v] = true;
            }
            foreach (v; u + 1 + deg[u] .. N) {
              ans[v][u] = true;
              --deg[v];
            }
            deg[u + 1 .. N].sort;
          }
          writeln(N);
          foreach (u; 0 .. N) {
            foreach (v; 0 .. N) {
              write(ans[u][v] ? 1 : 0);
            }
            writeln;
          }
          goto found;
        }
      }
      writeln("=(");
     found:
    }
  } catch (EOFException e) {
  }
}


The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive.All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city x to any other city contains at most one bad road.Your task is — for every possible x determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1 000 000 007 (109 + 7).

The first line of the input contains a single integer n (2 ≤ n ≤ 2·105) — the number of cities in the country. Next line contains n - 1 positive integers p2, p3, p4, ..., pn (1 ≤ pi ≤ i - 1) — the description of the roads in the country. Number pi means that the country has a road connecting city pi and city i.

Print n integers a1, a2, ..., an, where ai is the sought number of ways to improve the quality of the roads modulo 1 000 000 007 (109 + 7), if the capital of the country is at city number i.

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);
	}
}


Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers.Subarray a[i... j] (1 ≤ i ≤ j ≤ n) of array a = (a1, a2, ..., an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j] = (ai, ai + 1, ..., aj).

The first line contains two space-separated integers n, k (1 ≤ k ≤ n ≤ 4·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly.  The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — elements of the array.

Print the single number — the number of such subarrays of array a, that they have at least k equal integers. Please do not use the %lld specifier to read or write 64-bit integers in С++. In is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2).In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1).In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).

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]);
  auto n = next!int;
  auto k = next!int;
  auto a = next!int(n);
  auto pk = new int[](n);
  pk[] = -1;
  DList!int[int] posl;
  int[int] posllen;
  foreach(i, ai; a)
    {
      posl.require(ai, DList!int());
      posllen.require(ai, 0);
      posl[ai].insertBack(cast(int)i);
      posllen[ai]++;
      while(posllen[ai] > k)
	{
	  posl[ai].removeFront;
	  posllen[ai]--;
	}
      if (posllen[ai] == k)
	pk[i] = posl[ai].front;
    }
  int mx = -1;
  long cnt = 0;
  foreach(i, pi; pk)
    {
      mx = max(mx, pi);
      cnt += (mx + 1);
    }
  cnt.writeln;
}

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


You've got string s, consisting of small English letters. Some of the English letters are good, the rest are bad.A substring s[l...r] (1 ≤ l ≤ r ≤ |s|) of string s  =  s1s2...s|s| (where |s| is the length of string s) is string  slsl + 1...sr.The substring s[l...r] is good, if among the letters  sl, sl + 1, ..., sr there are at most k bad ones (look at the sample's explanation to understand it more clear).Your task is to find the number of distinct good substrings of the given string s. Two substrings s[x...y] and s[p...q] are considered distinct if their content is different, i.e. s[x...y] ≠ s[p...q].

The first line of the input is the non-empty string s, consisting of small English letters, the string's length is at most 1500 characters. The second line of the input is the string of characters "0" and "1", the length is exactly 26 characters. If the i-th character of this string equals "1", then the i-th English letter is good, otherwise it's bad. That is, the first character of this string corresponds to letter "a", the second one corresponds to letter "b" and so on. The third line of the input consists a single integer k (0 ≤ k ≤ |s|) — the maximum acceptable number of bad characters in a good substring.

Print a single integer — the number of distinct good substrings of string s.

NoteIn the first example there are following good substrings: "a", "ab", "b", "ba", "bab".In the second example there are following good substrings: "a", "aa", "ac", "b", "ba", "c", "ca", "cb".

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 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 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 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);
    }
}


The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dn - 1 is the distance between the n - 1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.

The first line contains integer n (3 ≤ n ≤ 100) — the number of stations on the circle line. The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 100) — the distances between pairs of neighboring stations. The third line contains two integers s and t (1 ≤ s, t ≤ n) — the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces.

Print a single number — the length of the shortest path between stations number s and t.

NoteIn the first sample the length of path 1 → 2 → 3 equals 5, the length of path 1 → 4 → 3 equals 13.In the second sample the length of path 4 → 1 is 100, the length of path 4 → 3 → 2 → 1 is 15.In the third sample the length of path 3 → 1 is 1, the length of path 3 → 2 → 1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0.

import std.algorithm;
import std.stdio;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		a ~= a;
		int s, t;
		readf (" %s %s", &s, &t);
		if (s > t)
		{
			swap (s, t);
		}
		s--;
		t--;
		int res = int.max;
		int d;
		d = 0;
		foreach (i; s..t)
		{
			d += a[i];
		}
		res = min (res, d);
		d = 0;
		foreach (i; t..s + n)
		{
			d += a[i];
		}
		res = min (res, d);
		writeln (res);
	}
}


A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show.The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions:  Is it true that y is strictly larger than number x?  Is it true that y is strictly smaller than number x?  Is it true that y is larger than or equal to number x?  Is it true that y is smaller than or equal to number x? On each question the host answers truthfully, "yes" or "no".Given the sequence of questions and answers, find any integer value of y that meets the criteria of all answers. If there isn't such value, print "Impossible".

The first line of the input contains a single integer n (1 ≤ n ≤ 10000) — the number of questions (and answers). Next n lines each contain one question and one answer to it. The format of each line is like that: "sign x answer", where the sign is:   ">" (for the first type queries),  "<" (for the second type queries),  ">=" (for the third type queries),  "<=" (for the fourth type queries).  All values of x are integer and meet the inequation  - 109 ≤ x ≤ 109. The answer is an English letter "Y" (for "yes") or "N" (for "no"). Consequtive elements in lines are separated by a single space.

Print any of such integers y, that the answers to all the queries are correct. The printed number y must meet the inequation  - 2·109 ≤ y ≤ 2·109. If there are many answers, print any of them. If such value doesn't exist, print word "Impossible" (without the quotes).

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

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

    auto rels = ["<", ">=", ">", "<="];
    int lo = to!int(-2e9), hi = to!int(2e9);
    foreach(i; 0..n) {
        string tp, yn;
        int x;
        readf(" %s %s %s\n", &tp, &x, &yn);
        auto pos = rels.find(tp).ptr - rels.ptr;
        if (yn == "N") {
            pos ^= 1;
        }
        final switch (pos) {
            case 0: hi = min(hi, x - 1); break;
            case 1: lo = max(lo, x); break;
            case 2: lo = max(lo, x + 1); break;
            case 3: hi = min(hi, x);
        }
    }

    if (lo <= hi) {
        writeln(lo);
    } else {
        writeln("Impossible");
    }
}

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

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

    auto rels = ["<", ">=", ">", "<="];
    int lo = to!int(-2e9), hi = to!int(2e9);
    foreach(i; 0..n) {
        string tp, yn;
        int x;
        readf(" %s %s %s\n", &tp, &x, &yn);
        auto pos = rels.find(tp).ptr - rels.ptr;
        if (yn == "N") {
            pos ^= 1;
        }
        final switch (pos) {
            case 0: hi = x - 1; break;
            case 1: lo = x; break;
            case 2: lo = x + 1; break;
            case 3: hi = x;
        }
    }

    if (lo <= hi) {
        writeln(lo);
    } else {
        writeln("Impossible");
    }
}


Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.

The first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.

Print a single number — the number of distinct letters in Anton's set.

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.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 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 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) {}
}


We say that a positive integer $$$n$$$ is $$$k$$$-good for some positive integer $$$k$$$ if $$$n$$$ can be expressed as a sum of $$$k$$$ positive integers which give $$$k$$$ distinct remainders when divided by $$$k$$$.Given a positive integer $$$n$$$, find some $$$k \geq 2$$$ so that $$$n$$$ is $$$k$$$-good or tell that such a $$$k$$$ does not exist.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. Each test case consists of one line with an integer $$$n$$$ ($$$2 \leq n \leq 10^{18}$$$).

For each test case, print a line with a value of $$$k$$$ such that $$$n$$$ is $$$k$$$-good ($$$k \geq 2$$$), or $$$-1$$$ if $$$n$$$ is not $$$k$$$-good for any $$$k$$$. If there are multiple valid values of $$$k$$$, you can print any of them.

Note$$$6$$$ is a $$$3$$$-good number since it can be expressed as a sum of $$$3$$$ numbers which give different remainders when divided by $$$3$$$: $$$6 = 1 + 2 + 3$$$.$$$15$$$ is also a $$$3$$$-good number since $$$15 = 1 + 5 + 9$$$ and $$$1, 5, 9$$$ give different remainders when divided by $$$3$$$.$$$20$$$ is a $$$5$$$-good number since $$$20 = 2 + 3 + 4 + 5 + 6$$$ and $$$2,3,4,5,6$$$ give different remainders when divided by $$$5$$$.

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);
    }
}


The only difference between easy and hard versions is constraints.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive integers.Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are $$$a$$$ and $$$b$$$, $$$a$$$ can be equal $$$b$$$) and is as follows: $$$[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$$$. There $$$x, y$$$ are integers greater than or equal to $$$0$$$. For example, sequences $$$[]$$$, $$$[2]$$$, $$$[1, 1]$$$, $$$[1, 2, 1]$$$, $$$[1, 2, 2, 1]$$$ and $$$[1, 1, 2, 1, 1]$$$ are three block palindromes but $$$[1, 2, 3, 2, 1]$$$, $$$[1, 2, 1, 2, 1]$$$ and $$$[1, 2]$$$ are not.Your task is to choose the maximum by length subsequence of $$$a$$$ that is a three blocks palindrome.You have to answer $$$t$$$ independent test cases.Recall that the sequence $$$t$$$ is a a subsequence of the sequence $$$s$$$ if $$$t$$$ can be derived from $$$s$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$s=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 26$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. Note that the maximum value of $$$a_i$$$ can be up to $$$26$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$).

For each test case, print the answer — the maximum possible length of some subsequence of $$$a$$$ that is a three blocks palindrome.

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