You are playing a strange game with Li Chen. You have a tree with $$$n$$$ nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from $$$1$$$ to $$$n$$$. Neither of you know the other's labelling of the tree.You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled $$$x_1, x_2, \ldots, x_{k_1}$$$ in your labeling, Li Chen's subtree consists of the vertices labeled $$$y_1, y_2, \ldots, y_{k_2}$$$ in his labeling. The values of $$$x_1, x_2, \ldots, x_{k_1}$$$ and $$$y_1, y_2, \ldots, y_{k_2}$$$ are known to both of you.   The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes. You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most $$$5$$$ questions, each of which is in one of the following two forms:   A x: Andrew will look at vertex $$$x$$$ in your labeling and tell you the number of this vertex in Li Chen's labeling.  B y: Andrew will look at vertex $$$y$$$ in Li Chen's labeling and tell you the number of this vertex in your labeling. Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices.

NoteFor the first sample, Li Chen's hidden permutation is $$$[2, 3, 1]$$$, and for the second, his hidden permutation is $$$[5, 3, 2, 4, 1, 6]$$$ for both cases.In the first sample, there is a tree with three nodes in a line. On the top, is how you labeled the tree and the subtree you chose, and the bottom is how Li Chen labeled the tree and the subtree he chose:   In the first question, you ask Andrew to look at node $$$1$$$ in your labelling and tell you the label of it in Li Chen's labelling. Andrew responds with $$$2$$$. At this point, you know that both of your subtrees contain the same node (i.e. node $$$1$$$ according to your labeling), so you can output "C 1" and finish. However, you can also ask Andrew to look at node $$$2$$$ in Li Chen's labelling and tell you the label of it in your labelling. Andrew responds with $$$1$$$ (this step was given with the only reason — to show you how to ask questions).For the second sample, there are two test cases. The first looks is the one from the statement:   We first ask "B 2", and Andrew will tell us $$$3$$$. In this case, we know $$$3$$$ is a common vertex, and moreover, any subtree with size $$$3$$$ that contains node $$$3$$$ must contain node $$$1$$$ as well, so we can output either "C 1" or "C 3" as our answer.In the second case in the second sample, the situation looks as follows:   In this case, you know that the only subtree of size $$$3$$$ that doesn't contain node $$$1$$$ is subtree $$$4,5,6$$$. You ask Andrew for the label of node $$$1$$$ in Li Chen's labelling and Andrew says $$$5$$$. In this case, you know that Li Chen's subtree doesn't contain node $$$1$$$, so his subtree must be consist of the nodes $$$4,5,6$$$ (in your labelling), thus the two subtrees have no common nodes.

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 t = next!int;
  foreach(tc; 0 .. t)
    {
      auto n = next!int;
      auto als = new int[][](n + 1);
      foreach(i; 0 .. n - 1)
	{
	  auto a = next!int;
	  auto b = next!int;
	  als[a] ~= b;
	  als[b] ~= a;
	}
      auto k1 = next!int;
      auto x = next!int(k1);
      auto xs = redBlackTree!int(x);
      auto k2 = next!int;
      auto y = next!int(k2);
      auto ys = redBlackTree!int(y);
      int A(int qx)
      {
	writeln("A ", qx); stdout.flush;
	return next!int;
      }
      int B(int qy)
      {
	writeln("B ", qy), stdout.flush;
	return next!int;
      }
      auto root = B(y[0]);
      int dfs(int v, int p)
      {
	if (v in xs)
	  return v;
	int res = 0;
	foreach(ch; als[v])
	  if (ch != p)
	    if ((res = dfs(ch, v)) != 0)
	      return res;
	return 0;
      }
      auto required = dfs(root, root);
      auto requiredForLi = A(required);
      if (requiredForLi in ys)
	{
	  writeln("C ", required); stdout.flush;
	}
      else
	{
	  writeln("C ", -1); stdout.flush;
	}
    }
}

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


A positive integer $$$a$$$ is given. Baron Munchausen claims that he knows such a positive integer $$$n$$$ that if one multiplies $$$n$$$ by $$$a$$$, the sum of its digits decreases $$$a$$$ times. In other words, $$$S(an) = S(n)/a$$$, where $$$S(x)$$$ denotes the sum of digits of the number $$$x$$$. Find out if what Baron told can be true.

The only line contains a single integer $$$a$$$ ($$$2 \le a \le 10^3$$$).

If there is no such number $$$n$$$, print $$$-1$$$. Otherwise print any appropriate positive integer $$$n$$$. Your number must not consist of more than $$$5\cdot10^5$$$ digits. We can show that under given constraints either there is no answer, or there is an answer no longer than $$$5\cdot10^5$$$ digits.

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

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

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

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

void main() {
  debug {
    enum limA = 20;
    enum limN = 10L^^7;

    long calc(long n) {
      long ret;
      for (; n > 0; n /= 10) {
        ret += n % 10;
      }
      return ret;
    }
    /*
    auto anss = new long[limA];
    foreach (a; 1 .. limA) {
      foreach (n; 1 .. limN) {
        if (a * calc(a * n) == calc(n)) {
          anss[a] = n;
          break;
        }
      }
    }
    writeln(anss);
    */
/*
[0, 1, 6, 6669, 75, 0, 0, 14286, 125, 0, 0, 0, 0, 7693077, 0, 0, 0, 5882353, 0, 0]
*/
    /*
    foreach (a; 1 .. limA) {
      writeln("a = ", a);
      foreach (u; 0 .. a) {
        write(u, " ->");
        foreach (x; 0 .. 10) {
          const y = (u * 10 + x) / a;
          const v = (u * 10 + x) % a;
          write(" ", [v, a * x - y]);
        }
        writeln();
      }
    }
    */
  }

  try {
    for (; ; ) {
      const A = readInt();

      const lim = 2 * A;
      alias Prev = Tuple!(int, "r", int, "s", int, "x");
      auto prev = new Prev[][](A, lim + 1 + lim);
      foreach (r; 0 .. A) foreach (s; -lim .. lim + 1) {
        prev[r][lim + s] = Prev(-1, -1, -1);
      }

      auto que = new int[A * (lim + 1 + lim) * 2];
      int qb, qe;
      foreach (x; 1 .. 10) {
        const rr = x % A;
        const ss = A * x - x / A;
        if (-lim <= ss && ss <= lim) {
          if (prev[rr][lim + ss].x == -1) {
            prev[rr][lim + ss] = Prev(-2, -2, x);
            que[qe++] = rr;
            que[qe++] = ss;
          }
        }
      }
      for (; qb != qe; ) {
        const r = que[qb++];
        const s = que[qb++];
        debug {
          // writeln(r, " ", s, " ", prev[r][lim + s]);
        }
        if (r == 0 && s == 0) {
          break;
        }
        foreach (x; 0 .. 10) {
          const rr = (r * 10 + x) % A;
          const y = (r * 10 + x) / A;
          const ss = s + A * x - y;
          if (-lim <= ss && ss <= lim) {
            if (prev[rr][lim + ss].x == -1) {
              prev[rr][lim + ss] = Prev(r, s, x);
              que[qe++] = rr;
              que[qe++] = ss;
            }
          }
        }
      }

      if (prev[0][lim + 0].x == -1) {
        writeln(-1);
      } else {
        int[] xs;
        for (int r = 0, s = 0; r != -2; ) {
          const p = prev[r][lim + s];
          xs ~= p.x;
          r = p.r;
          s = p.s;
        }
        xs.reverse;
        int[] ys;
        {
          int r = 0, s = 0;
          foreach (x; xs) {
            const rr = (r * 10 + x) % A;
            const y = (r * 10 + x) / A;
            const ss = s + A * x - y;
            if (!ys.empty || y != 0) {
              ys ~= y;
            }
            r = rr;
            s = ss;
          }
        }
        foreach (y; ys) {
          write(y);
        }
        writeln();
      }
    }
  } catch (EOFException e) {
  }
}


