Kawashiro Nitori is a girl who loves competitive programming. One day she found a rooted tree consisting of $$$n$$$ vertices. The root is vertex $$$1$$$. As an advanced problem setter, she quickly thought of a problem.Kawashiro Nitori has a vertex set $$$U=\{1,2,\ldots,n\}$$$. She's going to play a game with the tree and the set. In each operation, she will choose a vertex set $$$T$$$, where $$$T$$$ is a partial virtual tree of $$$U$$$, and change $$$U$$$ into $$$T$$$.A vertex set $$$S_1$$$ is a partial virtual tree of a vertex set $$$S_2$$$, if $$$S_1$$$ is a subset of $$$S_2$$$, $$$S_1 \neq S_2$$$, and for all pairs of vertices $$$i$$$ and $$$j$$$ in $$$S_1$$$, $$$\operatorname{LCA}(i,j)$$$ is in $$$S_1$$$, where $$$\operatorname{LCA}(x,y)$$$ denotes the lowest common ancestor of vertices $$$x$$$ and $$$y$$$ on the tree. Note that a vertex set can have many different partial virtual trees.Kawashiro Nitori wants to know for each possible $$$k$$$, if she performs the operation exactly $$$k$$$ times, in how many ways she can make $$$U=\{1\}$$$ in the end? Two ways are considered different if there exists an integer $$$z$$$ ($$$1 \le z \le k$$$) such that after $$$z$$$ operations the sets $$$U$$$ are different.Since the answer could be very large, you need to find it modulo $$$p$$$. It's guaranteed that $$$p$$$ is a prime number.

The first line contains two integers $$$n$$$ and $$$p$$$ ($$$2 \le n \le 2000$$$, $$$10^8 + 7 \le p \le 10^9+9$$$). It's guaranteed that $$$p$$$ is a prime number. Each of the next $$$n-1$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing an edge between $$$u_i$$$ and $$$v_i$$$. It is guaranteed that the given edges form a tree.

The only line contains $$$n-1$$$ integers — the answer modulo $$$p$$$ for $$$k=1,2,\ldots,n-1$$$.

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

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

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

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

struct ModInt {
  static int M;
  import std.conv : to;
  uint x;
  this(ModInt a) { x = a.x; }
  this(uint x_) { x = x_ % M; }
  this(ulong x_) { x = cast(uint)(x_ % M); }
  this(int x_) { x = ((x_ %= cast(int)(M)) < 0) ? (x_ + cast(int)(M)) : x_; }
  this(long x_) { x = cast(uint)(((x_ %= cast(long)(M)) < 0) ? (x_ + cast(long)(M)) : x_); }
  ref ModInt opAssign(T)(inout(T) a) if (is(T == uint) || is(T == ulong) || is(T == int) || is(T == long)) { return this = ModInt(a); }
  ref ModInt opOpAssign(string op, T)(T a) {
    static if (is(T == ModInt)) {
      static if (op == "+") { x = ((x += a.x) >= M) ? (x - M) : x; }
      else static if (op == "-") { x = ((x -= a.x) >= M) ? (x + M) : x; }
      else static if (op == "*") { x = cast(uint)((cast(ulong)(x) * a.x) % M); }
      else static if (op == "/") { this *= a.inv(); }
      else static assert(false);
      return this;
    } else static if (op == "^^") {
      if (a < 0) return this = inv()^^(-a);
      ModInt b = this, c = 1U;
      for (long e = a; e; e >>= 1) { if (e & 1) c *= b; b *= b; }
      return this = c;
    } else {
      return mixin("this " ~ op ~ "= ModInt(a)");
    }
  }
  ModInt inv() const {
    uint a = M, b = x; int y = 0, z = 1;
    for (; b; ) { const q = a / b; const c = a - q * b; a = b; b = c; const w = y - cast(int)(q) * z; y = z; z = w; }
    assert(a == 1); return ModInt(y);
  }
  ModInt opUnary(string op)() const {
    static if (op == "+") { return this; }
    else static if (op == "-") { ModInt a; a.x = x ? (M - x) : 0U; return a; }
    else static assert(false);
  }
  ModInt opBinary(string op, T)(T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op, T)(T a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  bool opCast(T: bool)() const { return (x != 0U); }
  string toString() const { return x.to!string; }
}

alias Mint = ModInt;

enum LIM_INV = 4010;
Mint[] inv, fac, invFac;
void prepare() {
  inv = new Mint[LIM_INV];
  fac = new Mint[LIM_INV];
  invFac = new Mint[LIM_INV];
  inv[1] = 1;
  foreach (i; 2 .. LIM_INV) {
    inv[i] = -((Mint.M / i) * inv[cast(size_t)(Mint.M % i)]);
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM_INV) {
    fac[i] = fac[i - 1] * i;
    invFac[i] = invFac[i - 1] * inv[i];
  }
}
Mint binom(long n, long k) {
  if (n < 0) {
    if (k >= 0) {
      return (-1)^^(k & 1) * binom(-n + k - 1, k);
    } else if (n - k >= 0) {
      return (-1)^^((n - k) & 1) * binom(-k - 1, n - k);
    } else {
      return Mint(0);
    }
  } else {
    if (0 <= k && k <= n) {
      assert(n < LIM_INV);
      return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] * invFac[cast(size_t)(n - k)];
    } else {
      return Mint(0);
    }
  }
}

int N;
int[] A, B;

int[][] G;
// max <= k
Mint[][] dp;

void dfs(int u, int p) {
  int[] vs;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      vs ~= v;
    }
  }
  const len = cast(int)(vs.length);
  foreach (v; vs) {
    dfs(v, u);
  }

  auto lss = new Mint[][](len + 1, N);
  auto rss = new Mint[][](len + 1, N);
  lss[0][] = Mint(1);
  foreach (j; 0 .. len) foreach (k; 0 .. N) {
    lss[j + 1][k] = lss[j][k] * dp[vs[j]][k];
  }
  rss[len][] = Mint(1);
  foreach_reverse (j; 0 .. len) foreach (k; 0 .. N) {
    rss[j][k] = dp[vs[j]][k] * rss[j + 1][k];
  }

  // max <= here
  foreach (k; 0 .. N) {
    dp[u][k] += rss[0][k];
  }

  // 2nd <= here < max
  if (~p) {
    foreach (j; 0 .. len) {
      const v = vs[j];
      Mint sum;
      foreach (k; 0 .. N) {
        dp[u][k] += (k ? (dp[v][k] - dp[v][k - 1]) : dp[v][k]) * sum;
        sum += lss[j][k] * rss[j + 1][k];
      }
    }
    foreach (k; 1 .. N) {
      dp[u][k] += dp[u][k - 1];
    }
  }

  debug {
    writeln(u, ": ", dp[u]);
  }
}

void main() {
  try {
    for (; ; ) {
      N = readInt;
      Mint.M = readInt;
      prepare;

      A = new int[N - 1];
      B = new int[N - 1];
      foreach (i; 0 .. N - 1) {
        A[i] = readInt - 1;
        B[i] = readInt - 1;
      }

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      dp = new Mint[][](N, N);
      dfs(0, -1);

      auto ans = dp[0].dup;
      foreach (k; 0 .. N) {
        foreach (l; 0 .. k) {
          ans[k] -= binom(k + 1, l + 1) * ans[l];
        }
      }

      foreach (k; 0 .. N - 1) {
        if (k) write(" ");
        write(ans[k]);
      }
      writeln;
    }
  } catch (EOFException e) {
  }
}