You are given a directed acyclic graph with $$$n$$$ vertices and $$$m$$$ edges. For all edges $$$a \to b$$$ in the graph, $$$a < b$$$ holds.You need to find the number of pairs of vertices $$$x$$$, $$$y$$$, such that $$$x > y$$$ and after adding the edge $$$x \to y$$$ to the graph, it has a Hamiltonian path.

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 5$$$): the number of test cases. The next lines contains the descriptions of the test cases. In the first line you are given two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 150\,000$$$, $$$0 \leq m \leq \min(150\,000, \frac{n(n-1)}{2})$$$): the number of vertices and edges in the graph.  Each of the next $$$m$$$ lines contains two integers $$$a$$$, $$$b$$$ ($$$1 \leq a < b \leq n$$$), specifying an edge $$$a \to b$$$ in the graph. No edge $$$a \to b$$$ appears more than once.

For each test case, print one integer: the number of pairs of vertices $$$x$$$, $$$y$$$, $$$x > y$$$, such that after adding the edge $$$x \to y$$$ to the graph, it has a Hamiltonian path.

NoteIn the first example, any edge $$$x \to y$$$ such that $$$x > y$$$ is valid, because there already is a path $$$1 \to 2 \to 3$$$.In the second example only the edge $$$4 \to 1$$$ is valid. There is a path $$$3 \to 4 \to 1 \to 2$$$ if this edge is added.In the third example you can add edges $$$2 \to 1$$$, $$$3 \to 1$$$, $$$4 \to 1$$$, $$$4 \to 2$$$.

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        int N = readInt;
        int M = readInt;
        auto A = new int[M];
        auto B = new int[M];
        foreach (i; 0 .. M) {
          A[i] = readInt;
          B[i] = readInt;
        }
        M += 2 * N;
        foreach (u; 1 .. N + 1) {
          A ~= 0;
          B ~= u;
          A ~= u;
          B ~= N + 1;
        }

        auto graph = new int[][N + 2];
        auto graphRev = new int[][N + 2];
        foreach (i; 0 .. M) {
          graph[A[i]] ~= B[i];
          graphRev[B[i]] ~= A[i];
        }

        auto fs = new int[N + 1];
        foreach (i; 0 .. M) {
          if (A[i] + 1 == B[i]) {
            fs[A[i]] = 1;
          }
        }
        auto fsSum = new int[N + 2];
        foreach (u; 0 .. N + 1) {
          fsSum[u + 1] = fsSum[u] + fs[u];
        }

        long ans;
        if (fsSum[N + 1] == N + 1) {
          ans = 1L * N * (N - 1) / 2;
        } else {
          int l = N + 1, r = 0;
          foreach (u; 0 .. N + 1) {
            if (!fs[u]) {
              chmin(l, u);
              chmax(r, u + 1);
            }
          }
          debug {
            writeln("fs = ", fs);
            writeln("l = ", l, ", r = ", r);
          }
          bool isGood(int u, int v) {
            return (u <= v && fsSum[v] - fsSum[u] == v - u);
          }

          // (u, u + 1) to (l, l + 1),  parity of # of steps
          auto visL = new bool[2][N + 1];
          visL[l][0] = true;
          foreach_reverse (u; 0 .. l + 1) {
            foreach (v; graphRev[u + 1]) {
              // v -> u + 1,  v + 1 -> u
              if (isGood(v + 1, u)) {
                if (visL[u][0]) visL[v][1] = true;
                if (visL[u][1]) visL[v][0] = true;
              }
            }
          }
          long[4] cntL;
          foreach (u; 0 .. l + 1) {
            int p;
            if (visL[u][0]) p |= 1 << 0;
            if (visL[u][1]) p |= 1 << 1;
            ++cntL[p];
          }

          // (l, l + 1) to (u, u + 1),  parity of # of steps
          auto visR = new bool[2][N + 1];
          visR[l][0] = true;
          foreach (u; l .. N + 1) {
            foreach (v; graph[u]) {
              // u -> v,  u + 1 -> v - 1
              if (isGood(u + 1, v - 1)) {
                if (visR[u][0]) visR[v - 1][1] = true;
                if (visR[u][1]) visR[v - 1][0] = true;
              }
            }
          }
          long[4] cntR;
          foreach (u; /*!!!*/r - 1 .. N + 1) {
            int p;
            if (visR[u][0]) p |= 1 << 0;
            if (visR[u][1]) p |= 1 << 1;
            ++cntR[p];
          }

          debug {
            writeln("visL = ", visL);
            writeln("cntL = ", cntL);
            writeln("visR = ", visR);
            writeln("cntR = ", cntR);
          }

          foreach (p; 0 .. 4) foreach (q; 0 .. 4) {
            if (p & q) {
              ans += cntL[p] * cntR[q];
            }
          }
          if (l + 1 == r) {
            ans -= 1;
          }
        }
        writeln(ans);
      }
    }
  } 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)); }

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        int N = readInt;
        int M = readInt;
        auto A = new int[M];
        auto B = new int[M];
        foreach (i; 0 .. M) {
          A[i] = readInt;
          B[i] = readInt;
        }
        M += 2 * N;
        foreach (u; 1 .. N + 1) {
          A ~= 0;
          B ~= u;
          A ~= u;
          B ~= N + 1;
        }

        auto G = new int[][N + 2];
        auto H = new int[][N + 2];
        foreach (i; 0 .. M) {
          G[A[i]] ~= i;
          H[B[i]] ~= i;
        }

        auto fs = new int[N + 1];
        foreach (i; 0 .. M) {
          if (A[i] + 1 == B[i]) {
            fs[A[i]] = 1;
          }
        }
        auto fsSum = new int[N + 2];
        foreach (u; 0 .. N + 1) {
          fsSum[u + 1] = fsSum[u] + fs[u];
        }

        long ans;
        if (fsSum[N + 1] == N + 1) {
          ans = 1L * N * (N - 1) / 2;
        } else {
          int l = N + 1, r = 0;
          foreach (u; 0 .. N + 1) {
            if (!fs[u]) {
              chmin(l, u);
              chmax(r, u + 1);
            }
          }
          debug {
            writeln("fs = ", fs);
            writeln("l = ", l, ", r = ", r);
          }
          bool isGood(int u, int v) {
            return (u <= v && fsSum[v] - fsSum[u] == v - u);
          }

          // (u, u + 1) to (l, l + 1),  parity of # of steps
          auto visL = new bool[2][N + 1];
          visL[l][0] = true;
          foreach_reverse (u; 0 .. l + 1) {
            foreach (i; H[u + 1]) {
              // v -> u + 1,  v + 1 -> u
              const v = A[i];
              if (isGood(v + 1, u)) {
                if (visL[u][0]) visL[v][1] = true;
                if (visL[u][1]) visL[v][0] = true;
              }
            }
          }
          long[4] cntL;
          foreach (u; 0 .. l + 1) {
            int p;
            if (visL[u][0]) p |= 1 << 0;
            if (visL[u][1]) p |= 1 << 1;
            ++cntL[p];
          }

          // (l, l + 1) to (u, u + 1),  parity of # of steps
          auto visR = new bool[2][N + 1];
          visR[l][0] = true;
          foreach (u; l .. N + 1) {
            foreach (i; G[u]) {
              // u -> v,  u + 1 -> v - 1
              const v = B[i];
              if (isGood(u + 1, v - 1)) {
                if (visR[u][0]) visR[v - 1][1] = true;
                if (visR[u][1]) visR[v - 1][0] = true;
              }
            }
          }
          long[4] cntR;
          foreach (u; /*!!!*/r - 1 .. N + 1) {
            int p;
            if (visR[u][0]) p |= 1 << 0;
            if (visR[u][1]) p |= 1 << 1;
            ++cntR[p];
          }

          debug {
            writeln("visL = ", visL);
            writeln("cntL = ", cntL);
            writeln("visR = ", visR);
            writeln("cntR = ", cntR);
          }

          foreach (p; 0 .. 4) foreach (q; 0 .. 4) {
            if (p & q) {
              ans += cntL[p] * cntR[q];
            }
          }
          if (l + 1 == r) {
            ans -= 1;
          }
        }
        writeln(ans);
      }
    }
  } 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)); }

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        int N = readInt;
        int M = readInt;
        auto A = new int[M];
        auto B = new int[M];
        foreach (i; 0 .. M) {
          A[i] = readInt;
          B[i] = readInt;
        }
        M += 2 * N;
        foreach (u; 1 .. N + 1) {
          A ~= 0;
          B ~= u;
          A ~= u;
          B ~= N + 1;
        }

        auto G = new int[][N + 2];
        auto H = new int[][N + 2];
        foreach (i; 0 .. M) {
          G[A[i]] ~= i;
          H[B[i]] ~= i;
        }

        auto fs = new int[N + 1];
        foreach (i; 0 .. M) {
          if (A[i] + 1 == B[i]) {
            fs[A[i]] = 1;
          }
        }
        auto fsSum = new int[N + 2];
        foreach (u; 0 .. N + 1) {
          fsSum[u + 1] = fsSum[u] + fs[u];
        }

        long ans;
        if (fsSum[N + 1] == N + 1) {
          ans = 1L * N * (N - 1) / 2;
        } else {
          int l = N + 1, r = 0;
          foreach (u; 0 .. N + 1) {
            if (!fs[u]) {
              chmin(l, u);
              chmax(r, u + 1);
            }
          }
          debug {
            writeln("fs = ", fs);
            writeln("l = ", l, ", r = ", r);
          }
          bool isGood(int u, int v) {
            return (u <= v && fsSum[v] - fsSum[u] == v - u);
          }

          // (u, u + 1) to (l, l + 1),  parity of # of steps
          auto visL = new bool[2][N + 1];
          visL[l][0] = true;
          foreach_reverse (u; 0 .. l + 1) {
            foreach (i; H[u + 1]) {
              // v -> u + 1,  v + 1 -> u
              const v = A[i];
              if (isGood(v + 1, u)) {
                static foreach (s; 0 .. 2) {
                  if (visL[u][s]) {
                    visL[v][s ^ 1] = true;
                  }
                }
              }
            }
          }
          long[4] cntL;
          foreach (u; 0 .. l + 1) {
            int p;
            foreach (s; 0 .. 2) {
              if (visL[u][s]) {
                p |= 1 << s;
              }
            }
            ++cntL[p];
          }

          // (l, l + 1) to (u, u + 1),  parity of # of steps
          auto visR = new bool[2][N + 1];
          visR[l][0] = true;
          foreach (u; l .. N + 1) {
            foreach (i; G[u]) {
              // u -> v,  u + 1 -> v - 1
              const v = B[i];
              if (isGood(u + 1, v - 1)) {
                static foreach (s; 0 .. 2) {
                  if (visR[u][s]) {
                    visR[v - 1][s ^ 1] = true;
                  }
                }
              }
            }
          }
          long[4] cntR;
          foreach (u; /*!!!*/r - 1 .. N + 1) {
            int p;
            foreach (s; 0 .. 2) {
              if (visR[u][s]) {
                p |= 1 << s;
              }
            }
            ++cntR[p];
          }

          debug {
            writeln("visL = ", visL);
            writeln("cntL = ", cntL);
            writeln("visR = ", visR);
            writeln("cntR = ", cntR);
          }

          foreach (p; 0 .. 4) foreach (q; 0 .. 4) {
            if (p & q) {
              ans += cntL[p] * cntR[q];
            }
          }
          if (l + 1 == r) {
            ans -= 1;
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


New Year is coming! Vasya has prepared a New Year's verse and wants to recite it in front of Santa Claus.Vasya's verse contains $$$n$$$ parts. It takes $$$a_i$$$ seconds to recite the $$$i$$$-th part. Vasya can't change the order of parts in the verse: firstly he recites the part which takes $$$a_1$$$ seconds, secondly — the part which takes $$$a_2$$$ seconds, and so on. After reciting the verse, Vasya will get the number of presents equal to the number of parts he fully recited.Vasya can skip at most one part of the verse while reciting it (if he skips more than one part, then Santa will definitely notice it).Santa will listen to Vasya's verse for no more than $$$s$$$ seconds. For example, if $$$s = 10$$$, $$$a = [100, 9, 1, 1]$$$, and Vasya skips the first part of verse, then he gets two presents.Note that it is possible to recite the whole verse (if there is enough time). Determine which part Vasya needs to skip to obtain the maximum possible number of gifts. If Vasya shouldn't skip anything, print 0. If there are multiple answers, print any of them.You have to process $$$t$$$ test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$s$$$ ($$$1 \le n \le 10^5, 1 \le s \le 10^9$$$) — the number of parts in the verse and the maximum number of seconds Santa will listen to Vasya, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the time it takes to recite each part of the verse. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the number of the part that Vasya needs to skip to obtain the maximum number of gifts. If Vasya shouldn't skip any parts, print 0.

NoteIn the first test case if Vasya skips the second part then he gets three gifts.In the second test case no matter what part of the verse Vasya skips.In the third test case Vasya can recite the whole verse.

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

void solve() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1].to!long;
    auto A = readln.split.map!(to!long).array;
    long mx = -1;
    int mxi = -1;
    long sm = 0;
    bool erased = false;
    int skipped = -1;
    foreach (i, a; A) {
        if (sm + a <= M) {
            sm += a;
            if (a >= mx) {
                mx = a;
                mxi = i.to!int;
            }
        } else if (!erased) {
            if (a >= mx) {
                mx = a;
                mxi = i.to!int;
            }
            if (sm + a - mx <= M) {
                sm += a - mx;
                erased = true;
                skipped = mxi;
            } else {
                break;
            }
        } else {
            break;
        }
    }
    writeln(skipped + 1);
}

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

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.typecons;

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

alias Ans = Tuple!(int, int);

void main() {
  auto r = new InputReader;
  auto nt = r.next!uint;
  foreach (tid; 0 .. nt) {
    immutable n = r.next!uint.to!int;
    immutable s = r.next!uint;
    auto a = r.nextA!ulong(n);
    auto b = chain (only (0UL), a.cumulativeFold!((acc, x) => acc + x)).array;
    auto ans = Ans (0, 0);
    foreach (i; 1 .. n + 1) {
      if (b[i] <= s) ans = Ans (i, 0);
    }
    debug stderr.writeln (ans);
    auto e = assumeSorted (b);
    foreach (i; 0 .. n) {
      ulong x = s + a[i];
      auto rng = e.lowerBound (s + a[i] + 1);
      auto k = rng.length - 1;
      if (k >= (i + 1)) {
        auto cur = Ans ((k-1).to!int, (i + 1));
        if (ans[0] < cur[0]) ans = cur;
      }
      debug stderr.writeln (i, ' ', ans);
    }
    debug stderr.writeln (ans);
    writeln (ans[1]);
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	foreach(_; 0 .. rint){
		int n = rint;
		long s = rlong;
		long[] as = rlong(n);

		long[] sums  = [0];
		foreach(a; as) sums ~= sums[$ - 1] + a;
		long[] maxs = [0];
		foreach(a; as) maxs ~= max(maxs[$ - 1], a);

		if(sums[n] <= s) 0.writeln;
		else{
			int right = 1;
			long best = 0;
			foreach(i; 0 .. n + 1){
				long tmp = sums[i] - maxs[i];
				if(tmp <= s && best < i - 1){
					best = i - 1;
					right = i;
				}
			}
			int ans = 0;
			foreach(i; 0 .. right) if(as[i] == maxs[right]) ans = i + 1;
			ans.writeln;
		}

	}
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto s = RD!int;
		auto a = RDA;
		auto b = new long[](n+1);
		auto c = new long[][](n+1, 2);
		foreach (i; 0..n)
		{
			b[i+1] = b[i] + a[i];
			c[i+1] = c[i].dup;
			if (a[i] > c[i+1][0])
				c[i+1] = [a[i], i+1];
		}
		long best;
		int pos;
		foreach (i; 0..n)
		{
			if (b[i+1] <= s)
			{
				best = i+1;
				pos = 0;
			}
			else if (b[i+1] - c[i+1][0] <= s)
			{
				best = i;
				pos = cast(int)c[i+1][1];
			}
		}
		ans[ti] = pos;
	}

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


It is the easy version of the problem. The only difference is that in this version $$$k = 3$$$.You are given a positive integer $$$n$$$. Find $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, such that:  $$$a_1 + a_2 + \ldots + a_k = n$$$  $$$LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$$$ Here $$$LCM$$$ is the least common multiple of numbers $$$a_1, a_2, \ldots, a_k$$$.We can show that for given constraints the answer always exists.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 10^4)$$$  — the number of test cases. The only line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$3 \le n \le 10^9$$$, $$$k = 3$$$).