You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells:   $$$(i - 1, j - 1)$$$;  $$$(i - 1, j)$$$;  $$$(i - 1, j + 1)$$$;  $$$(i, j - 1)$$$;  $$$(i, j + 1)$$$;  $$$(i + 1, j - 1)$$$;  $$$(i + 1, j)$$$;  $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n < 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).

For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		long res = 0;
		foreach (i; 1..n / 2 + 1)
		{
			res += i * 8L * i;
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (i; 0..n/2)
		{
			auto size = n - (i*2);
			auto cnt = size * 2 + (size-2) * 2;
			auto d = n/2 - i;
			ans[ti] += cnt * d;
		}
	}

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


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Each $$$a_i$$$ is one of the six following numbers: $$$4, 8, 15, 16, 23, 42$$$.Your task is to remove the minimum number of elements to make this array good.An array of length $$$k$$$ is called good if $$$k$$$ is divisible by $$$6$$$ and it is possible to split it into $$$\frac{k}{6}$$$ subsequences $$$4, 8, 15, 16, 23, 42$$$.Examples of good arrays:  $$$[4, 8, 15, 16, 23, 42]$$$ (the whole array is a required sequence);  $$$[4, 8, 4, 15, 16, 8, 23, 15, 16, 42, 23, 42]$$$ (the first sequence is formed from first, second, fourth, fifth, seventh and tenth elements and the second one is formed from remaining elements);  $$$[]$$$ (the empty array is good). Examples of bad arrays:   $$$[4, 8, 15, 16, 42, 23]$$$ (the order of elements should be exactly $$$4, 8, 15, 16, 23, 42$$$);  $$$[4, 8, 15, 16, 23, 42, 4]$$$ (the length of the array is not divisible by $$$6$$$);  $$$[4, 8, 15, 16, 23, 42, 4, 8, 15, 16, 23, 23]$$$ (the first sequence can be formed from first six elements but the remaining array cannot form the required sequence).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ (each $$$a_i$$$ is one of the following numbers: $$$4, 8, 15, 16, 23, 42$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum number of elements you have to remove to obtain a good array.

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee, enumerate;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;
import std.math;

alias Tree = RBT!int;
alias ll = long;

void main() {
  GC.disable();

  int n;
  readf(" %s", n);
  int[] a = new int[n];
  int[] v = new int[n];
  v[] =0;
  foreach(i;0..n) readf(" %s", a[i]);

  int[] nn =[4, 8, 15, 16, 23, 42];
  int[] aa;
  int ii = 0;
  int cc = 0;
  int[6] sii;
  sii[] = 0;
  int i;
  i =0;
  while(i < n) {
    if (v[i] == 0 && a[i] == nn[ii]) {
      cc++;
      v[i] = 1;
      sii[ii] = i;
      ii = (ii+1) % nn.length;
      i = sii[0 .. ii+1].maxElement;
    }
    i++;
  }

  writeln(n - (cc/6)*6);

}

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

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto a = RDR.ARR;
	auto toI = [4:0, 8:1, 15:2, 16:3, 23:4, 42:5];
	auto cnt = new long[](6);
	foreach (i; 0..n)
	{
		auto pos = toI[cast(int)a[i]];
		bool ok = true;
		foreach (j; 0..pos)
		{
			if (cnt[j] <= cnt[pos])
			{
				ok = false;
				break;
			}
		}
		if (ok)
			++cnt[pos];
	}
	long ans;
	ans = n - (cnt[$-1]*6);

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

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee, enumerate;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;
import std.math;

alias Tree = RBT!int;
alias ll = long;

void main() {
  GC.disable();

  int n;
  readf(" %s", n);
  int[] a = new int[n];
  int[] v = new int[n];
  v[] =0;
  foreach(i;0..n) readf(" %s", a[i]);

  int[] nn =[4, 8, 15, 16, 23, 42];
  int[] aa;
  int ii = 0;
  int cc = 0;
  int[6] sii;
  int i;
  i =0;
  while(i < n) {
    if (v[i] == 0 && a[i] == nn[ii]) {
      sii[ii] = i;
      ii = (ii+1) % nn.length;
      cc++;
      v[i] = 1;
      i = sii[ii];
    }
    i++;
  }

  writeln(n - (cc/6)*6);

}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee, enumerate;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;
import std.math;

alias Tree = RBT!int;
alias ll = long;

void main() {
  GC.disable();

  int n;
  readf(" %s", n);
  int[] a = new int[n];
  foreach(i;0..n) readf(" %s", a[i]);

  int[] nn =[4, 8, 15, 16, 23, 42];
  int[] aa;
  int ii = 0;
  int cc = 0;
  foreach(e; a) {
    if (e == nn[ii]) {
      ii = (ii+1) % nn.length;
      cc++;
    }
  }

  writeln(n - (cc/6)*6);

}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee, enumerate;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;
import std.math;

alias Tree = RBT!int;
alias ll = long;

void main() {
  GC.disable();

  int n;
  readf(" %s", n);
  int[] a = new int[n];
  int[] v = new int[n];
  v[] =0;
  foreach(i;0..n) readf(" %s", a[i]);

  int[] nn =[4, 8, 15, 16, 23, 42];
  int[] aa;
  int ii = 0;
  int cc = 0;
  int[6] sii;
  sii[] = 0;
  int i;
  i =0;
  while(i < n) {
    if (v[i] == 0 && a[i] == nn[ii]) {
      sii[ii] = i;
      ii = (ii+1) % nn.length;
      cc++;
      v[i] = 1;
      i = sii[ii];
    }
    i++;
  }

  writeln(n - (cc/6)*6);

}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee, enumerate;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;
import std.math;

alias Tree = RBT!int;
alias ll = long;

void main() {
  GC.disable();

  int n;
  readf(" %s", n);
  int[] a = new int[n];
  foreach(i;0..n) readf(" %s", a[i]);

  int[] nn =[4, 8, 15, 16, 23, 42];
  int[] aa;
  int ii = 0;
  int cc = 0;
  foreach(e; a) {
    if (e == nn[ii]) {
      ii = (ii+1) % nn.length;
      cc++;
    }
  }

  writeln(n - (n/6)*6);

}

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

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

long mod = 10^^9 + 7;
//long mod = 998244353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto a = RDR.ARR;
	auto toI = [4:0, 8:1, 15:2, 16:3, 23:4, 42:5];
	auto cnt = new long[](6);
	long ans;
	foreach (i; 0..n)
	{
		auto pos = toI[cast(int)a[i]];
		bool ok = true;
		foreach (j; 0..pos)
		{
			if (cnt[j] <= cnt[pos])
			{
				ok = false;
				break;
			}
		}
		if (ok)
			++cnt[pos];
		else
			++ans;
	}
	debug writeln(ans);
	ans += (n-ans) % 6;

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


You are given a string $$$s$$$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $$$s$$$ such that it contains each of these three characters at least once.A contiguous substring of string $$$s$$$ is a string that can be obtained from $$$s$$$ by removing some (possibly zero) characters from the beginning of $$$s$$$ and some (possibly zero) characters from the end of $$$s$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 20000$$$) — the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \le |s| \le 200000$$$). It is guaranteed that each character of $$$s$$$ is either 1, 2, or 3. The sum of lengths of all strings in all test cases does not exceed $$$200000$$$.