For each test case print $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, for which all conditions are satisfied.

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(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

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

		if (n % 2)
		{
			auto x = n - 1;
			ans[ti] = [1, x/2, x/2];
		}
		else if ((n/2) % 2)
		{
			auto x = n - 2;
			ans[ti] = [2, x/2, x/2];
		}
		else
		{
			ans[ti] = [n/2, n/4, n/4];
		}
	}

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


There are $$$n$$$ segments on a $$$Ox$$$ axis $$$[l_1, r_1]$$$, $$$[l_2, r_2]$$$, ..., $$$[l_n, r_n]$$$. Segment $$$[l, r]$$$ covers all points from $$$l$$$ to $$$r$$$ inclusive, so all $$$x$$$ such that $$$l \le x \le r$$$.Segments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is $$$l_i=r_i$$$ is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:  if $$$n=3$$$ and there are segments $$$[3, 6]$$$, $$$[100, 100]$$$, $$$[5, 8]$$$ then their union is $$$2$$$ segments: $$$[3, 8]$$$ and $$$[100, 100]$$$;  if $$$n=5$$$ and there are segments $$$[1, 2]$$$, $$$[2, 3]$$$, $$$[4, 5]$$$, $$$[4, 6]$$$, $$$[6, 6]$$$ then their union is $$$2$$$ segments: $$$[1, 3]$$$ and $$$[4, 6]$$$. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given $$$n$$$ so that the number of segments in the union of the rest $$$n-1$$$ segments is maximum possible.For example, if $$$n=4$$$ and there are segments $$$[1, 4]$$$, $$$[2, 3]$$$, $$$[3, 6]$$$, $$$[5, 7]$$$, then:  erasing the first segment will lead to $$$[2, 3]$$$, $$$[3, 6]$$$, $$$[5, 7]$$$ remaining, which have $$$1$$$ segment in their union;  erasing the second segment will lead to $$$[1, 4]$$$, $$$[3, 6]$$$, $$$[5, 7]$$$ remaining, which have $$$1$$$ segment in their union;  erasing the third segment will lead to $$$[1, 4]$$$, $$$[2, 3]$$$, $$$[5, 7]$$$ remaining, which have $$$2$$$ segments in their union;  erasing the fourth segment will lead to $$$[1, 4]$$$, $$$[2, 3]$$$, $$$[3, 6]$$$ remaining, which have $$$1$$$ segment in their union. Thus, you are required to erase the third segment to get answer $$$2$$$.Write a program that will find the maximum number of segments in the union of $$$n-1$$$ segments if you erase any of the given $$$n$$$ segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly $$$n-1$$$ segments.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2\cdot10^5$$$) — the number of segments in the given set. Then $$$n$$$ lines follow, each contains a description of a segment — a pair of integers $$$l_i$$$, $$$r_i$$$ ($$$-10^9 \le l_i \le r_i \le 10^9$$$), where $$$l_i$$$ and $$$r_i$$$ are the coordinates of the left and right borders of the $$$i$$$-th segment, respectively. The segments are given in an arbitrary order. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

Print $$$t$$$ integers — the answers to the $$$t$$$ given test cases in the order of input. The answer is the maximum number of segments in the union of $$$n-1$$$ segments if you erase any of the given $$$n$$$ segments.

import std.algorithm : maxElement, sort, swap;
import std.conv : to;
import std.range;
import std.stdio;
import std.typecons : Tuple, tuple;
import std.algorithm.mutation;

// import std.container.array;

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

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

void main()
{
    int T = readInt;
    while (T--)
    {
        int n = readInt;
        auto a = new Tuple!(int, int)[n];
        for (int i = 0; i < n; ++i)
        {
            a[i][0] = readInt;
            a[i][1] = readInt;
        }
        sort(a);
        int result = 0, mx0 = -1, mx1 = -1;
        int[] delta = new int[n];
        for (int i = 0; i < n; ++i)
        {
            if (mx0 == -1 || a[mx0][1] < a[i][0])
                result++, delta[i] = -1;
            else
            {
                delta[i] = 0;
                if (mx1 == -1 || a[mx1][1] < a[i][0])
                    delta[mx0]++;
            }
            int x = i;
            if (mx0 == -1 || a[x][1] > a[mx0][1])
                swap(mx0, x);
            if (~x && (mx1 == -1 || a[x][1] > a[mx1][1]))
                mx1 = x;
        }
        writeln(result + delta.maxElement);
    }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	foreach(_; 0 .. rint){
		int n = rint;
		A[] as;
		B[] bs;
		foreach(i; 0 .. n){
			long l = rlong * 2, r = rlong * 2 + 1;
			as ~= A(l, r);
			bs ~= B(l, 1);
			bs ~= B(r, 2);
		}
		bs.sort!((a, b) => a.x < b.x)();
		log("as:", as);
		log("bs:", bs);

		int[long] za;
		int zt = -1, f = 0;
		foreach(b; bs){
			if(f == b.f) za[b.x] = zt;
			else f = b.f, za[b.x] = (++ zt);
		}
		log("za:", za);

		int zmax = zt + 1;

		long[] us = new long[](zmax);
		foreach(b; bs) us[za[b.x]] += [0, 1, -1][b.f];
		log("us:", us);

		long[] vs = [0];
		foreach(u; us) vs ~= vs[$ - 1] + u;
		log("vs:", vs);

		int vcnt = 0;
		long oldv = 0;
		foreach(v; vs){
			if(oldv == 0 && v > 0) vcnt += 1;
			oldv = v;
		}
		log("vcnt:", vcnt);

		long[] ws = [0];
		long[] ws2 = [0];
		foreach(i; 1 .. zmax){
			if(vs[i - 1] > 1 && vs[i] == 1 && vs[i + 1] > 1) ws ~= ws[$ - 1] + 1;
			else ws ~= ws[$ - 1];
			if(vs[i - 1] == 0 && vs[i] == 1 && vs[i + 1] == 0) ws2 ~= ws2[$ - 1] + 1;
			else ws2 ~= ws2[$ - 1];
		}
		ws ~= ws[$ - 1];
		ws2 ~= ws2[$ - 1];
		log("ws:", ws);
		log("ws2:", ws2);

		long ans;
		foreach(a; as){
			log("a:", a);
			long tmp = vcnt + (ws[za[a.r]] - ws[za[a.l]]) - (ws2[za[a.r]] - ws2[za[a.l]]);
			log("a:", a, "tmp:", tmp);
			ans.chmax(tmp);
		}

		ans.writeln;

	}
}

struct A{
	long l, r;
}
struct B{
	long x;
	int f; // 1 = opening, 2 = closing
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	foreach(_; 0 .. rint){
		int n = rint;
		A[] as;
		B[] bs;
		foreach(i; 0 .. n){
			long l = rlong * 2, r = rlong * 2 + 1;
			as ~= A(l, r);
			bs ~= B(l, 1);
			bs ~= B(r, 2);
		}
		bs.sort!((a, b) => a.x < b.x)();
		log("as:", as);
		log("bs:", bs);

		int[long] za;
		int zt = -1, f = 0;
		foreach(b; bs){
			if(f == b.f) za[b.x] = zt;
			else f = b.f, za[b.x] = (++ zt);
		}
		log("za:", za);

		int zmax = zt + 1;

		long[] us = new long[](zmax);
		foreach(b; bs) us[za[b.x]] += [0, 1, -1][b.f];
		log("us:", us);

		long[] vs = [0];
		foreach(u; us) vs ~= vs[$ - 1] + u;
		log("vs:", vs);

		int vcnt = 0;
		long oldv = 0;
		foreach(v; vs){
			if(oldv == 0 && v > 0) vcnt += 1;
			oldv = v;
		}
		log("vcnt:", vcnt);

		long[] ws = [0];
		foreach(i; 1 .. zmax - 1){
			if(vs[i - 1] > 1 && vs[i] == 1 && vs[i + 1] > 1) ws ~= ws[$ - 1] + 1;
			else ws ~= ws[$ - 1];
		}
		ws ~= ws[$ - 1];
		log("ws:", ws);

		long ans;
		foreach(a; as){
			log("a:", a);
			long tmp = vcnt + ws[za[a.r]] - ws[za[a.l]];
			log("a:", a, "tmp:", tmp);
			ans.chmax(tmp);
		}

		ans.writeln;

	}
}

struct A{
	long l, r;
}
struct B{
	long x;
	int f; // 1 = opening, 2 = closing
}


You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers:  exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks).  exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$ and $$$k$$$ ($$$2 \le x \le 10^9$$$; $$$1 \le y, k \le 10^9$$$) — the number of sticks you can buy with one stick, the number of sticks required to buy one coal and the number of torches you need, respectively.

For each test case, print the answer: the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    ll x, y, k, s;
    x = rd; y = rd; k = rd;
    x -= 1;
    ll totake = (k*y + k - 1);
    ll trade = totake/x + (totake % x != 0) + k;
    writeln(trade);
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto a = k*y;
		auto b = k + a - 1;
		ans[ti] = (b+x-1) / x + k;
	}

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

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    ll x, y, k;
    x = rd; y = rd; k = rd;
    x -= 1;
    ll trade = 0;
    ll s = 1;
    ll left = k*y;
    trade += left/x + (left % x != 0);
    if(left % x != 0){ s = left % x; }
    left = k - s;
    trade += left/x + (left % x != 0);
    trade += k;
    writeln(trade);
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    ll x, y, k, s;
    x = rd; y = rd; k = rd;
    if(k == 1){
        writeln(0);
    }
    x -= 1;
    ll trade = 1;
    ll left = k*y - x - 1;
    trade += left/x + (left % x != 0);
    if(left % x != 0){ s = x - (left % x); }
    left = max(k - s, 0);
    debug writeln(" L ", left);
    trade += left/x + (left % x != 0);
    trade += k;
    writeln(trade);
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

void solve(){
    ll x, y, k, s;
    x = rd; y = rd; k = rd;
    x -= 1;
    ll trade = 1;
    ll left = k*y - x - 1;
    trade += left/x + (left % x != 0);
    if(left % x != 0){ s = x - (left % x); }
    left = max(k - s, 0);
    trade += left/x + (left % x != 0);
    trade += k;
    writeln(trade);
}

void main(){
    long t = 1;
    t = rd;
    while(t--) solve();
    stdout.flush;
}


A non-empty digit string is diverse if the number of occurrences of each character in it doesn't exceed the number of distinct characters in it.For example:   string "7" is diverse because 7 appears in it $$$1$$$ time and the number of distinct characters in it is $$$1$$$;  string "77" is not diverse because 7 appears in it $$$2$$$ times and the number of distinct characters in it is $$$1$$$;  string "1010" is diverse because both 0 and 1 appear in it $$$2$$$ times and the number of distinct characters in it is $$$2$$$;  string "6668" is not diverse because 6 appears in it $$$3$$$ times and the number of distinct characters in it is $$$2$$$. You are given a string $$$s$$$ of length $$$n$$$, consisting of only digits $$$0$$$ to $$$9$$$. Find how many of its $$$\frac{n(n+1)}{2}$$$ substrings are diverse.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Note that if the same diverse string appears in $$$s$$$ multiple times, each occurrence should be counted independently. For example, there are two diverse substrings in "77" both equal to "7", so the answer for the string "77" is $$$2$$$.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The second line of each test case contains a string $$$s$$$ of length $$$n$$$. It is guaranteed that all characters of $$$s$$$ are digits from $$$0$$$ to $$$9$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the number of diverse substrings of the given string $$$s$$$.

NoteIn the first test case, the diverse substring is "7".In the second test case, the only diverse substring is "7", which appears twice, so the answer is $$$2$$$.In the third test case, the diverse substrings are "0" ($$$2$$$ times), "01", "010", "1" ($$$2$$$ times), "10" ($$$2$$$ times), "101" and "1010".In the fourth test case, the diverse substrings are "0" ($$$3$$$ times), "01", "011", "0110", "1" ($$$2$$$ times), "10", "100", "110" and "1100".In the fifth test case, the diverse substrings are "3", "39", "399", "6", "9" ($$$4$$$ times), "96" and "996".In the sixth test case, all $$$15$$$ non-empty substrings of "23456" are diverse.

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

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

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

void solve() {
    int n = read!int;
    auto s = readln.strip();
    long res;
    foreach(i; 0 .. n) {
        int[10] num;
        int cnt, maxNum;
        foreach(k; i .. n) {
            auto t = s[k] - '0';
            if (num[t] >= 10)
                break;
            if(!num[t]) ++cnt;
            num[t]++;
            maxNum = max(maxNum, num[t]);
            if (maxNum <= cnt)
                ++res;
        }
    }
    writeln(res);
}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!int;
    auto s = readln.strip;
    long ans;
    foreach (i ; 0 .. s.length) {
      int used = 0;
      int distinct = 0;
      int[10] cnt;
      foreach (j ; i .. s.length) {
        int digit = cast(int)(s[j] - '0');
//        writeln(digit);
        if ((used & (1 << digit)) == 0)
          distinct++;
        used |= (1 << digit);
        if (++cnt[digit] > 10)
          break;
        bool good = true;
//        writeln(cnt);
        foreach (x ; cnt) {
          if (x > distinct) {
            good = false;
            break;
          }
        }
        if (good)
          ans++;
      }
    }
    writeln(ans);
  }
}

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

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

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

void solve() {
    int n = read!int;
    auto s = readln.strip();
    long res, max_freq;
    foreach(i; 0 .. n)
        foreach(k; i .. n) {
            max_freq = 0;
            if (k - i > 1) {
                auto tmp = s[i..k].array.sort;
                auto dist = tmp.uniq.array.length;
                auto freq = tmp.group;
                max_freq = (freq.maxElement!"a[1]")[1];
                if (max_freq <= dist)
                    res++;
            }
            else if (k - i == 1)
                res++;
            if (max_freq > 10)
                break;
        }
    writeln(res);
}

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

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

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

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