For each test case, print one integer — the length of the shortest contiguous substring of $$$s$$$ containing all three types of characters at least once. If there is no such substring, print $$$0$$$ instead.

NoteConsider the example test:In the first test case, the substring 123 can be used.In the second test case, the substring 213 can be used.In the third test case, the substring 1223 can be used.In the fourth test case, the substring 3221 can be used.In the fifth test case, there is no character 3 in $$$s$$$.In the sixth test case, there is no character 1 in $$$s$$$.In the seventh test case, the substring 3112 can be used.

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto S = readln.chomp;
        auto len = S.length;
        auto l1 = new size_t[](len);
        auto r1 = new size_t[](len);
        auto l2 = new size_t[](len);
        auto r2 = new size_t[](len);
        auto l3 = new size_t[](len);
        auto r3 = new size_t[](len);

        auto i1 = len, i2 = len, i3 = len;
        foreach (i, c; S) {
            switch (c) {
                case '1': i1 = i; break;
                case '2': i2 = i; break;
                default: i3 = i;
            }
            l1[i] = i1;
            l2[i] = i2;
            l3[i] = i3;
        }
        i1 = len, i2 = len, i3 = len;
        foreach_reverse (i, c; S) {
            switch (c) {
                case '1': i1 = i; break;
                case '2': i2 = i; break;
                default: i3 = i;
            }
            r1[i] = i1;
            r2[i] = i2;
            r3[i] = i3;
        }

        auto res = size_t.max;
        foreach (i; 0..len) {
            switch (S[i]) {
                case '1':
                    if (l2[i] != len && r3[i] != len) {
                        res = min(res, r3[i] - l2[i] + 1);
                    }
                    if (l3[i] != len && r2[i] != len) {
                        res = min(res, r2[i] - l3[i] + 1);
                    }
                    break;
                case '2':
                    if (l1[i] != len && r3[i] != len) {
                        res = min(res, r3[i] - l1[i] + 1);
                    }
                    if (l3[i] != len && r1[i] != len) {
                        res = min(res, r1[i] - l3[i] + 1);
                    }
                    break;
                default:
                    if (l2[i] != len && r1[i] != len) {
                        res = min(res, r1[i] - l2[i] + 1);
                    }
                    if (l1[i] != len && r2[i] != len) {
                        res = min(res, r2[i] - l1[i] + 1);
                    }
            }
        }
        writeln(res == size_t.max ? 0 : 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)); }

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

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

		auto cnt = new long[][](s.length+1, 3);
		foreach (i; 0..s.length)
		{
			auto num = s[i]-'1';
			cnt[i+1] = cnt[i].dup;
			++cnt[i+1][num];
		}

		int tmp = int.max;
		foreach (int i; 0..cast(int)s.length)
		{
			bool f(int j)
			{
				auto x = cnt[j].dup;
				x[] -= cnt[i][];
				return x[0] != 0 && x[1] != 0 && x[2] != 0;
			}
			auto r = binarySearch!(f)(cast(int)s.length+1, i);
			if (r != s.length+1)
			{
				tmp.chmin(r-i);
			}
		}
		if (tmp != int.max)
		{
			ans[ti] = tmp;
		}
	}

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


It has finally been decided to build a roof over the football field in School 179. Its construction will require placing $$$n$$$ consecutive vertical pillars. Furthermore, the headmaster wants the heights of all the pillars to form a permutation $$$p$$$ of integers from $$$0$$$ to $$$n - 1$$$, where $$$p_i$$$ is the height of the $$$i$$$-th pillar from the left $$$(1 \le i \le n)$$$.As the chief, you know that the cost of construction of consecutive pillars is equal to the maximum value of the bitwise XOR of heights of all pairs of adjacent pillars. In other words, the cost of construction is equal to $$$\max\limits_{1 \le i \le n - 1}{p_i \oplus p_{i + 1}}$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.Find any sequence of pillar heights $$$p$$$ of length $$$n$$$ with the smallest construction cost.In this problem, a permutation is an array consisting of $$$n$$$ distinct integers from $$$0$$$ to $$$n - 1$$$ in arbitrary order. For example, $$$[2,3,1,0,4]$$$ is a permutation, but $$$[1,0,1]$$$ is not a permutation ($$$1$$$ appears twice in the array) and $$$[1,0,3]$$$ is also not a permutation ($$$n=3$$$, but $$$3$$$ is in the array).

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The only line for each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of pillars for the construction of the roof. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_n$$$ — the sequence of pillar heights with the smallest construction cost. If there are multiple answers, print any of them.

NoteFor $$$n = 2$$$ there are $$$2$$$ sequences of pillar heights:   $$$[0, 1]$$$ — cost of construction is $$$0 \oplus 1 = 1$$$.  $$$[1, 0]$$$ — cost of construction is $$$1 \oplus 0 = 1$$$. For $$$n = 3$$$ there are $$$6$$$ sequences of pillar heights:   $$$[0, 1, 2]$$$ — cost of construction is $$$\max(0 \oplus 1, 1 \oplus 2) = \max(1, 3) = 3$$$.  $$$[0, 2, 1]$$$ — cost of construction is $$$\max(0 \oplus 2, 2 \oplus 1) = \max(2, 3) = 3$$$.  $$$[1, 0, 2]$$$ — cost of construction is $$$\max(1 \oplus 0, 0 \oplus 2) = \max(1, 2) = 2$$$.  $$$[1, 2, 0]$$$ — cost of construction is $$$\max(1 \oplus 2, 2 \oplus 0) = \max(3, 2) = 3$$$.  $$$[2, 0, 1]$$$ — cost of construction is $$$\max(2 \oplus 0, 0 \oplus 1) = \max(2, 1) = 2$$$.  $$$[2, 1, 0]$$$ — cost of construction is $$$\max(2 \oplus 1, 1 \oplus 0) = \max(3, 1) = 3$$$.

import std;

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

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

        immutable most_significant_bit = 1 << cast(int)log2(n - 1);

        chain(
            iota(n - 1, most_significant_bit - 1, -1),
            iota(0, most_significant_bit)
        ).writefln!"%(%s %)";
    }
}
// ""


In "The Man in the High Castle" world, there are $$$m$$$ different film endings. Abendsen owns a storage and a shelf. At first, he has $$$n$$$ ordered films on the shelf. In the $$$i$$$-th month he will do: Empty the storage. Put $$$k_i \cdot m$$$ films into the storage, $$$k_i$$$ films for each ending. He will think about a question: if he puts all the films from the shelf into the storage, then randomly picks $$$n$$$ films (from all the films in the storage) and rearranges them on the shelf, what is the probability that sequence of endings in $$$[l_i, r_i]$$$ on the shelf will not be changed? Notice, he just thinks about this question, so the shelf will not actually be changed.Answer all Abendsen's questions.Let the probability be fraction $$$P_i$$$. Let's say that the total number of ways to take $$$n$$$ films from the storage for $$$i$$$-th month is $$$A_i$$$, so $$$P_i \cdot A_i$$$ is always an integer. Print for each month $$$P_i \cdot A_i \pmod {998244353}$$$.$$$998244353$$$ is a prime number and it is equal to $$$119 \cdot 2^{23} + 1$$$.It is guaranteed that there will be only no more than $$$100$$$ different $$$k$$$ values.