void solve() {
    int n = read!int;
    auto s = readln.strip();
    long res, max_freq;
    foreach(i; 0 .. n + 1)
        foreach(k; i .. n + 1) {
            if (k - i > 1) {
                auto tmp = s[i..k].array.sort;
                auto dist = tmp.uniq.array.length;
                auto freq = tmp.group;
                max_freq = (freq.maxElement!"a[1]")[1];
                if (max_freq <= dist)
                    res++;
            }
            else if (k - i == 1)
                res++;
            if (max_freq > 10)
                break;
        }
    writeln(res);
}

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

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

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

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

void solve() {
    int n = read!int;
    auto s = readln.strip();
    long res, max_freq;
    foreach(i; 0 .. n)
        foreach(k; i .. n + 1) {
            auto tmp = s[i..k].array.sort;
            if (k - i > 1) {
                auto dist = tmp.uniq.array.length;
                auto freq = tmp.group;
                max_freq = (freq.maxElement!"a[1]")[1];
                if (max_freq <= dist)
                    res++;
            }
            else if (k - i == 1)
                res++;
            if (max_freq > 10)
                break;
        }
    writeln(res);
}

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


Note that girls in Arpa’s land are really attractive.Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the ai-th chair, and his girlfriend, sitting on the bi-th chair. The chairs were numbered 1 through 2n in clockwise direction. There was exactly one person sitting on each chair.  There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that:   Each person had exactly one type of food,  No boy had the same type of food as his girlfriend,  Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs 2n and 1 are considered consecutive. Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.

The first line contains an integer n (1  ≤  n  ≤  105) — the number of pairs of guests. The i-th of the next n lines contains a pair of integers ai and bi (1  ≤ ai, bi ≤  2n) — the number of chair on which the boy in the i-th pair was sitting and the number of chair on which his girlfriend was sitting. It's guaranteed that there was exactly one person sitting on each chair.

If there is no solution, print -1. Otherwise print n lines, the i-th of them should contain two integers which represent the type of food for the i-th pair. The first integer in the line is the type of food the boy had, and the second integer is the type of food the girl had. If someone had Kooft, print 1, otherwise print 2. If there are multiple solutions, print any of them.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		alias Pair = Tuple !(int, q{u}, int, q{v});
		auto p = new Pair [n];
		foreach (i, ref x; p)
		{
			readf (" %s %s", &x.u, &x.v);
			x.u -= 1;
			x.v -= 1;
		}

		auto a = new int [] [n * 2];
		foreach (i; 0..n)
		{
			a[p[i].u] ~= p[i].v;
			a[p[i].v] ~= p[i].u;
		}
		foreach (i; 0..n)
		{
			a[i * 2 + 0] ~= i * 2 + 1;
			a[i * 2 + 1] ~= i * 2 + 0;
		}
		debug {writeln (a);}

		auto w = new int [n * 2];
		foreach (i; 0..n * 2)
		{
			if (w[i] == 0)
			{
				int prev = -1;
				int cur = i;
				int color = 1;
				do
				{
					w[cur] = color;
					color ^= 3;
					int next = (a[cur][0] == prev) ?
					    a[cur][1] : a[cur][0];
					prev = cur;
					cur = next;
				}
				while (cur != i);
			}
		}
		debug {writeln (w);}

		foreach (i; 0..n * 2)
		{
			assert (w[i] == 1 || w[i] == 2);
		}

		foreach (i; 0..n * 2)
		{
			int j = (i + 1) % (n * 2);
			int k = (i + n * 2 - 1) % (n * 2);
			assert (w[i] != w[j] || w[i] != w[k]);
		}

		foreach (i; 0..n)
		{
			assert (w[p[i].u] != w[p[i].v]);
		}

		foreach (i; 0..n)
		{
			writeln (w[p[i].u], " ", w[p[i].v]);
		}
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		alias Pair = Tuple !(int, q{u}, int, q{v});
		auto p = new Pair [n];
		foreach (i, ref x; p)
		{
			readf (" %s %s", &x.u, &x.v);
			x.u -= 1;
			x.v -= 1;
		}

		auto a = new int [] [n * 2];
		foreach (i; 0..n)
		{
			a[p[i].u] ~= p[i].v;
			a[p[i].v] ~= p[i].u;
		}
		foreach (i; 0..n)
		{
			a[i * 2 + 0] ~= i * 2 + 1;
			a[i * 2 + 1] ~= i * 2 + 0;
		}

		auto w = new int [n * 2];
		foreach (i; 0..n)
		{
			if (w[i] == 0)
			{
				int prev = -1;
				int cur = i;
				int color = 1;
				do
				{
					w[cur] = color;
					color ^= 3;
					int next = (a[cur][0] == prev) ?
					    a[cur][1] : a[cur][0];
					prev = cur;
					cur = next;
				}
				while (cur != i);
			}
		}

		foreach (i; 0..n)
		{
			writeln (w[p[i].u], " ", w[p[i].v]);
		}
	}
}


A camera you have accidentally left in a desert has taken an interesting photo. The photo has a resolution of n pixels width, and each column of this photo is all white or all black. Thus, we can represent the photo as a sequence of n zeros and ones, where 0 means that the corresponding column is all white, and 1 means that the corresponding column is black.You think that this photo can contain a zebra. In this case the whole photo should consist of several (possibly, only one) alternating black and white stripes of equal width. For example, the photo [0, 0, 0, 1, 1, 1, 0, 0, 0] can be a photo of zebra, while the photo [0, 0, 0, 1, 1, 1, 1] can not, because the width of the black stripe is 3, while the width of the white stripe is 4. Can the given photo be a photo of zebra or not?

The first line contains a single integer n (1 ≤ n ≤ 100 000) — the width of the photo. The second line contains a sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 1) — the description of the photo. If ai is zero, the i-th column is all black. If ai is one, then the i-th column is all white.

If the photo can be a photo of zebra, print "YES" (without quotes). Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteThe first two examples are described in the statements.In the third example all pixels are white, so the photo can be a photo of zebra.In the fourth example the width of the first stripe is equal to three (white color), the width of the second stripe is equal to three (black), and the width of the third stripe is equal to two (white). Thus, not all stripes have equal length, so this photo is not a photo of zebra.

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d",&n);
	int [] s = new int[n];
	for (int i=0; i<n; i++)
		scanf("%d", &s[i]);
	int x=0, y=0;
	bool isOk = true;
	for (int i=1; i<n; i++)
	{
		if (s[i] == s[i-1])
		{
			x++;
		}
		if (s[i] != s[i-1])
		{
			if (!isOk)
			{
				if (x != y)
				{
					printf("NO");
					return 0;
				}
			}
			if (isOk)
			{
				isOk = false;
			}
			y = x;
			x = 0;

		}
	}
	if (x != y && !isOk)
	{
		printf("NO");
		return 0;
	}
	printf("YES");
	return 0;
}