The first line contains three integers $$$n$$$, $$$m$$$, and $$$q$$$ ($$$1 \le n, m, q \le 10^5$$$, $$$n+q\leq 10^5$$$) — the number of films on the shelf initially, the number of endings, and the number of months. The second line contains $$$n$$$ integers $$$e_1, e_2, \ldots, e_n$$$ ($$$1\leq e_i\leq m$$$) — the ending of the $$$i$$$-th film on the shelf. Each of the next $$$q$$$ lines contains three integers $$$l_i$$$, $$$r_i$$$, and $$$k_i$$$ ($$$1 \le l_i \le r_i \le n, 0 \le k_i \le 10^5$$$) — the $$$i$$$-th query. It is guaranteed that there will be only no more than $$$100$$$ different $$$k$$$ values.

Print the answer for each question in a separate line.

NoteIn the first sample in the second query, after adding $$$2 \cdot m$$$ films into the storage, the storage will look like this: $$$\{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4\}$$$.There are $$$26730$$$ total ways of choosing the films so that $$$e_l, e_{l+1}, \ldots, e_r$$$ will not be changed, for example, $$$[1, 2, 3, 2, 2]$$$ and $$$[1, 2, 3, 4, 3]$$$ are such ways.There are $$$2162160$$$ total ways of choosing the films, so you're asked to print $$$(\frac{26730}{2162160} \cdot 2162160) \mod 998244353 = 26730$$$.

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

struct ModInt(int M_) {
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op)() const if (op == "-") { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op)(long a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  string toString() const { return x.to!string; }
}

enum MO = 998244353;
alias Mint = ModInt!MO;

enum LIM = 3 * 10^^5 + 20;
Mint[] inv, fac, invFac;
void prepare() {
  inv = new Mint[LIM];
  fac = new Mint[LIM];
  invFac = new Mint[LIM];
  inv[1] = 1;
  foreach (i; 2 .. LIM) {
    inv[i] = -(Mint.M / i) * inv[cast(size_t)(Mint.M % i)];
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM) {
    fac[i] = fac[i - 1] * i;
    invFac[i] = invFac[i - 1] * inv[i];
  }
}
Mint binom(long n, long k) {
  if (0 <= k && k <= n) {
    assert(n < LIM);
    return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] * invFac[cast(size_t)(n - k)];
  } else {
    return Mint(0);
  }
}

enum LIM_K = 10^^5 + 5;

void main() {
  prepare();

  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      const Q = readInt();
      auto E = new int[N];
      foreach (i; 0 .. N) {
        E[i] = readInt() - 1;
      }
      auto L = new int[Q];
      auto R = new int[Q];
      auto K = new int[Q];
      foreach (q; 0 .. Q) {
        L[q] = readInt() - 1;
        R[q] = readInt();
        K[q] = readInt();
      }

      debug {
        // brute
        writeln("brute");
        foreach (q; 0 .. Q) {
          auto as = new int[M];
          auto bs = new int[M];
          foreach (i; 0 .. N) {
            ++as[E[i]];
            if (L[q] <= i && i < R[q]) {
              ++bs[E[i]];
            }
          }
          Mint ans = 1;
          foreach (j; 0 .. M) {
            ans *= fac[K[q] + as[j]] * invFac[K[q] + as[j] - bs[j]];
          }
          foreach (i; R[q] - L[q] .. N) {
            ans *= (1L * K[q] * M + N - i);
          }
          writeln(ans);
        }
      }

      auto as = new int[M];
      foreach (i; 0 .. N) {
        ++as[E[i]];
      }

      class Query {
        int l, r;
        int id;
        int key0, key1;
        this(int l, int r, int id) {
          this.l = l;
          this.r = r;
          this.id = id;
        }
        override string toString() const {
          return format("[%s, %s)", l, r);
        }
      }
      auto queriess = new Query[][LIM_K];
      foreach (q; 0 .. Q) {
        queriess[K[q]] ~= new Query(L[q], R[q], q);
      }
      auto ans = new Mint[Q];
      foreach (k; 0 .. LIM_K) {
        auto queries = queriess[k];
        if (queries) {
          // suffix prod for (k M + N - 0) ... (k M + N - (N - 1))
          auto prod = new Mint[N + 1];
          prod[N] = 1;
          foreach_reverse (i; 0 .. N) {
            prod[i] = (1L * k * M + N - i) * prod[i + 1];
          }

          const queriesLen = cast(int)(queries.length);
          // int sz = cast(int)(sqrt(cast(real)(N)));
          // chmax(sz, 10^^5 / queriesLen);
          const sz = max(N / cast(int)(sqrt(cast(real)(queriesLen))), 1);
          foreach (q; queries) {
            q.key0 = q.l / sz;
            q.key1 = q.r;
            if (q.key0 % 2 != 0) {
              q.key1 *= -1;
            }
          }
          queries.sort!((a, b) => ((a.key0 != b.key0) ? (a.key0 < b.key0) : (a.key1 < b.key1)));
          debug {
            writeln("k = ", k, ", sz = ", sz);
            writeln("  queries = ", queries);
          }

          Mint now = 1;
          auto bs = new int[M];
          void add(int i) {
            const j = E[i];
            /*
            now *= fac[k + as[j] - bs[j]];
            ++bs[j];
            now *= invFac[k + as[j] - bs[j]];
            */
            now *= (k + as[j] - bs[j]);
            ++bs[j];
          }
          void rem(int i) {
            const j = E[i];
            /*
            now *= fac[k + as[j] - bs[j]];
            --bs[j];
            now *= invFac[k + as[j] - bs[j]];
            */
            --bs[j];
            now *= inv[k + as[j] - bs[j]];
          }

          int l, r;
          foreach (q; queries) {
            for (; l > q.l; ) add(--l);
            for (; r < q.r; ) add(r++);
            for (; l < q.l; ) rem(l++);
            for (; r > q.r; ) rem(--r);
            ans[q.id] = now * prod[q.r - q.l];
          }
        }
      }
      foreach (q; 0 .. Q) {
        writeln(ans[q]);
      }
    }
  } 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)); }

struct ModInt(int M_) {
  alias M = M_;
  int x;
  this(ModInt a) { x = a.x; }
  this(long a) { x = cast(int)(a % M); if (x < 0) x += M; }
  ref ModInt opAssign(long a) { return (this = ModInt(a)); }
  ref ModInt opOpAssign(string op)(ModInt a) {
    static if (op == "+") { x += a.x; if (x >= M) x -= M; }
    else static if (op == "-") { x -= a.x; if (x < 0) x += M; }
    else static if (op == "*") { x = cast(int)((cast(long)(x) * a.x) % M); }
    else static if (op == "/") { this *= a.inv(); }
    else static assert(false);
    return this;
  }
  ref ModInt opOpAssign(string op)(long a) {
    static if (op == "^^") {
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e; e >>= 1) {
        if (e & 1) te *= t2;
        t2 *= t2;
      }
      x = cast(int)(te.x);
      return this;
    } else return mixin("this " ~ op ~ "= ModInt(a)");
  }
  ModInt inv() const {
    int a = x, b = M, y = 1, z = 0, t;
    for (; ; ) {
      t = a / b; a -= t * b;
      if (a == 0) {
        assert(b == 1 || b == -1);
        return ModInt(b * z);
      }
      y -= t * z;
      t = b / a; b -= t * a;
      if (b == 0) {
        assert(a == 1 || a == -1);
        return ModInt(a * y);
      }
      z -= t * y;
    }
  }
  ModInt opUnary(string op)() const if (op == "-") { return ModInt(-x); }
  ModInt opBinary(string op, T)(T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op)(long a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  string toString() const { return x.to!string; }
}

enum MO = 998244353;
alias Mint = ModInt!MO;

enum LIM = 3 * 10^^5 + 20;
Mint[] inv, fac, invFac;
void prepare() {
  inv = new Mint[LIM];
  fac = new Mint[LIM];
  invFac = new Mint[LIM];
  inv[1] = 1;
  foreach (i; 2 .. LIM) {
    inv[i] = -(Mint.M / i) * inv[cast(size_t)(Mint.M % i)];
  }
  fac[0] = invFac[0] = 1;
  foreach (i; 1 .. LIM) {
    fac[i] = fac[i - 1] * i;
    invFac[i] = invFac[i - 1] * inv[i];
  }
}
Mint binom(long n, long k) {
  if (0 <= k && k <= n) {
    assert(n < LIM);
    return fac[cast(size_t)(n)] * invFac[cast(size_t)(k)] * invFac[cast(size_t)(n - k)];
  } else {
    return Mint(0);
  }
}

enum LIM_K = 10^^5 + 5;

void main() {
  prepare();

  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      const Q = readInt();
      auto E = new int[N];
      foreach (i; 0 .. N) {
        E[i] = readInt() - 1;
      }
      auto L = new int[Q];
      auto R = new int[Q];
      auto K = new int[Q];
      foreach (q; 0 .. Q) {
        L[q] = readInt() - 1;
        R[q] = readInt();
        K[q] = readInt();
      }

      debug {
        // brute
        writeln("brute");
        foreach (q; 0 .. Q) {
          auto as = new int[M];
          auto bs = new int[M];
          foreach (i; 0 .. N) {
            ++as[E[i]];
            if (L[q] <= i && i < R[q]) {
              ++bs[E[i]];
            }
          }
          Mint ans = 1;
          foreach (j; 0 .. M) {
            ans *= fac[K[q] + as[j]] * invFac[K[q] + as[j] - bs[j]];
          }
          foreach (i; R[q] - L[q] .. N) {
            ans *= (1L * K[q] * M + N - i);
          }
          writeln(ans);
        }
      }

      auto as = new int[M];
      foreach (i; 0 .. N) {
        ++as[E[i]];
      }

      class Query {
        int l, r;
        int id;
        int key0, key1;
        this(int l, int r, int id) {
          this.l = l;
          this.r = r;
          this.id = id;
        }
        override string toString() const {
          return format("[%s, %s)", l, r);
        }
      }
      auto queriess = new Query[][LIM_K];
      foreach (q; 0 .. Q) {
        queriess[K[q]] ~= new Query(L[q], R[q], q);
      }
      auto ans = new Mint[Q];
      foreach (k; 0 .. LIM_K) {
        auto queries = queriess[k];
        if (queries) {
          // suffix prod for (k M + N - 0) ... (k M + N - (N - 1))
          auto prod = new Mint[N + 1];
          prod[N] = 1;
          foreach_reverse (i; 0 .. N) {
            prod[i] = (1L * k * M + N - i) * prod[i + 1];
          }

          const queriesLen = cast(int)(queries.length);
          int sz = cast(int)(sqrt(cast(real)(N)));
          chmax(sz, 10^^6 / queriesLen);
          // const sz = max(N / cast(int)(sqrt(cast(real)(queriesLen))), 1);
          foreach (q; queries) {
            q.key0 = q.l / sz;
            q.key1 = q.r;
            if (q.key0 % 2 != 0) {
              q.key1 *= -1;
            }
          }
          queries.sort!((a, b) => ((a.key0 != b.key0) ? (a.key0 < b.key0) : (a.key1 < b.key1)));
          debug {
            writeln("k = ", k, ", sz = ", sz);
            writeln("  queries = ", queries);
          }

          Mint now = 1;
          auto bs = new int[M];
          void add(int i) {
            const j = E[i];
            /*
            now *= fac[k + as[j] - bs[j]];
            ++bs[j];
            now *= invFac[k + as[j] - bs[j]];
            */
            now *= (k + as[j] - bs[j]);
            ++bs[j];
          }
          void rem(int i) {
            const j = E[i];
            /*
            now *= fac[k + as[j] - bs[j]];
            --bs[j];
            now *= invFac[k + as[j] - bs[j]];
            */
            --bs[j];
            now *= inv[k + as[j] - bs[j]];
          }

          int l, r;
          foreach (q; queries) {
            for (; l > q.l; ) add(--l);
            for (; r < q.r; ) add(r++);
            for (; l < q.l; ) rem(l++);
            for (; r > q.r; ) rem(--r);
            ans[q.id] = now * prod[q.r - q.l];
          }
        }
      }
      foreach (q; 0 .. Q) {
        writeln(ans[q]);
      }
    }
  } catch (EOFException e) {
  }
}


Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable.In total the table Arthur bought has n legs, the length of the i-th leg is li.Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number di — the amount of energy that he spends to remove the i-th leg.A table with k legs is assumed to be stable if there are more than half legs of the maximum length. For example, to make a table with 5 legs stable, you need to make sure it has at least three (out of these five) legs of the maximum length. Also, a table with one leg is always stable and a table with two legs is stable if and only if they have the same lengths.Your task is to help Arthur and count the minimum number of energy units Arthur should spend on making the table stable.

The first line of the input contains integer n (1 ≤ n ≤ 105) — the initial number of legs in the table Arthur bought. The second line of the input contains a sequence of n integers li (1 ≤ li ≤ 105), where li is equal to the length of the i-th leg of the table. The third line of the input contains a sequence of n integers di (1 ≤ di ≤ 200), where di is the number of energy units that Arthur spends on removing the i-th leg off the table.

Print a single integer — the minimum number of energy units that Arthur needs to spend in order to make the table stable.

import std.stdio;
import std.c.stdio;
import std.math;
import std.algorithm;
import std.conv;
import std.string;
import std.array;
import std.typecons;
import std.range;
import std.container.binaryheap;

alias Leg = Tuple!(int, "l", int, "d");