import std.algorithm;
import std.container;
import std.conv;
import std.exception;
import std.format;
import std.math;
import std.random;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main()
{
    immutable n = readln.strip.to!int;

    auto p = readln.strip.split.map!(a => to!int(a)).array;

    int w = 1;
    int prev = -1;
    bool ok = true;
    foreach (i; 1 .. n)
    {
        if (p[i - 1] == p[i])
        {
            w++;
        }
        else
        {
            ok &= prev < 0 || prev == w;
            prev = w;
            w = 1;
        }
    }
    ok &= prev < 0 || prev == w;

    writeln(ok ? "YES" : "NO");
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n,k;
	int curr;
	int firstPeriod;
	int currentPeriod;
	scanf("%d", &n);
	firstPeriod = 0;
	currentPeriod= 0;
	for(int i = 0; i<n; i++){
		scanf("%d", &k);
		if(i==0){
			curr = k;
		}

		if(curr!=k){
			if(firstPeriod == 0){
				firstPeriod = currentPeriod;
			}
			if(firstPeriod != currentPeriod){
					printf("No");
					return 0;
			}
			currentPeriod = 0;
			curr = k;
		}
		currentPeriod++;

	}

	if(currentPeriod == firstPeriod || firstPeriod == 0){
		printf("YES");
	} else {
		printf("NO");
	}
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &a[i]);
	int q;
	if (a[0] == 1) {
	    for (int i = 0; i < n; i++)
	        a[i] = (a[i] + 1) % 2;
	}
	int k = 0;
	while (k < n && a[k] == 0)
	    k++;
	if (k == n)
	{
	    printf("YES\n");
	    return 0;
	}
	int ok = (n % k == 0);
	int type = 0;
	for (int i = 0; i < n && ok; i += k)
	{
	    for (int j = 0; j < k; j++)
	        if (a[i] != a[i + j] || a[i] != type)
	            ok = 0;
	    type ^= 1;
	}
	if (ok)
	    printf("YES\n");
	else
	    printf("NO\n");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &a[i]);
	int q=1,lq=-1,ok=1;
	for(int i = 1; i<n; i++){
            if(a[i]==a[i-1])
                q++;
            else{
                if(lq!=-1 && q!=lq)
                    ok=0;
                lq=q;
                q=1;
            }
	}
	if(!ok || (lq!=-1 && lq!=q))
        printf("NO");
    else
        printf("YES");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n + 6];
	for(int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
	}
	int sz = 1;
	for(int i = 2; i <= n; i++) {
		if(a[i] != a[i - 1]) break;
		sz++;
	}
	if(sz == n) {
		printf("YES");
		return 0;
	}
	int cur = 1;
	for(int i = 2; i <= n; i++) {
		if(a[i] != a[i - 1]) {
			if(cur != sz) {
				printf("NO");
				return 0;
			}
			cur = 1;
		}
		else {
			cur++;
		}
	}
	if(cur != sz) {
		printf("NO");
		return 0;
	}
	printf("YES");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv) {
    int n,k;
    scanf("%d", &n);
    int [] arr = new int[n];
    for(int i = 0; i<n; i++)
        scanf("%d", &arr[i]);
    int q;
    for(int i = 0; i<n; i++)
        if(arr[0] == arr[i])
            q++;
        else break;
    int now = 1;
    if (k == n) {
        printf("YES");
        return 0;
    }
    for (int i = k+1; i<n; i++) {
        if (arr[i] != arr[i-1]) {
            if (now!=q) {
                printf("NO");
                return 0;
            }
            now = 1;
        } else now++;
    }
    if (now != q) {
        printf("NO");
        return 0;
    }
    printf("YES");
    return 0;
}

module main;

import core.stdc.stdio;

int main()
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n];
	int [] b = new int [n];
	int k = 1, id = 0;
	a[0]=-1;
	for(int i = 1; i <= n; i ++)
	{
		scanf("%d", &a[i]);
		if(a[i] == a[i - 1])
			k ++;
		else
		{
		    if(i != 1) {
			id ++;
			b[id] = k;
			k = 1;
			}
		}
	}
	id ++;
	b[id] = k;
	k = 1;
	int t = 0;
	for(int i = 2; i <= id; i ++)
	{
		if(b[i] != b[i - 1])
			t = 1;
	}
	if(t == 1)
		printf("NO");
	else
		printf("YES");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n,k;
	scanf("%d", &n);
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);

	k = 1;
	int w = -1;
	for(int i = 1; i<n; i++){
	    if (arr[i] == arr[i - 1])
	    {
	        k++;
	    }
	    else
	    {
	        if (w == -1)
	            w = k;
	        else
	        {
	            if (w != k)
	            {
	                //printf("%d ", k);
	                printf("NO");
	                return 0;
	            }

	        }
	        k = 1;

	    }
	}
	if (w == -1)
	  w = k;
	 else
	 {
	   if (w != k)
	    {
	                //printf("%d ", k);
	       printf("NO");
	       return 0;
      }

   }

	printf("YES");
	return 0;
}

import std.stdio;
import std.conv;
import core.stdc.stdio;
import std.string;
int a[100005];
int dp[100005];
int main(string[] argv)
{
	int n;
	int x = 0,y=0;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d",&a[i]);
		dp[i]=dp[i-1]+a[i];
		if (i>1) {if (a[i]!=a[i-1])
		{
		    if (x==0)
		    {
		        x=i-1;
		        y=i;
		    }
		    else {if (i-y==x) y=i;
		    else {printf("NO");return 0;}}
		}
		}

	}
	if (dp[n]==0) {printf("YES");return 0;}
	if (dp[n]==n) {printf("YES");return 0;}
	if (n-y==x-1)
	printf("YES");
	else printf("NO");
	return 0;
}

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

void main() {
	int n, x;
	int ans = 1;
	int a=0, b=0;
	int c=0, d=-1;
	scanf("%d", &n );
	for( int i = 1; i <= n; i ++ )
	{
	    scanf( "%d", &x );
	    if( d == -1 )
	    {
	        d = x;
	    }
	   if( d == x )
	   {
	        c ++;
	   }
	   else
	   {
	    if( x == 1 )
	    {
	        if( a == 0 )
	            a = c;
	       if( a != c )
	            ans = 0;
	    }
	    else
	    {
	        if( b == 0 )
	            b = c;
	        if( b != c )
	            ans = 0;
	    }
	    d = x;
	    c = 1;
	    }
  }
	if( d == 0 )
	{
    	if( a == 0 )
    	   a = c;
    	   if( a != c )
    	        ans = 0;
	}
	else
    {
        if( b == 0 )
            b = c;
	    if( b != c )
	        ans = 0;
	}
	if( a == 0 )
	    a = b;
	if( b == 0 )
	    b = a;
	if( a != b )
	    ans = 0;
	if( ans == 1 )
	    printf( "YES" );
	else
	    printf( "NO" );
}

import std.stdio;

void main() {
    int cnt = 0, temp = 0, last = -1;
    int n;
    readf("%d\n", &n);
    int a;
    int ok = 1;
    for (int i = 0; i < n; i++) {
        readf("%d ", &a);

        if (a == last) {
            temp++;
        } else {
            last = a;
            if (cnt > 0 && cnt != temp) {
                ok = 2;
                break;
            } else {
                cnt = temp;
                temp = 1;
            }
        }
    }
    if (cnt > 0 && cnt != temp) {
        ok = 2;
    }
    if (ok == 1) {
        write("YES\n");
    } else {
        write("NO\n");
    }
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	if (n == 1) {
	    printf("YES");
	    return 0;
	} else {
    	int[] array = new int[n];
    	for(int i = 0; i < n; i++) {
    		scanf("%d", &array[i]);
    	}
    	int j = 1;
    	for (; j < n && array[j] == array[j - 1]; ++j) {}
    	if (j == n) {
    	    printf("YES");
    	    return 0;
    	}
    	if (n % j != 0) {
    	    printf("NO");
    	    return 0;
    	}
	    for(int i = 0; i < n; i += j) {
	        if (i > 0 && array[i] == array[i - 1]) {
	            printf("NO");
	            return 0;
	        }
	        for(int k = i + 1; k < i + j; ++k) {
	            if (array[k] != array[k - 1]) {
	                printf("NO");
	                return 0;
	            }
	        }
	    }
	    printf("YES");
	    return 0;
	}
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] m = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &m[i]);
	int l = 1;
	for (int i = 1; i < n; ++i)
	    if (m[i] == m[i-1])
	        l += 1;
	    else
	        break;

	bool f = false;
	int frst = m[0];
	for (int i = 0; i < n; ++i){
	    if (i % l == 0)
	        f = !f;
	    if ((f && m[i] != frst) || (!f && m[i] == frst)){
	        printf("NO");
	        return 0;
	    }
	}
	if (n % l == 0){
	    printf("YES");
	}
	else{
	    printf("NO");
	}

	return 0;
}