void main() {
  int n;
  scanf("%d", &n);
  Leg[] a = new Leg[n];
  foreach(i; 0..n) {
    scanf("%d", &a[i].l);
  }
  foreach(i; 0..n) {
    scanf("%d", &a[i].d);
  }
  a.sort();
  int[] s = new int[n + 1];
  foreach(i; 0..n) {
    s[i + 1] = s[i] + a[i].d;
  }
  int p = 0, q = 0;
  auto pq = BinaryHeap!(int[])(new int[n], 0);
  int ans = int.max, sum = 0;
  while (q < n) {
    while (p < n && a[p].l == a[q].l) {
      p++;
    }
    int ct = p - q;
    int cost = s[n];
    cost -= s[p] - s[q];
    int[] vs;
    foreach (v; pq.take(ct - 1)) {
      cost -= v;
      vs ~= v;
    }
    foreach(v; vs) {
      pq.insert(v);
    }
    ans = min(ans, cost);
    while (q < p) {
      sum += a[q].d;
      pq.insert(a[q].d);
      q++;
    }
  }
  writeln(ans);
}

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

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

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

    auto vals = make!(RedBlackTree!(int, "a > b", true));

    int ans = int.max;
    int biggersm = ds.sum(), smallersm = 0;
    auto arr = zip(ls, ds).sort!((t1, t2) => t1[0] < t2[0]).array;
    for (int i = 0; i < n; ) {
        debug { arr[i].writeln; }

        int j = i+1;

        while (j < n && arr[i][0] == arr[j][0]) { j += 1; }
        auto cursm = arr[i .. j].map!(t => t[1]).sum();
        biggersm -= cursm;

        debug { biggersm.writeln; }

        int[] omitted;
        for (int k = i; k < j-1 && ! vals.empty(); ++k) {
            omitted ~= vals.front;
            vals.removeFront();
        }

        ans = min(ans, biggersm + smallersm - omitted.sum());

        foreach (e; omitted) { vals.insert(e); }
        smallersm += cursm;
        for (int k = i; k < j; ++k) vals.insert(arr[k][1]);
        i = j;
    }

    ans.writeln;
}

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

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

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

    auto vals = make!(RedBlackTree!(int, "a > b", true));

    int ans = int.max;
    int biggersm = ds.sum(), smallersm = 0;
    auto arr = zip(ls, ds).sort!((t1, t2) => t1[0] < t2[0]).array;
    for (int i = 0; i < n; ) {
        debug { arr[i].writeln; }

        int j = i+1;

        while (j < n && arr[i][0] == arr[j][0]) { j += 1; }
        auto cursm = arr[i .. j].map!(t => t[1]).sum();
        biggersm -= cursm;

        debug { biggersm.writeln; }

        int[] ommited;
        for (int k = i; k < j-1 && ! vals.empty(); ++k) {
            ommited ~= vals.front;
            vals.removeFront();
        }

        ans = min(ans, biggersm + smallersm - ommited.sum());

        foreach (e; ommited) { vals.insert(e); }
        smallersm += cursm;
        for (int k = i; k < j; ++k) vals.insert(arr[k][1]);
        i = j;
    }

    ans.writeln;
}


The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.

The first line of the input contains the dimensions of the map n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns respectively. Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.

Print a single integer — the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.

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

immutable int INF = int.max / 8;

void main ()
{
    int n, m;
    while (readf (" %s %s", &n, &m) > 0)
    {
        readln;
        string [] a;
        a ~= '#'.repeat (m + 2).text;
        foreach (row; 1..n + 1)
        {
            a ~= '#' ~ readln.strip ~ '#';
        }
        a ~= '#'.repeat (m + 2).text;

        int [] [] distmap (int start)
        {
            alias Pair = Tuple !(int, "row", int, "col");
            Pair [] q;
            q.reserve ((m + 2) * (n + 2) + 1);
            auto d = new int [] [] (n + 2, m + 2);
            foreach (ref e; d)
            {
                e[] = INF;
            }

            foreach (row; 1..n + 1)
            {
                foreach (col; 1..m + 1)
                {
                    if (a[row][col] == start)
                    {
                        q ~= Pair (row, col);
                        d[row][col] = 0;
                    }
                }
            }

            immutable int DIRS = 4;
            immutable int [DIRS] DROW = [-1,  0, +1,  0];
            immutable int [DIRS] DCOL = [ 0, -1,  0, +1];

            while (!q.empty)
            {
                auto cur = q.front;
                q.popFront ();
                foreach (dir; 0..DIRS)
                {
                    int nrow = cur.row + DROW[dir];
                    int ncol = cur.col + DCOL[dir];
                    if (a[nrow][ncol] == '#')
                    {
                        continue;
                    }
                    if (d[nrow][ncol] >= INF)
                    {
                        d[nrow][ncol] =
                            d[cur.row][cur.col] + 1;
                        q.assumeSafeAppend ();
                        q ~= Pair (nrow, ncol);
                    }
                }
            }

            debug {writefln ("%(%-(%9d %)\n%)", d);}
            return d;
        }

        int [] [] [] d;
        foreach (c; '1'..'3' + 1)
        {
            d ~= distmap (c);
        }

        pure int disttwo (int p, int q)
        {
            int res = INF;
            foreach (row; 1..n + 1)
            {
                foreach (col; 1..m + 1)
                {
                    if (a[row][col] == q)
                    {
                        res = min (res,
                            d[p - '1'][row][col] - 1);
                    }
                }
            }
            debug {writeln (p, ' ', q, ' ', res);}
            return res;
        }

        int res = INF;
        res = min (res, disttwo ('1', '2') + disttwo ('2', '3'));
        res = min (res, disttwo ('2', '3') + disttwo ('3', '1'));
        res = min (res, disttwo ('3', '1') + disttwo ('1', '2'));
        foreach (row; 1..n + 1)
        {
            foreach (col; 1..m + 1)
            {
                if (a[row][col] == '.')
                {
                    res = min (res, d[0][row][col] - 2 +
                        d[1][row][col] + d[2][row][col]);
                }
            }
        }

        if (res >= INF / 2)
        {
            res = -1;
        }
        writeln (res);
    }
}

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

immutable int INF = int.max / 8;

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		readln;
		string [] a;
		a ~= '#'.repeat (m + 2).text;
		foreach (row; 1..n + 1)
		{
			a ~= '#' ~ readln.strip ~ '#';
		}
		a ~= '#'.repeat (m + 2).text;

		int [] [] distmap (int start)
		{
			alias Pair = Tuple !(int, "row", int, "col");
			Pair [] q;
			q.reserve ((m + 2) * (n + 2) + 1);
			auto d = new int [] [] (n + 2, m + 2);
			foreach (ref e; d)
			{
				e[] = INF;
			}

			foreach (row; 1..n + 1)
			{
				foreach (col; 1..m + 1)
				{
					if (a[row][col] == start)
					{
						q ~= Pair (row, col);
						d[row][col] = 0;
					}
				}
			}

			immutable int DIRS = 4;
			immutable int [DIRS] DROW = [-1,  0, +1,  0];
			immutable int [DIRS] DCOL = [ 0, -1,  0, +1];

			while (!q.empty)
			{
				auto cur = q.front;
				q.popFront ();
				foreach (dir; 0..DIRS)
				{
					int nrow = cur.row + DROW[dir];
					int ncol = cur.col + DCOL[dir];
					if (a[nrow][ncol] == '#')
					{
						continue;
					}
					if (d[nrow][ncol] >= INF)
					{
						d[nrow][ncol] =
						    d[cur.row][cur.col] + 1;
						q.assumeSafeAppend ();
						q ~= Pair (nrow, ncol);
					}
				}
			}

			debug {writefln ("%(%-(%9d %)\n%)", d);}
			return d;
		}

		int [] [] [] d;
		foreach (c; '1'..'3' + 1)
		{
			d ~= distmap (c);
		}

		pure int disttwo (int p, int q)
		{
			int res = INF;
			foreach (row; 1..n + 1)
			{
				foreach (col; 1..m + 1)
				{
					if (a[row][col] == q)
					{
						res = min (res,
						    d[p - '1'][row][col] - 1);
					}
				}
			}
			debug {writeln (p, ' ', q, ' ', res);}
			return res;
		}

		int res = INF;
		res = min (res, disttwo ('1', '2') + disttwo ('2', '3'));
		res = min (res, disttwo ('2', '3') + disttwo ('3', '1'));
		res = min (res, disttwo ('3', '1') + disttwo ('1', '2'));
		foreach (row; 1..n + 1)
		{
			foreach (col; 1..m + 1)
			{
				if (a[row][col] == '.')
				{
					res = min (res, d[0][row][col] - 2 +
					    d[1][row][col] + d[2][row][col]);
				}
			}
		}

		if (res >= INF)
		{
			res = -1;
		}
		writeln (res);
	}
}


Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types.  speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type);  overtake is allowed: this sign means that after some car meets it, it can overtake any other car;  no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign);  no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well.In the beginning of the ride overtake is allowed and there is no speed limit.You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types:  Polycarp changes the speed of his car to specified (this event comes with a positive integer number);  Polycarp's car overtakes the other car;  Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer);  Polycarp's car goes past the "overtake is allowed" sign;  Polycarp's car goes past the "no speed limit";  Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?

The first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events. Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event. An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).

Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.

NoteIn the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120.In the second example Polycarp didn't make any rule violation.In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.

module main;
__gshared:
import core.bitop, std.algorithm, std.bigint, std.bitmanip, std.complex,
	std.container, std.conv, std.datetime, std.functional, std.math, std.meta;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.parallelism, std.random, std.range, std.regex, std.stdio, std.string,
	std.traits, std.typecons, std.uni, std.variant;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
enum mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///lcm
		T lcm(T)(auto ref T a, auto ref T b)
		{
			return a / gcd(a, b) * b;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///BigInt greatest common divizor
		BigInt gcd(BigInt a, BigInt b)
		{
			while (b)
			{
				a %= b;
				swap(a, b);
			}
			return a;
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///integer size
		int sz(T)(T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			size_t l = 0, r = a.length;
			while (r - l > 1)
			{
				auto m = (l + r) >> 1;
				if (!(a[m] < g))
					r = m;
				else
					l = m;
			}
			return (!(a[l] < g)) ? l : r;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			size_t l = 0, r = a.length;
			while (r - l > 1)
			{
				auto m = (l + r) >> 1;
				if (g < a[m])
					r = m;
				else
					l = m;
			}
			return (g < a[l]) ? l : r;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return binf(a, g) != a.length;
		}
	}
	///write an array
	void putarr(X)(in X a, in char ch = ' ') if (isInputRange!X)
	{
		writefln("%(%s" ~ ch ~ "%)", a);
	}
	///write a matrix
	void putarr(X)(in X a)
			if (isInputRange!X && isInputRange!(ElementType!X) && !isSomeString!(ElementType!X))
	{
		writefln("%(%(%s %)\n%)", a);
	}
	///get an array
	bool getarr(X)(X a, in size_t n)
	{
		bool b = 1;
		foreach (ref i; a[0 .. n])
			b = input(&i);
		return b;
	}
	///read without format
	bool input(T...)(ref T ptrs) if (ptrs.length > 0)
	{
		size_t s = 0;
		foreach (ref e; ptrs)
		{
			if (isSomeChar!(Unqual!(typeof(e))))
				s += readf(" %c", &e);
			else
				s += readf(" %s", &e);
		}
		return s == ptrs.length;
	}
	///readln without format
	bool read(T...)(ref T ptrs) if (ptrs.length > 0)
	{
		size_t s = 0;
		foreach (ref e; ptrs)
		{
			if (isSomeChar!(Unqual!(typeof(e))))
				s += readf(" %c", &e);
			else
				s += readf(" %s", &e);
		}
		readln;
		return s == ptrs.length;
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version (home)
	{
		freopen("input.txt", "r", core.stdc.stdio.stdin);
		//freopen("output.txt", "w", core.stdc.stdio.stdout);
		/*StopWatch sw;
		sw.start;
		scope (exit)
		{
			sw.stop;
			stderr.writefln("\nTime: %d ms", sw.peek.msecs);
		}*/
	}
	int n;
	loop: while (read(n))
	{
		auto st = new SList!int;
		int cnt, ans, sp;
		foreach (_; 0 .. n)
		{
			int t;
			input(t);
			switch (t)
			{
			case 1:
				read(sp);
				while (!st.empty && st.front < sp)
				{
					ans++;
					st.removeFront;
				}
				break;
			case 2:
				ans += cnt;
				cnt = 0;
				break;
			case 3:
				int g;
				read(g);
				st.insert(g);
				while (!st.empty && st.front < sp)
				{
					ans++;
					st.removeFront;
				}
				break;
			case 4:
				cnt = 0;
				break;
			case 5:
				st.clear;
				break;
			case 6:
				cnt++;
				break;
			default:
				assert(0);
			}

		}
		writeln(ans);
	}
}

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

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

    int[] overtakes;
    Tuple!(int, int)[] speeds;
    foreach (i; 0 .. n) {
        int t;
        readf("%s", &t);
        if (t == 2 || t == 4 || t == 6) { overtakes ~= t; }
        else {
            int x = 0;
            if (t == 1 || t == 3) { readf(" %s", &x); }

            speeds ~= tuple(t, x);
        }
        readln;
    }

    int ans = 0;
    int ostack = 0;
    foreach (e; overtakes) {
        if (e == 2) {
            ans += ostack;
            ostack = 0;
        } else if (e == 4) { ostack = 0; }
        else { ostack += 1; }
    }

    int cspeed = 0;
    int[] speedlims;
    foreach (e; speeds) {
        if (e[0] == 1) {
            while (!speedlims.empty() && speedlims.back() < e[1]) {
                ans += 1;
                speedlims.popBack();
            }
            cspeed = e[1];
        } else if (e[0] == 3) {
            if (cspeed > e[1]) { ans += 1; }
            else { speedlims ~= e[1]; }
        } else {
            speedlims = [];
        }
    }

    ans.writeln;
}


After many unsuccessful tries, Mashtali decided to copy modify an AtCoder problem. So here is his copied new problem:There is a tree with $$$n$$$ vertices and some non-empty set of the vertices are pinned to the ground.Two players play a game against each other on the tree. They alternately perform the following action:  Remove an edge from the tree, then remove every connected component that has no pinned vertex.The player who cannot move loses(every edge has been deleted already). You are given the tree, but not the set of the pinned vertices. Your task is to determine, for each $$$k$$$, the winner of the game, if only the vertices $$$1, 2, 3, \ldots, k$$$ are pinned and both players play optimally.

The first line of input contains an integer $$$n$$$ — the number of vertices ($$$1 \le n \le 3 \cdot 10^5$$$). The $$$i$$$-th of the following $$$n-1$$$ lines contains two integers $$$u_i, v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) — the endpoints of the $$$i$$$-th edge. It's guaranteed that these edges form a tree.

Print a string of length $$$n$$$. The $$$i$$$-th character should be '1' if the first player wins the $$$i$$$-th scenario, and '2' otherwise.