module main;

import std.c.stdio;

void main(){
    int[100010] a;
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    int x=a[0];
    int res=1;
    int diff=0;
    int f=0;
    for(int i=1;i<n;i++){
        if(a[i]==x){
            res++;
        }
        else{
            x=a[i];
            if(diff==0) diff=res;
            else{
                if(res!=diff){
                    f=1;
                    break;
                }
            }
            res=1;
        }
    }
    if(res!=diff && diff!=0) f=1;
    if(!f) puts("YES");
    else puts("NO");

}

module main;

import core.stdc.stdio;

int main(string[] argv)
{
	int n,l,tmp;
	scanf("%d", &n);
	int [] a = new int[n+5];
	for(int i = 0; i<n; i++)
		scanf("%d", &a[i]);
	for(int i=0;i<n;i++)
	{
		if (i==0||a[i]==a[i-1])
		    l = i + 1;
		else break;
    }
	tmp = l;
	for(int i=0; i<n; i++)
	{
	    if (i==0||a[i]!=a[i-1])
	    {
	        if (tmp!=l)
	        {
	            printf("NO");
	            return 0;
	        }
	        tmp=1;
	    }
	    else tmp++;
	}
	if (tmp==l)
	    printf("YES");
	else
	    printf("NO");
	return 0;
}

import std.stdio;

void main() {
    int n;
    readf("%d ", &n);
    int init = -1;
    int size = -1;
    bool ans = true;
    for (int i = 0; i < n; i++) {
        int q;
        readf("%d ", &q);
        if (i == 0) {
            init = q;
        } else {
            if (size == -1) {
                if (q != init) {
                    size = i;
                }
            } else {
                if (q != (((i / size) + init) % 2)) {
                    ans = false;
                    break;
                }
            }
        }
    }
    if (ans && n % size == 0) {
        writeln("YES");
    } else {
        writeln("NO");
    }
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n,k;
	scanf("%d", &n);
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);

	int pr = -1;
	int ln = 1;
	int ch = arr[0];
	int fl = 0;
	for (int i = 1; i < n; i++) {
	    if (arr[i] == ch) {
	        ln++;
	    } else {
	        if (pr == -1) pr = ln;
	        if (pr != ln) fl = 1;
	        ln = 1;
	        ch = arr[i];
	    }
	}
	if (pr == -1) pr = ln;
	if (ln != pr) fl = 1;

	if (fl == 1) printf("NO"); else printf("YES");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);
	int nw=0;
	int ans=0;
	for(int i=0;i<n;i++){
	  if(i==0 || arr[i]==arr[i-1]) nw++;
	  else{
	    if(ans==0) ans=nw;
	    else{
	      if(ans!=nw){
	        printf("NO");
	        return 0;
	      }
	    }
	    nw=1;
	 }
	}
	 if(ans==0) ans=nw;
	    else{
	      if(ans!=nw){
	        printf("NO");
	        return 0;
	      }
	    }
	printf("YES");
	return 0;
}

//in the name of god
import std.stdio;
void main() {
	int w,x=1,y=-1,z,p;
	bool b=1;
	readf(" %s\n%s",&w,&z);
	for(int i = 1; i<w; i++){
	    readf(" %s",&p);
	    if(z!=p){
	        if(y==-1) y=x;
	        else if(y!=x) b=0;
	        x=1;
	    }
	    else x++;
	    z=p;
	}
	if(y==-1) y=x;
	else if(y!=x) b=0;
	writeln(b?"YES":"NO");
}

module main;
import std.c.stdio;
import std.algorithm;
import std.array;
void main()
{
    int n,w=0,b=0,col=0,x=0;
    scanf("%d",&n);
    auto a = new int[n];
    for (int i=0;i<n;i++)
        scanf("%d",&a[i]);
    for (int i=0;i<n;i++)
    {
        if (i>0 && a[i]!=a[i-1])
        {
            if (col==0)
                col=x;
            if (col!=x)
            {
                printf("NO");
                return ;
            }
            x=0;
        }
        x++;
    }
    if (x!=0 && x!=col && col!=0)
    {
        printf("NO");
        return ;
    }
    printf("YES");
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);
	int q;
	int cur = arr[0];
	int i=1;
	while(i<n && arr[i] == cur)
	i++;
	q=i;
	int c=0;
	int ans=1;
	while(i<n)
	{
	    cur=arr[i];
	    c=0;
	    while(i<n && arr[i] == cur)
	    {
	        c++;i++;
	    }
	    if(c!=q)
	    ans=0;
	}
	if(ans)
	printf("YES");
	else
	printf("NO");
	return 0;
}

import std.stdio;

void main() {
    int n;
    int[100005] a;
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    int cnt = -1;
    bool flag = 1;
    for (int i = 0; i < n; i++) {
        int j = i;
        for (j = i; j+1 < n && a[j+1] == a[i]; j++) {}
        if (cnt == -1 || j-i == cnt) {
            cnt = j-i;
            i = j;
        } else {
            flag = 0;
        }
    }
    if (flag) printf("YES"); else printf("NO");
}

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

void main(){

	int n;

	readf("%s", &n);
	readln;

	//  writeln(n);

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

	int x = a[0];
	int y = 1;

	int [100010]c;

	for (int i = 0; i < n; ++i){
		if (i == 0){
			++c[y];
			continue;
		}

		if (a[i] == a[i - 1]){
			++c[y];
			continue;
		}

		else{
			++y;
			c[y] = 1;
		}
	}

	int flag = 1;
	for (int i = 2; i <= y; ++i){
		if (c[i] != c[i - 1]){
			flag = 0;
			break;
		}
	}

	if (flag == 1) writeln("YES");
	else writeln("NO");

}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n+1];
	for(int i = 0; i<n; i++)
		scanf("%d", &a[i]);
	int q=1,lq=-1,ok=1;
	for(int i = 1; i<n; i++){
            if(a[i]==a[i-1])
                q++;
            else{
                if(lq!=-1 && q!=lq)
                    ok=0;
                lq=q;
                q=1;
            }
	}
	if(!ok || lq!=q)
        printf("NO");
    else
        printf("YES");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] a = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &a[i]);
	int q=1,lq=-1,ok=1;
	for(int i = 0; i<n; i++){
            if(a[i]==a[i-1])
                q++;
            else{
                if(lq!=-1 && q!=lq)
                    ok=0;
                lq=q;
                q=1;
            }
	}
	if(!ok || lq!=q)
        printf("NO");
    else
        printf("YES");
	return 0;
}

module main;

import std.c.stdio;

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	int [] arr = new int[n];
	for(int i = 0; i<n; i++)
		scanf("%d", &arr[i]);
	int nw=0;
	int ans=0;
	for(int i=0;i<n;i++){
	  if(i==0 || arr[i]==arr[i-1]) nw++;
	  else{
	    if(ans==0) ans=nw;
	    else{
	      if(ans!=nw){
	        printf("NO");
	        return 0;
	      }
	    }
	    nw=1;
	 }
	}
	 if(ans!=nw){
	        printf("NO");
	        return 0;
	      }
	printf("YES");
	return 0;
}

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

void main(){

	int n;

	readf("%s", &n);
	readln;

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

	int x = a[0];
	int y = 1;

	int [100010]c;

	for (int i = 0; i < n; ++i){
		if (i == 0){
			++c[y];
			continue;
		}

		if (a[i] == a[i - 1]){
			++c[y];
			continue;
		}

		else{
			++y;
			c[y] = 1;
		}
	}

	int flag = 1;
	for (int i = 2; i <= y; ++i){
		if (c[y] != c[y - 1]){
			flag = 0;
			break;
		}
	}

	if (flag == 1) writeln("YES");
	else writeln("NO");

}