NoteBelow you can see the tree in the first sample :  If $$$k = 1$$$ then the first player can cut the edge $$$(1, 2)$$$.If $$$k = 2$$$ or $$$k = 3$$$, the first player can cut the edge $$$(2, 4)$$$, after that only the edges $$$(1, 2)$$$ and $$$(2, 3)$$$ remain. After the second players move, there will be a single edge left for the first player to cut. So first player wins.

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

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

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

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

int N;
int[] A, B;

int[][] G;
int[] par;
int[] gs;

void dfs(int u, int p) {
  par[u] = p;
  gs[u] = 0;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
      gs[u] ^= (1 + gs[v]);
    }
  }
}

void main() {
  debug {
    // cycle?, after
    enum lim = 10;
    auto dp = new int[][](lim, lim);
    foreach (a; 1 .. lim) {
      foreach (b; 0 .. lim) {
        bool[int] app;
        app[(a == 1) ? 0 : dp[a - 1][b]] = true;
        foreach (bb; 0 .. b) {
          app[dp[a][bb]] = true;
        }
        for (int g = 0; ; ++g) {
          if (g !in app) {
            dp[a][b] = g;
            break;
          }
        }
      }
      writeln(a, ": ", dp[a]);
    }
  }

  try {
    for (; ; ) {
      N = readInt();
      A = new int[N - 1];
      B = new int[N - 1];
      foreach (i; 0 .. N - 1) {
        A[i] = readInt() - 1;
        B[i] = readInt() - 1;
      }

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      par = new int[N];
      gs = new int[N];
      dfs(0, -1);
      debug {
        writeln("gs = ", gs);
      }

      // u -> par[u]
      auto cut = new bool[N];
      cut[0] = true;

      auto ans = new char[N];
      int g = gs[0];
      foreach (u; 0 .. N) {
        for (int v = u; !cut[v]; v = par[v]) {
          cut[v] = true;
          g ^= 1;
          g ^= gs[v];
          g ^= (1 + gs[v]);
        }
        ans[u] = g ? '1' : '2';
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Given an array $$$a$$$ of length $$$n$$$ and an integer $$$k$$$, find the number of indices $$$1 \leq i \leq n - k$$$ such that the subarray $$$[a_i, \dots, a_{i+k}]$$$ with length $$$k+1$$$ (not with length $$$k$$$) has the following property:   If you multiply the first element by $$$2^0$$$, the second element by $$$2^1$$$, ..., and the ($$$k+1$$$)-st element by $$$2^k$$$, then this subarray is sorted in strictly increasing order.  More formally, count the number of indices $$$1 \leq i \leq n - k$$$ such that $$$$$$2^0 \cdot a_i < 2^1 \cdot a_{i+1} < 2^2 \cdot a_{i+2} < \dots < 2^k \cdot a_{i+k}.$$$$$$

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq k < n$$$) — the length of the array and the number of inequalities. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array. The sum of $$$n$$$ across all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of indices satisfying the condition in the statement.

NoteIn the first test case, both subarrays satisfy the condition:   $$$i=1$$$: the subarray $$$[a_1,a_2,a_3] = [20,22,19]$$$, and $$$1 \cdot 20 < 2 \cdot 22 < 4 \cdot 19$$$.  $$$i=2$$$: the subarray $$$[a_2,a_3,a_4] = [22,19,84]$$$, and $$$1 \cdot 22 < 2 \cdot 19 < 4 \cdot 84$$$.  In the second test case, three subarrays satisfy the condition:   $$$i=1$$$: the subarray $$$[a_1,a_2] = [9,5]$$$, and $$$1 \cdot 9 < 2 \cdot 5$$$.  $$$i=2$$$: the subarray $$$[a_2,a_3] = [5,3]$$$, and $$$1 \cdot 5 < 2 \cdot 3$$$.  $$$i=3$$$: the subarray $$$[a_3,a_4] = [3,2]$$$, and $$$1 \cdot 3 < 2 \cdot 2$$$.  $$$i=4$$$: the subarray $$$[a_4,a_5] = [2,1]$$$, but $$$1 \cdot 2 = 2 \cdot 1$$$, so this subarray doesn't satisfy the condition.

void main() { runSolver(); }

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

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

      auto satisfied = (N - 1).iota.map!(i => A[i] / 2 < A[i + 1] ? 1 : 0).array;
      auto acc = 0 ~ satisfied.cumulativeFold!"a + b".array;

      return (N - K).iota.count!(i => acc[i + K] - acc[i] == K);
    }

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

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, 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"];

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

void main() { runSolver(); }

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

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

      long[] div;
      foreach(i; 0..N - 1) div ~= A[i] / A[i + 1];

      long ans;
      foreach(i; 0..N - K) {
        bool ok = true;
        foreach(k; 0..K) {
          if (k >= 50) break;
          if (div[i + k] > 2^^k || (div[i + k] == 2^^k && A[i + k] / 2 >= A[i + k + 1])) {
            ok = false;
            break;
          }
        }

        if (ok) ans++;
      }

      return ans;
    }

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

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, 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"];

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

void main() { runSolver(); }

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

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

      long[] div;
      foreach(i; 0..N - 1) div ~= A[i] / A[i + 1];

      long ans;
      foreach(i; 0..N - K) {
        bool ok = true;
        foreach(k; 0..K) {
          if (k >= 32) break;
          if (div[i + k] > 2^^k || (div[i + k] == 2^^k && A[i + k] / 2 >= A[i + k + 1])) {
            ok = false;
            break;
          }
        }

        if (ok) ans++;
      }

      return ans;
    }

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

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, 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"];

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

void main() { runSolver(); }

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

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

      long[] div;
      foreach(i; 0..N - 1) div ~= A[i] / A[i + 1];

      long ans;
      foreach(i; 0..N - K) {
        bool ok = true;
        foreach(k; 0..K) {
          if (k >= 30) {
            break;
          } else {
            if (div[i + k] > 2^^k || (div[i + k] == 2^^k && A[i + k] / 2 >= A[i + k + 1])) {
              ok = false;
              break;
            }
          }
        }

        if (ok) ans++;
      }

      return ans;
    }

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

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, 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"];

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


Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive.For permutation p = p0, p1, ..., pn, Polo has defined its beauty — number .Expression  means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as "^" and in Pascal — as "xor".Help him find among all permutations of integers from 0 to n the permutation with the maximum beauty.

The single line contains a positive integer n (1 ≤ n ≤ 106).

In the first line print integer m the maximum possible beauty. In the second line print any permutation of integers from 0 to n with the beauty equal to m. If there are several suitable permutations, you are allowed to print any of them.

import std.algorithm;
import std.array;
import std.container;
import std.exception;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

long solve (ref int [] a, int n)
{
	if (n <= 0)
	{
		return 0;
	}

	int m = 1;
	while (m < n)
	{
		m |= m << 1;
	}
	int hi = n + 1;
	int lo = m - n;
	debug {writefln ("%d: %d, [%d..%d]", n, m, lo, hi);}
	reverse (a[lo..hi]);
	return (cast (long) (hi - lo)) * m + solve (a, lo - 1);
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = array (iota (n + 1));
		auto s = solve (a, n);
		writeln (s);
		writefln ("%(%s %)", a);
	}
}