Given the string $$$s$$$ of decimal digits (0-9) of length $$$n$$$.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes ($$$l, r$$$), where $$$1 \le l \le r \le n$$$, corresponds to a substring of the string $$$s$$$. We will define as $$$v(l,r)$$$ the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if $$$n=7$$$, $$$s=$$$"1003004", then $$$v(1,3)=100$$$, $$$v(2,3)=0$$$ and $$$v(2,7)=3004$$$.You are given $$$n$$$, $$$s$$$ and an integer $$$w$$$ ($$$1 \le w < n$$$).You need to process $$$m$$$ queries, each of which is characterized by $$$3$$$ numbers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n; 0 \le k_i \le 8$$$).The answer to the $$$i$$$th query is such a pair of substrings of length $$$w$$$ that if we denote them as $$$(L_1, L_1+w-1)$$$ and $$$(L_2, L_2+w-1)$$$, then:  $$$L_1 \ne L_2$$$, that is, the substrings are different;  the remainder of dividing a number $$$v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1)$$$ by $$$9$$$ is equal to $$$k_i$$$. If there are many matching substring pairs, then find a pair where $$$L_1$$$ is as small as possible. If there are many matching pairs in this case, then minimize $$$L_2$$$.Note that the answer may not exist.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — number of input test cases. The first line of each test case contains a string $$$s$$$, which contains only the characters 0-9 and has a length $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$). The second line contains two integers $$$w, m$$$ ($$$1 \le w < n, 1 \le m \le 2 \cdot 10^5$$$), where $$$n$$$ — is the length of the given string $$$s$$$. The number $$$w$$$ denotes the lengths of the substrings being searched for, and $$$m$$$ is the number of queries to be processed. The following $$$m$$$ lines contain integers $$$l_i, r_i, k_i$$$ ($$$1 \le l_i \le r_i \le n$$$, $$$0 \le k_i \le 8$$$) — $$$i$$$th query parameters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. It is also guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each request, print in a separate line:    left borders of the required substrings: $$$L_1$$$ and $$$L_2$$$; -1 -1 otherwise, if there is no solution.  If there are several solutions, minimize $$$L_1$$$ first, and minimize $$$L_2$$$ second.

NoteConsider the first test case of example inputs. In this test case $$$n=7$$$, $$$s=$$$"1003004", $$$w=4$$$ and one query $$$l_1=1$$$, $$$r_1=2$$$, $$$k_1=1$$$. Note that $$$v(1,2)=10$$$. We need to find a pair of substrings of length $$$4$$$ such that $$$v(L_1, L_1+3)\cdot10+v(L_2,L_2+3)$$$ has a remainder of $$$k_1=1$$$ when divided by $$$9$$$. The values $$$L_1=2, L_2=4$$$ actually satisfy all the requirements: $$$v(L_1, L_1+w-1)=v(2,5)=30$$$, $$$v(L_2, L_2+w-1)=v(4,7)=3004$$$. Indeed, $$$30\cdot10+3004=3304$$$, which has a remainder of $$$1$$$ when divided by $$$9$$$. It can be shown that $$$L_1=2$$$ is the minimum possible value, and $$$L_2=4$$$ is the minimum possible with $$$L_1=2$$$.

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

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

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

void solve() {
    auto S = read!string;
    int N = S.length;
    int W, M; readf("%d %d\n", &W, &M);
    auto L = new int[M];
    auto R = new int[M];
    auto K = new int[M];
    foreach (i; 0 .. M) {
        readf("%d %d %d\n", &L[i], &R[i], &K[i]);
    }

    int ord(char c) {
        return cast(int)(c - '0') % 9;
    }

    int x = 0;
    for (int i = 0; i < W; i++) {
        x = (x + ord(S[i])) % 9;
    }
    auto V = new int[N - W + 1];
    V[0] = x;
    for (int i = 1; i + W <= N; i++) {
        x = (x + 9 - ord(S[i - 1])) % 9;
        x = (x + ord(S[i - 1 + W])) % 9;
        V[i] = x;
    }

    auto X = new int[][9];
    for (int i = 0; i < N - W + 1; i++) {
        int v = V[i];
        if (X[v].length < 2) {
            X[v] ~= i;
        }
    }

    auto A = new int[N + 1];
    for (int i = 0; i < N; i++) {
        A[i + 1] = (A[i] + ord(S[i])) % 9;
    }

    auto ans = new int[][][](9, 9, 9);
    for (int vl0 = 0; vl0 <= 8; vl0++) {
        for (int vlr = 0; vlr <= 8; vlr++) {
            for (int k = 0; k <= 8; k++) {
                int vl1 = (9 * 9 + k - vl0 * vlr) % 9;
                int l1;
                if (vl0 == vl1) {
                    if (X[vl1].length <= 1) {
                        l1 = -2;
                    } else {
                        l1 = X[vl1][1];
                    }
                } else {
                    if (X[vl1].empty) {
                        l1 = -2;
                    } else {
                        l1 = X[vl1][0];
                    }
                }
                ans[vl0][vlr][k] = l1;
            }
        }
    }

    for (int m = 0; m < M; m++) {
        int li = L[m] - 1, ri = R[m], ki = K[m];
        int vlr = (9 * 10000 + A[ri] - A[li]) % 9;
        int L0 = INF, L1 = INF;
        for (int vl0 = 0; vl0 <= 8; vl0++) {
            if (X[vl0].empty) continue;
            auto l0 = X[vl0][0];
            auto l1 = ans[vl0][vlr][ki];
            if (l1 >= 0) {
                if (L0 > l0) {
                    L0 = l0;
                    L1 = l1;
                } else if (L0 == l0) {
                    L1 = min(L1, l1);
                }
            }
        }
        if (L0 == INF) {
            writeln("-1 -1");
        } else {
            writefln("%s %s", L0 + 1, L1 + 1);
        }
    }

    /*
    writeln("S: ", S);
    writeln("W: ", W);
    writeln("V: ", V);
    writeln("X: ", X);
    */
}
enum int INF = 1<<28;


Connect the countless points with lines, till we reach the faraway yonder.There are n points on a coordinate plane, the i-th of which being (i, yi).Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes through at least one point in the set.

The first line of input contains a positive integer n (3 ≤ n ≤ 1 000) — the number of points. The second line contains n space-separated integers y1, y2, ..., yn ( - 109 ≤ yi ≤ 109) — the vertical coordinates of each point.

Output "Yes" (without quotes) if it's possible to fulfill the requirements, and "No" otherwise. You can print each letter in any case (upper or lower).

NoteIn the first example, there are five points: (1, 7), (2, 5), (3, 8), (4, 6) and (5, 9). It's possible to draw a line that passes through points 1, 3, 5, and another one that passes through points 2, 4 and is parallel to the first one.In the second example, while it's possible to draw two lines that cover all points, they cannot be made parallel.In the third example, it's impossible to satisfy both requirements at the same time.

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

  int n; rd(n);
  auto y=readln.split.to!(long[]);

  alias pt=Tuple!(long, "x", long ,"y");
  pt[] f(long dy, long dx){
    pt[] rt;
    foreach(x; 1..n){
      long dy_=y[x]-y[0];
      if(dy*x!=dy_*dx) rt~=pt(x, y[x]);
    }
    return rt;
  }

  bool g(long _dy, long _dx, pt[] ys){
    if(ys.length==0) return false;
    if(ys.length==1) return true;
    long dy=ys[1].y-ys[0].y;
    long dx=ys[1].x-ys[0].x;
    if(_dy*dx!=dy*_dx) return false;
    foreach(i; 1..ys.length){
      long dy_=ys[i].y-ys[0].y;
      long dx_=ys[i].x-ys[0].x;
      if(dy*dx_!=dy_*dx) return false;
    }
    return true;
  }

  foreach(x; 1..n){
    long dy=y[x]-y[0];
    // int dx=x;
    auto rs=f(dy, x);
    // writeln(x, " ", rs);

    if(g(dy, x, rs)){
      writeln("Yes");
      return;
    }
  }

  // l1={1}, l2={2, 3, ..., n};
  long dydy=y[2]-y[1];
  // int dxdx=2-1;
  pt[] rsrs;
  foreach(x; 2..y.length){
    long dy_dy=y[x]-y[1];
    if(dydy*(x-1)!=dy_dy*1) rsrs~=pt(x, y[x]);
  }
  if(rsrs.length==0){
    if(y[1]-y[0]!=dydy){
      writeln("Yes"); return;
    }
  }

  writeln("No");
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  foreach(i, ref e; x){
    e=l[i].to!(typeof(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 N = readInt();
      auto Y = new long[N];
      foreach (x; 0 .. N) {
        Y[x] = readLong();
      }

      bool ans;
      foreach (i; 0 .. 2) {
        foreach (j; 0 .. N) {
          if (i != j) {
            // (i, Y[i]), (j, Y[j])
            int[] xs;
            foreach (x; 0 .. N) {
              if ((j - i) * (Y[x] - Y[i]) != (Y[j] - Y[i]) * (x - i)) {
                xs ~= x;
              }
            }
            if (!xs.empty) {
              bool ok = true;
              foreach (x; xs) {
                if ((j - i) * (Y[x] - Y[xs[0]]) != (Y[j] - Y[i]) * (x - xs[0])) {
                  ok = false;
                }
              }
              if (ok) {
                ans = true;
              }
            }
          }
        }
      }
      writeln(ans ? "Yes" : "No");
    }
  } catch (EOFException e) {
  }
}


Given a string s, find the number of ways to split s to substrings such that if there are k substrings (p1, p2, p3, ..., pk) in partition, then pi = pk - i + 1 for all i (1 ≤ i ≤ k) and k is even.Since the number of ways can be large, print it modulo 109 + 7.

The only line of input contains a string s (2 ≤ |s| ≤ 106) of even length consisting of lowercase Latin letters.

Print one integer, the number of ways of partitioning the string modulo 109 + 7.

NoteIn the first case, the only way to partition the string is ab|cd|cd|ab.In the second case, the string can be partitioned as ab|b|ab|ab|ab|ab|b|ab or ab|b|abab|abab|b|ab or abbab|ab|ab|abbab.

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 = 10^^9 + 7;
alias Mint = ModInt!MO;

class Eertree(int size, char offset) {
  string s;
  int n;
  int[] us, len, fail, slink;
  int[] next;
  this(in string s) {
    this.s = s;
    n = cast(int)(s.length);
    us = new int[n + 3];
    len = new int[n + 3];
    fail = new int[n + 3];
    slink = new int[n + 3];
    next = new int[(n + 3) * size];
    us[1] = 1; len[1] = -1; fail[1] = 1; slink[1] = 1;
    us[2] = 2; len[2] =  0; fail[2] = 1; slink[2] = 1;
    foreach (i; 0 .. n) {
      const c = s[i] - offset;
      int u = us[i + 2];
      for (; !isSuffix(i, u); u = fail[u]) {}
      if (!next[u * size + c]) {
        next[u * size + c] = i + 3;
        len[i + 3] = len[u] + 2;
        if (u == 1) {
          fail[i + 3] = 2;
          slink[i + 3] = 2;
        } else {
          int v = fail[u];
          for (; !isSuffix(i, v); v = fail[v]) {}
          fail[i + 3] = next[v * size + c];
          slink[i + 3] = (len[i + 3] - len[fail[i + 3]] == len[fail[i + 3]] - len[fail[fail[i + 3]]]) ? slink[fail[i + 3]] : fail[i + 3];
        }
      }
      us[i + 3] = next[u * size + c];
    }
  }
  bool isSuffix(int i, int u) const {
    const j = i - 1 - len[u];
    return (j >= 0 && s[j] == s[i]);
  }
  void print() const {
    void dfs(int u, string prefix, int type) {
      writefln("%s%s%s %s %s", prefix, ["", "|-- ", "`-- "][type],
               (len[u] <= 0) ? ("(" ~ len[u].to!string ~ ")")
                             : s[u - 2 - len[u] .. u - 2],
               u, fail[u]);
      const vs = next[u * size .. (u + 1) * size].filter!(v => v).array;
      foreach (v; vs) {
        dfs(v, prefix ~ ["", "|   ", "    "][type], (v == vs[$ - 1]) ? 2 : 1);
      }
    }
    dfs(1, "", 0);
    dfs(2, "  ", 0);
  }
}

void main() {
  try {
    for (; ; ) {
      const S = readToken();
      const N = cast(int)(S.length) / 2;

      string T;
      foreach (i; 0 .. N) {
        T ~= S[i];
        T ~= S[2 * N - 1 - i];
      }
      const t = new Eertree!(26, 'a')(T);
      debug {
        t.print;
        writeln("T = ", T);
        writeln("us = ", t.us);
        writeln("fail = ", t.fail);
        writeln("slink = ", t.slink);
        writeln("diff = ", iota(t.n + 3).map!(u => t.len[u] - t.len[t.fail[u]]));
      }

      debug {
        auto brt = new Mint[N + 1];
        brt[0] = 1;
        foreach (i; 1 .. N + 1) {
          for (int u = t.us[2 * i + 2]; u > 2; u = t.fail[u]) {
            if (t.len[u] % 2 == 0) {
              debug {
                writeln(i, " ", u, " ", t.len[u]);
              }
              brt[i] += brt[i - t.len[u] / 2];
            }
          }
        }
        writeln("brt = ", brt);
      }

      auto dp = new Mint[t.n + 1];
      auto sdp = new Mint[t.n + 3];
      dp[0] = 1;
      foreach (i; 1 .. t.n + 1) {
        for (int u = t.us[i + 2]; u > 2; u = t.slink[u]) {
          sdp[u] = dp[i - t.len[u] + t.len[t.fail[u]] - t.len[t.slink[u]]];
          if (t.len[u] - t.len[t.fail[u]] == t.len[t.fail[u]] - t.len[t.fail[t.fail[u]]]) {
            sdp[u] += sdp[t.fail[u]];
          }
          dp[i] += sdp[u];
        }
        if (i % 2 != 0) {
          dp[i] = 0;
        }
      }
      debug {
        writeln("dp = ", dp);
        writeln("sdp = ", sdp);
      }
      writeln(dp[2 * N]);
    }
  } catch (EOFException e) {
  }
}


You are given a connected undirected graph consisting of $$$n$$$ vertices and $$$m$$$ edges. There are no self-loops or multiple edges in the given graph.You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges).

The first line contains two integer numbers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n - 1 \le m \le 2 \cdot 10^5$$$) — the number of vertices and edges, respectively. The following $$$m$$$ lines contain edges: edge $$$i$$$ is given as a pair of vertices $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$). There are no multiple edges in the given graph, i. e. for each pair ($$$u_i, v_i$$$) there are no other pairs ($$$u_i, v_i$$$) and ($$$v_i, u_i$$$) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph).

If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length $$$m$$$. The $$$i$$$-th element of this string should be '0' if the $$$i$$$-th edge of the graph should be directed from $$$u_i$$$ to $$$v_i$$$, and '1' otherwise. Edges are numbered in the order they are given in the input.

NoteThe picture corresponding to the first example: And one of possible answers:

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

immutable long MOD = 10^^9 + 7;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto G = new Tuple!(int, int, int)[][](N);
    foreach (i; 0..M) {
        s = readln.split.map!(to!int);
        G[s[0]-1] ~= tuple(s[1]-1, i, 0);
        G[s[1]-1] ~= tuple(s[0]-1, i, 1);
    }

    auto C = new int[](N);
    C[] = -1;

    bool dfs(int n, int c) {
        if (C[n] != -1) {
            return C[n] == c;
        }
        C[n] = c;
        foreach (m; G[n]) {
            if (!dfs(m[0], c^1)) {
                return false;
            }
        }
        return true;
    }

    if (!dfs(0, 0)) {
        writeln("NO");
        return;
    }

    auto ans = new int[](M);
    foreach (i; 0..N) {
        foreach (e; G[i]) {
            if (C[i] != e[2]) {
                ans[e[1]] = 1;
            }
        }
    }

    writeln("YES");
    ans.map!(to!string).join("").writeln;
}

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

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

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

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

        --u, --v;
        g[u] ~= v;
        g[v] ~= u;
        edges ~= tuple(u, v);
    }

    auto clr = new int[] (n);
    bool dfs(int v, int clrnow) {
        auto ok = true;
        clr[v] = clrnow;
        foreach (u; g[v]) {
            if (clr[u] == 0) { ok &= dfs(u, 3 - clrnow); }
            else if (clr[u] == clrnow) { return false; }
        }

        return ok;
    }

    auto ok = dfs(1, 1);

    if (!ok) {
        writeln("NO");
        return;
    }

    int[] ans;
    foreach (e; edges) {
        ans ~= clr[e[0]] - 1;
    }

    writeln("YES");
    ans.writefln!"%(%s%)";
}


You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.You know that you have $$$n$$$ bacteria in the Petri dish and size of the $$$i$$$-th bacteria is $$$a_i$$$. Also you know intergalactic positive integer constant $$$K$$$.The $$$i$$$-th bacteria can swallow the $$$j$$$-th bacteria if and only if $$$a_i > a_j$$$ and $$$a_i \le a_j + K$$$. The $$$j$$$-th bacteria disappear, but the $$$i$$$-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria $$$i$$$ can swallow any bacteria $$$j$$$ if $$$a_i > a_j$$$ and $$$a_i \le a_j + K$$$. The swallow operations go one after another.For example, the sequence of bacteria sizes $$$a=[101, 53, 42, 102, 101, 55, 54]$$$ and $$$K=1$$$. The one of possible sequences of swallows is: $$$[101, 53, 42, 102, \underline{101}, 55, 54]$$$ $$$\to$$$ $$$[101, \underline{53}, 42, 102, 55, 54]$$$ $$$\to$$$ $$$[\underline{101}, 42, 102, 55, 54]$$$ $$$\to$$$ $$$[42, 102, 55, \underline{54}]$$$ $$$\to$$$ $$$[42, 102, 55]$$$. In total there are $$$3$$$ bacteria remained in the Petri dish.Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.

The first line contains two space separated positive integers $$$n$$$ and $$$K$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le K \le 10^6$$$) — number of bacteria and intergalactic constant $$$K$$$. The second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — sizes of bacteria you have.

Print the only integer — minimal possible number of bacteria can remain.

NoteThe first example is clarified in the problem statement.In the second example an optimal possible sequence of swallows is: $$$[20, 15, 10, 15, \underline{20}, 25]$$$ $$$\to$$$ $$$[20, 15, 10, \underline{15}, 25]$$$ $$$\to$$$ $$$[20, 15, \underline{10}, 25]$$$ $$$\to$$$ $$$[20, \underline{15}, 25]$$$ $$$\to$$$ $$$[\underline{20}, 25]$$$ $$$\to$$$ $$$[25]$$$.In the third example no bacteria can swallow any other bacteria.

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

immutable long MOD = 10^^9+7;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto A = readln.split.map!(to!int).array;
    A.sort();
    int ans = 0;
    int tmp = 1;
    int prev = -1;

    foreach (i; 0..N-1) {
        if (A[i+1] == A[i]) {
            ++tmp;
        }
        else {
            if (A[i+1] <= A[i] + K)
                ans += tmp;
            tmp = 1;
        }
    }

    ans = N - ans;
    ans.writeln;
}

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.complex, std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

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
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///int length
		int sz(T)(ref const T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///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))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///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))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///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 assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			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;
			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)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int n, k;
	read(n, k);
	auto a = arread!int;
	sort(a);
	debug writeln(a);
	int p;
	int c = 1;
	foreach (i; 1 .. n)
	{
		if (a[i] > a[i - 1] && a[i] <= a[i - 1] + k)
		{
			p += c;
			c = 1;
		}
		else if (a[i] == a[i - 1])
			c++;
		else
			c = 1;
	}
	writeln(n - p);
}

import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

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

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

    a.sort();

    debug { a.writeln; }

    SList!int res;
    foreach (e; a) {
        while (!res.empty && res.front < e && e <= res.front + k) res.removeFront();
        res.insertFront(e);
    }

    res.array.length.writeln;
}

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

  int n, k; rd(n, k);
  auto a=readln.split.to!(int[]);

  int num=0, c=1;
  sort(a);
  // writeln(a);
  foreach(i; 1..n){
    if(a[i-1]==a[i]){
      c++;
    }else{
      if(a[i-1]+k<a[i]) num+=c;
      c=1;
    }
  }
  // writeln(num);
  // writeln(c);
  writeln(num+c);
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}


A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ of length $$$n$$$ containing each number exactly once. For example, $$$[1]$$$, $$$[4, 3, 5, 1, 2]$$$, $$$[3, 2, 1]$$$ are permutations, and $$$[1, 1]$$$, $$$[0, 1]$$$, $$$[2, 2, 1, 4]$$$ are not.There was a permutation $$$p[1 \dots n]$$$. It was merged with itself. In other words, let's take two instances of $$$p$$$ and insert elements of the second $$$p$$$ into the first maintaining relative order of elements. The result is a sequence of the length $$$2n$$$.For example, if $$$p=[3, 1, 2]$$$ some possible results are: $$$[3, 1, 2, 3, 1, 2]$$$, $$$[3, 3, 1, 1, 2, 2]$$$, $$$[3, 1, 3, 1, 2, 2]$$$. The following sequences are not possible results of a merging: $$$[1, 3, 2, 1, 2, 3$$$], [$$$3, 1, 2, 3, 2, 1]$$$, $$$[3, 3, 1, 2, 2, 1]$$$.For example, if $$$p=[2, 1]$$$ the possible results are: $$$[2, 2, 1, 1]$$$, $$$[2, 1, 2, 1]$$$. The following sequences are not possible results of a merging: $$$[1, 1, 2, 2$$$], [$$$2, 1, 1, 2]$$$, $$$[1, 2, 2, 1]$$$.Your task is to restore the permutation $$$p$$$ by the given resulting sequence $$$a$$$. It is guaranteed that the answer exists and is unique.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 400$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of permutation. The second line of the test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the array $$$a$$$ represents the result of merging of some permutation $$$p$$$ with the same permutation $$$p$$$.

For each test case, print the answer: $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$), representing the initial permutation. It is guaranteed that the answer exists and is unique.

import std.stdio;
import std.string : split, strip;
import std.algorithm : map, joiner;
import std.conv : to, text;

void main()
{
  int t;
  readf!"%d\n"(t);

  foreach (i; 0..t) {
    int n;
    readf!"%d\n"(n);

    auto a = readln.strip.split.map!(to!int);
    bool[] s = new bool[n];
    int[] o = new int[n];

    int p = 0;

    foreach (j; a) {
      if (s[j-1]) continue;
      s[j-1] = true;

      o[p++] = j;
    }

    writeln(o.map!text.joiner(" "));
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		bool [int] used;
		int [] p;
		foreach (ref c; a)
		{
			if (c !in used)
			{
				p ~= c;
				used[c] = true;
			}
		}
		writefln !("%(%s %)") (p);
	}
}


It is the easy version of the problem. The only difference is that in this version $$$a_i \le 200$$$.You are given an array of $$$n$$$ integers $$$a_0, a_1, a_2, \ldots a_{n - 1}$$$. Bryap wants to find the longest beautiful subsequence in the array.An array $$$b = [b_0, b_1, \ldots, b_{m-1}]$$$, where $$$0 \le b_0 < b_1 < \ldots < b_{m - 1} < n$$$, is a subsequence of length $$$m$$$ of the array $$$a$$$.Subsequence $$$b = [b_0, b_1, \ldots, b_{m-1}]$$$ of length $$$m$$$ is called beautiful, if the following condition holds:   For any $$$p$$$ ($$$0 \le p < m - 1$$$) holds: $$$a_{b_p} \oplus b_{p+1} < a_{b_{p+1}} \oplus b_p$$$. Here $$$a \oplus b$$$ denotes the bitwise XOR of $$$a$$$ and $$$b$$$. For example, $$$2 \oplus 4 = 6$$$ and $$$3 \oplus 1=2$$$.Bryap is a simple person so he only wants to know the length of the longest such subsequence. Help Bryap and find the answer to his question.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_0,a_1,...,a_{n-1}$$$ ($$$0 \leq a_i \leq 200$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case print a single integer — the length of the longest beautiful subsequence.

NoteIn the first test case, we can pick the whole array as a beautiful subsequence because $$$1 \oplus 1 < 2 \oplus 0$$$.In the second test case, we can pick elements with indexes $$$1$$$, $$$2$$$ and $$$4$$$ (in $$$0$$$-indexation). For this elements holds: $$$2 \oplus 2 < 4 \oplus 1$$$ and $$$4 \oplus 4 < 1 \oplus 2$$$.

import std.stdio;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

void solve() {
    int N = readln.chomp.to!int;
    auto A = readln.chomp.split(" ").map!(to!uint).array;

    auto f = new int[N];
    f[0] = 1;
    for (int k = 1; k < N; k++) {
        f[k] = 1;
        for (int j = max(0, k-512); j < k; j++) {
            if ( (A[j] ^ k) < (A[k] ^ j) ) {
                f[k] = max(f[k], f[j] + 1);
            }
        }
    }
    writeln(f.reduce!max);
}

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


You are given an integer $$$n$$$ and an array $$$a_1, a_2, \ldots, a_n$$$. You should reorder the elements of the array $$$a$$$ in such way that the sum of $$$\textbf{MEX}$$$ on prefixes ($$$i$$$-th prefix is $$$a_1, a_2, \ldots, a_i$$$) is maximized.Formally, you should find an array $$$b_1, b_2, \ldots, b_n$$$, such that the sets of elements of arrays $$$a$$$ and $$$b$$$ are equal (it is equivalent to array $$$b$$$ can be found as an array $$$a$$$ with some reordering of its elements) and $$$\sum\limits_{i=1}^{n} \textbf{MEX}(b_1, b_2, \ldots, b_i)$$$ is maximized.$$$\textbf{MEX}$$$ of a set of nonnegative integers is the minimal nonnegative integer such that it is not in the set.For example, $$$\textbf{MEX}(\{1, 2, 3\}) = 0$$$, $$$\textbf{MEX}(\{0, 1, 2, 4, 5\}) = 3$$$.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$  — the number of test cases. The first line of each test case contains a single integer $$$n$$$ $$$(1 \le n \le 100)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(0 \le a_i \le 100)$$$.

For each test case print an array $$$b_1, b_2, \ldots, b_n$$$  — the optimal reordering of $$$a_1, a_2, \ldots, a_n$$$, so the sum of $$$\textbf{MEX}$$$ on its prefixes is maximized. If there exist multiple optimal answers you can find any.

// Vicfred
// https://codeforces.com/contest/1497/problem/A
// sorting, greedy
import std.algorithm;
import std.array;
import std.conv;
import std.container;
import std.stdio;
import std.string;

void main() {
    int t = readln.chomp.to!int;

while(t--) {
    int n = readln.chomp.to!int;
    int[] a = readln.split.map!(to!int).array;

    auto unique = redBlackTree(a);
    auto dups = redBlackTree!true(a);

    foreach(number; unique) {
        writef("%s ", number);
        dups.removeKey(number);
    }
    foreach(number; dups) {
        writef("%s ", number);
    }
    "".writeln;
}
}

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(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 a = RDA!int;

		auto cnt = new long[](101);
		foreach (e; a)
			++cnt[e];

		int[] rem;
		foreach (i; 0..cnt.length)
		{
			if (cnt[i] == 0) continue;
			ans[ti] ~= cast(int)i;
			foreach (j; 1..cnt[i])
				rem ~= cast(int)i;
		}
		ans[ti] ~= rem;
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}

import std.stdio, std.string, std.algorithm, std.conv, std.range;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int n;
        readf!"%d\n"(n);
        int[] a = readln.split.map!(to!int).array, res;
        a.sort();
        foreach (i; 0 .. n)
            if (!i || a[i] != a[i - 1])
                res ~= [a[i]];
        foreach (i; 0 .. n)
            if (i && a[i] == a[i - 1])
                res ~= [a[i]];
        res.map!(to!string).join(" ").writeln;
    }
}

// Vicfred
// https://codeforces.com/contest/1497/problem/A
// sorting, greedy
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

long mex(long[] numbers) {
    long[long] missing;
    foreach(number; numbers) {
        missing[number] = 1L;
    }

    long mex = 0L;
    for(long i = 0L; i <= 100L; ++i) {
        auto p = (i in missing);
        if(p is null) {
            mex = i;
            return mex;
        }
    }
    return mex;
}

void main() {
    long t = readln.chomp.to!long;

while(t--) {
    long n = readln.chomp.to!long;
    long[] a = readln.split.map!(to!long).array;
    a.sort;

    foreach(number; a) {
        writef("%s ", number);
    } "".writeln;
}
}


You are given a square grid with $$$n$$$ rows and $$$n$$$ columns. Each cell contains either $$$0$$$ or $$$1$$$. In an operation, you can select a cell of the grid and flip it (from $$$0 \to 1$$$ or $$$1 \to 0$$$). Find the minimum number of operations you need to obtain a square that remains the same when rotated $$$0^{\circ}$$$, $$$90^{\circ}$$$, $$$180^{\circ}$$$ and $$$270^{\circ}$$$.The picture below shows an example of all rotations of a grid.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the size of the grid. Then $$$n$$$ lines follow, each with $$$n$$$ characters $$$a_{i,j}$$$ ($$$0 \leq a_{i,j} \leq 1$$$) — the number written in each cell.

For each test case output a single integer  — the minimum number of operations needed to make the square look the same rotated $$$0^{\circ}$$$, $$$90^{\circ}$$$, $$$180^{\circ}$$$ and $$$270^{\circ}$$$.

NoteIn the first test case, we can perform one operations to make the grid $$$\begin{matrix}0 & 1 & 0\\ 1 & 1 & \color{red}{1}\\ 0 & 1 & 0\end{matrix}$$$. Now, all rotations of the square are the same.In the second test case, all rotations of the square are already the same, so we don't need any flips.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto board = new string [n];
		foreach (ref line; board)
		{
			line = readln.strip;
		}

		int res = 0;
		foreach (row; 0..(n + 0) / 2)
		{
			foreach (col; 0..(n + 1) / 2)
			{
				int s = 0;
				s += board[row][col] - '0';
				s += board[col][n - 1 - row] - '0';
				s += board[n - 1 - row][n - 1 - col] - '0';
				s += board[n - 1 - col][row] - '0';
				res += min (s, 4 - s);
			}
		}
		writeln (res);
	}
}


You are given a sequence $$$a$$$ of length $$$n$$$ consisting of $$$0$$$s and $$$1$$$s.You can perform the following operation on this sequence:   Pick an index $$$i$$$ from $$$1$$$ to $$$n-2$$$ (inclusive).  Change all of $$$a_{i}$$$, $$$a_{i+1}$$$, $$$a_{i+2}$$$ to $$$a_{i} \oplus a_{i+1} \oplus a_{i+2}$$$ simultaneously, where $$$\oplus$$$ denotes the bitwise XOR operation  Find a sequence of at most $$$n$$$ operations that changes all elements of $$$a$$$ to $$$0$$$s or report that it's impossible.We can prove that if there exists a sequence of operations of any length that changes all elements of $$$a$$$ to $$$0$$$s, then there is also such a sequence of length not greater than $$$n$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 2\cdot10^5$$$) — the length of $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$) — elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, do the following:    if there is no way of making all the elements of $$$a$$$ equal to $$$0$$$ after performing the above operation some number of times, print "NO".  otherwise, in the first line print "YES", in the second line print $$$k$$$ ($$$0 \le k \le n$$$) — the number of operations that you want to perform on $$$a$$$, and in the third line print a sequence $$$b_1, b_2, \dots, b_k$$$ ($$$1 \le b_i \le n - 2$$$) — the indices on which the operation should be applied.  If there are multiple solutions, you may print any.

NoteIn the first example, the sequence contains only $$$0$$$s so we don't need to change anything.In the second example, we can transform $$$[1, 1, 1, 1, 0]$$$ to $$$[1, 1, 0, 0, 0]$$$ and then to $$$[0, 0, 0, 0, 0]$$$ by performing the operation on the third element of $$$a$$$ and then on the first element of $$$a$$$.In the third example, no matter whether we first perform the operation on the first or on the second element of $$$a$$$ we will get $$$[1, 1, 1, 1]$$$, which cannot be transformed to $$$[0, 0, 0, 0]$$$.

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

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

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

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

void main() {
  debug {
    foreach (n; 1 .. 8 + 1) {
      auto prv = new int[1 << n];
      prv[] = -1;
      prv[0] = -2;
      for (; ; ) {
        bool upd;
        foreach (p; 0 .. 1 << n) {
          if (!~prv[p]) {
            foreach (i; 0 .. n - 2) {
              const s = popcnt((p >> i) & 7) & 1;
              int pp = p;
              if (s) {
                pp |= 7 << i;
              } else {
                pp &= ~(7 << i);
              }
              if (~prv[pp]) {
                prv[p] = i;
                upd = true;
                break;
              }
            }
          }
        }
        if (!upd) {
          break;
        }
      }
      foreach (p; 0 .. 1 << n) {
        /*
        if (~prv[p]) {
          foreach (i; 0 .. n) {
            write((p >> i) & 1);
          }
          writeln(" ", prv[p]);
        }
        */
        if (!(popcnt(p) & 1) && !~prv[p]) {
          foreach (i; 0 .. n) {
            write((p >> i) & 1);
          }
          writeln;
        }
      }
      writeln(n, ": ", (1 << n) - prv.count(-1));
    }
  }

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

        auto sumA = new int[N + 1];
        foreach (i; 0 .. N) {
          sumA[i + 1] = sumA[i] + A[i];
        }

        int[] ans;
        void waf(int l, int r) {
          for (int i = r - 3; i >= l; i -= 2) {
            ans ~= i;
          }
          for (int i = l + 2; i + 3 <= r; i += 2) {
            ans ~= i;
          }
        }

        if (N % 2 == 0) {
          for (int k = 1; k < N; k += 2) {
            if (sumA[k] % 2 == 0 && (sumA[N] - sumA[k]) % 2 == 0) {
              debug {
                writeln("k = ", k);
              }
              waf(0, k);
              waf(k, N);
              break;
            }
          }
        } else {
          if (sumA[N] % 2 == 0) {
            waf(0, N);
          }
        }

        if (ans) {
          writeln("YES");
          writeln(ans.length);
          foreach (index, i; ans) {
            if (index > 0) write(" ");
            write(i + 1);
          }
          writeln;
        } else {
          writeln("NO");
        }
      }
    }
  } catch (EOFException e) {
  }
}


Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.

The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.

If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.

abc
ab
6
a b 4
a b 7
b a 8
c b 11
c a 3
a c 0

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;

immutable int INF = 10 ^^ 8;

void main()
{
    string[2] s;
    foreach (i; 0 .. 2) {
        s[i] = readln.chomp;
    }

    auto cost = new int[][] (300, 300);
    foreach (i; 'a' .. 'z'+1) { cost[i][] = INF; }

    int q;
    readf("%s", &q);
    readln;
    foreach (i; 0 .. q) {
        char a, b; int c;
        readf("%s %s %s", &a, &b, &c);
        readln;
        cost[a.to!int][b.to!int] = min(cost[a.to!int][b.to!int], c);
    }

    if (s[0].length != s[1].length) {
        writeln(-1);
        return;
    }

    foreach (u; 'a' .. 'z' + 1) {
        foreach (v1; 'a' .. 'z' + 1) {
            foreach (v2; 'a' .. 'z' + 1) {
                cost[v1][v2] = min(cost[v1][v2], cost[v1][u] + cost[u][v2]);
            }
        }
    }

    debug {
        foreach (v1; 'a' .. 'z' + 1) {
            foreach (v2; 'a' .. 'z' + 1) {
                if (cost[v1][v2] != INF) {
                    writeln(v1.to!dchar, ' ', v2.to!dchar, ' ', cost[v1][v2]);
                }
            }
        }
    }

    int ans = 0;
    dchar[] res;
    foreach (a, b; lockstep(s[0], s[1])) {
        int curbest = INF;
        dchar curltr = 'a';
        auto toChg = [a, b];
        foreach (ltr; 'a' .. 'z' + 1) {
            int cur = 0;
            foreach (e; toChg) {
                if (e == ltr) { continue; }

                cur += cost[e][ltr];
            }

            if (cur < curbest) {
                curbest = cur;
                curltr = ltr.to!dchar;
            }
        }

        if (curbest == INF) {
            writeln(-1);
            return;
        }

        ans += curbest;
        res ~= curltr;
    }

    ans.writeln;
    res.writeln;
}

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()
{
    string[2] s;
    foreach (i; 0 .. 2) {
        s[i] = readln.chomp;
    }

    auto cost = new int[][] (300, 300);
    foreach (i; 'a' .. 'z'+1) { cost[i][] = 10 ^^ 9; }
    int q;
    readf("%s", &q);
    readln;
    foreach (i; 0 .. q) {
        char a, b; int c;
        readf("%s %s %s", &a, &b, &c);
        debug { writeln(a, ' ', b, ' ', c); }
        readln;
        cost[a.to!int][b.to!int] = min(cost[a.to!int][b.to!int], c);
    }

    if (s[0].length != s[1].length) {
        writeln(-1);
        return;
    }

    int ans = 0;
    dchar[] res;
    foreach (a, b; lockstep(s[0], s[1])) {
        int curbest = 10 ^^ 9;
        dchar curltr = 'a';
        auto toChg = [a, b];
        foreach (ltr; 'a' .. 'z' + 1) {
            int cur = 0;
            foreach (e; toChg) {
                if (e == ltr) { continue; }

                cur += cost[e][ltr];
            }

            if (cur < curbest) {
                curbest = cur;
                curltr = ltr.to!dchar;
            }
        }

        if (curbest == 10 ^^ 9) {
            writeln(-1);
            return;
        }

        ans += curbest;
        res ~= curltr;
    }

    ans.writeln;
    res.writeln;
}

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()
{
    string[2] s;
    foreach (i; 0 .. 2) {
        s[i] = readln.chomp;
    }

    auto cost = new int[][] (300, 300);
    foreach (i; 'a' .. 'z'+1) { cost[i][] = -1; }
    int q;
    readf("%s", &q);
    readln;
    foreach (i; 0 .. q) {
        char a, b; int c;
        readf("%s %s %s", &a, &b, &c);
        debug { writeln(a, ' ', b, ' ', c); }
        readln;
        cost[a.to!int][b.to!int] = c;
    }

    if (s[0].length != s[1].length) {
        writeln(-1);
        return;
    }

    int ans = 0;
    dchar[] res;
    foreach (a, b; lockstep(s[0], s[1])) {
        int curbest = 10 ^^ 9;
        dchar curltr = 'a';
        auto toChg = [a, b];
        outer: foreach (ltr; 'a' .. 'z' + 1) {
            int cur = 0;
            foreach (e; toChg) {
                if (e == ltr) { continue; }

                if (cost[e][ltr] == -1) {
                    continue outer;
                }

                cur += cost[e][ltr];
            }

            if (cur < curbest) {
                curbest = cur;
                curltr = ltr.to!dchar;
            }
        }

        if (curbest == 10 ^^ 9) {
            writeln(-1);
            return;
        }

        ans += curbest;
        res ~= curltr;
    }

    ans.writeln;
    res.writeln;
}


Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct positions in the array. Also note that Petya must swap some two integers even if the original array meets all requirements.Array a (the array elements are indexed from 1) consisting of n elements is called sorted if it meets at least one of the following two conditions:  a1 ≤ a2 ≤ ... ≤ an;  a1 ≥ a2 ≥ ... ≥ an. Help Petya find the two required positions to swap or else say that they do not exist.

The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n non-negative space-separated integers a1, a2, ..., an — the elements of the array that Petya's mother presented him. All integers in the input do not exceed 109.

If there is a pair of positions that make the array unsorted if swapped, then print the numbers of these positions separated by a space. If there are several pairs of positions, print any of them. If such pair does not exist, print -1. The positions in the array are numbered with integers from 1 to n.

NoteIn the first two samples the required pairs obviously don't exist.In the third sample you can swap the first two elements. After that the array will look like this: 2 1 3 4. This array is unsorted.

import std.stdio : writeln, writefln;
import std.array;
import std.range;
import std.algorithm : sort , filter;

int n;
int[] arr;

void swap(T)(ref T a, ref T b){
	T tmp = a;
	a = b;
	b = tmp;
}

void main(){
	n.next;
	arr = new int[n];
	int[][int] list;
	for(int i=0; i<n; ++i){
		arr[i].next;
		list[arr[i]] ~= i;
	}

	int[] r = arr.dup.sort;
	int[] d = r.retro.array;

	if(filter!(a => a != arr[0])(arr).array.length == 0){
		writeln = -1;
		return;
	}

	bool flag = false;
	LOOP:
	for(int i=0; i<n; ++i){
		foreach(num, idxs; list){
			if(num>arr[i]){
				foreach(idx; idxs){
					swap(arr[i], arr[idx]);
					if(arr == r || arr == d){
						swap(arr[i], arr[idx]);
						continue;
					}
					writefln("%d %d", i+1, idx+1);
					flag = true;
					break LOOP;
				}
			}
		}
	}

	/+
	for(int i=0; i<n; ++i){
		for(int j=i+1; j<n; ++j){
			if(arr[i] != arr[j]){
				swap(arr[i], arr[j]);
				if(arr == r || arr == d){
					swap(arr[i], arr[j]);
					continue;
				}
				writefln("%d %d",i+1, j+1);
				return;
			}
		}
	}
	+/

	if(!flag){ writeln("-1"); }
}

import std.stdio : readln, chomp;
import std.conv : to;
import std.string : split;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}

import std.stdio : writeln, writefln;
import std.array;
import std.range;
import std.algorithm : filter, max, sort;
import std.math : sqrt;

int n;
int[] arr;

void swap(T)(ref T a, ref T b){
	T tmp = a;
	a = b;
	b = tmp;
}

void main(){
	n.next;
	arr = new int[n];
	foreach(ref v; arr){
		v = next!int();
	}

	int[] r = arr.dup;
	r.sort;
	int[] d = r.dup.retro.array;

	swap(arr[0], arr[$-1]);

	if(r==arr || d==arr){
		writeln = -1;
	}else{
		writefln("%d %d", arr[$-1], arr[0]);
	}
}

import std.stdio : readln, chomp;
import std.conv : to;
import std.string : split;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}

import std.stdio : writeln, writefln;
import std.array;
import std.range;
import std.algorithm : filter, max, sort;
import std.math : sqrt;

int n;
int[] arr;

void swap(T)(ref T a, ref T b){
	T tmp = a;
	a = b;
	b = tmp;
}

void main(){
	n.next;
	arr = new int[n];
	foreach(ref v; arr){
		v = next!int();
	}

	int[] r = arr.dup;
	r.sort;
	int[] d = r.dup.retro.array;

	swap(arr[0], arr[$-1]);

	if(r==arr || d==arr){
		writeln = -1;
	}else{
		writefln("%d %d", 1, n);
	}
}

import std.stdio : readln, chomp;
import std.conv : to;
import std.string : split;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}

import std.stdio : writeln, writefln;
import std.array;
import std.range;
import std.algorithm : filter, max, sort;
import std.math : sqrt;

int n;
int[] arr;

void swap(T)(ref T a, ref T b){
	T tmp = a;
	a = b;
	b = tmp;
}

void main(){
	n.next;
	arr = new int[n];
	foreach(ref v; arr){
		v = next!int();
	}

	int[] r = arr.dup;
	r.sort;
	int[] d = r.dup.retro.array;

	int idx = r == arr ? 0 : 1;
	auto f = [(int a, int b){return a < b;}, (int a, int b){return a > b;}];

	for(int i=1; i<n; ++i){
		if(f[idx](arr[i-1], arr[i])){
			int[] tmp = arr.dup;
			swap(tmp[i], tmp[i-1]);
			if(r == tmp || d == tmp){ continue; }

			writefln("%d %d", i, i+1);
			return;
		}
	}

	writeln("-1");
}

import std.stdio : readln, chomp;
import std.conv : to;
import std.string : split;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}


You are the owner of a harvesting field which can be modeled as an infinite line, whose positions are identified by integers.It will rain for the next $$$n$$$ days. On the $$$i$$$-th day, the rain will be centered at position $$$x_i$$$ and it will have intensity $$$p_i$$$. Due to these rains, some rainfall will accumulate; let $$$a_j$$$ be the amount of rainfall accumulated at integer position $$$j$$$. Initially $$$a_j$$$ is $$$0$$$, and it will increase by $$$\max(0,p_i-|x_i-j|)$$$ after the $$$i$$$-th day's rain.A flood will hit your field if, at any moment, there is a position $$$j$$$ with accumulated rainfall $$$a_j>m$$$.You can use a magical spell to erase exactly one day's rain, i.e., setting $$$p_i=0$$$. For each $$$i$$$ from $$$1$$$ to $$$n$$$, check whether in case of erasing the $$$i$$$-th day's rain there is no flood.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq m \leq 10^9$$$) — the number of rainy days and the maximal accumulated rainfall with no flood occurring. Then $$$n$$$ lines follow. The $$$i$$$-th of these lines contains two integers $$$x_i$$$ and $$$p_i$$$ ($$$1 \leq x_i,p_i \leq 10^9$$$) — the position and intensity of the $$$i$$$-th day's rain. The sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a binary string $$$s$$$ length of $$$n$$$. The $$$i$$$-th character of $$$s$$$ is 1 if after erasing the $$$i$$$-th day's rain there is no flood, while it is 0, if after erasing the $$$i$$$-th day's rain the flood still happens.

NoteIn the first test case, if we do not use the spell, the accumulated rainfall distribution will be like this:  If we erase the third day's rain, the flood is avoided and the accumulated rainfall distribution looks like this:  In the second test case, since initially the flood will not happen, we can erase any day's rain.In the third test case, there is no way to avoid the flood.

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

immutable long infinity = long.max / 8;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);

		alias Rain = Tuple !(long, q{x}, long, q{p});
		auto r = new Rain [n];
		foreach (ref c; r)
		{
			readf !(" %s %s") (c.x, c.p);
		}

		alias Event = Tuple !(long, q{x}, long, q{delta});
		Event [] e;
		e.reserve (n * 3);
		foreach (ref c; r)
		{
			e ~= Event (c.x - c.p, +1);
			e ~= Event (c.x, -2);
			e ~= Event (c.x + c.p, +1);
		}
		sort (e);

		auto x = new long [n * 3];
		auto y = new long [n * 3];
		long cur = e[0].delta;
		x[0] = e[0].x;
		foreach (i; 1..n * 3)
		{
			x[i] = e[i].x;
			y[i] = y[i - 1] + cur * (x[i] - x[i - 1]);
			cur += e[i].delta;
		}

		auto lo = new long [n * 3];
		lo[0] = -infinity;
		foreach (i; 1..n * 3)
		{
			lo[i] = lo[i - 1];
			if (y[i] > m)
			{
				lo[i] = max (lo[i], y[i] - x[i]);
			}
		}

		auto hi = new long [n * 3];
		hi[$ - 1] = -infinity;
		foreach_reverse (i; 0..n * 3 - 1)
		{
			hi[i] = hi[i + 1];
			if (y[i] > m)
			{
				hi[i] = max (hi[i], y[i] + x[i]);
			}
		}

		auto xs = x.assumeSorted ();

		auto answer = new bool [n];
		foreach (i; 0..n)
		{
			answer[i] = true;
			auto pos = xs.lowerBound (r[i].x).length;
			answer[i] &= (lo[pos] + x[pos] - r[i].p <= m);
			answer[i] &= (hi[pos] - x[pos] - r[i].p <= m);
		}

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

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        const M = readLong;
        auto X = new long[N];
        auto P = new long[N];
        foreach (i; 0 .. N) {
          X[i] = readLong;
          P[i] = readLong;
        }

        alias Entry = Tuple!(long, "x", long, "a", long, "b");
        auto es = new Entry[3 * N];
        foreach (i; 0 .. N) {
          es[i * 3 + 0] = Entry(X[i] - P[i], +1, -(X[i] - P[i]));
          es[i * 3 + 1] = Entry(X[i]       , -2, +2 * X[i]);
          es[i * 3 + 2] = Entry(X[i] + P[i], +1, -(X[i] + P[i]));
        }
        es.sort;

        long maxS = long.min;
        long maxT = long.min;
        {
          long a, b;
          foreach (ref e; es) {
            const x = e.x;
            const y = (a * x + b) - M;
            debug {
              writeln(x, " ", y);
            }
            if (y > 0) {
              chmax(maxS, y + x);
              chmax(maxT, y - x);
            }
            a += e.a;
            b += e.b;
          }
        }

        auto ans = new char[N];
        foreach (i; 0 .. N) {
          const s = P[i] + X[i];
          const t = P[i] - X[i];
          ans[i] = (s >= maxS && t >= maxT) ? '1' : '0';
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from $$$a_1, a_2, \ldots, a_n$$$ to $$$-a_1, -a_2, \ldots, -a_n$$$. For some unknown reason, the number of service variables is always an even number.William understands that with his every action he attracts more and more attention from the exchange's security team, so the number of his actions must not exceed $$$5\,000$$$ and after every operation no variable can have an absolute value greater than $$$10^{18}$$$. William can perform actions of two types for two chosen variables with indices $$$i$$$ and $$$j$$$, where $$$i < j$$$:  Perform assignment $$$a_i = a_i + a_j$$$  Perform assignment $$$a_j = a_j - a_i$$$  William wants you to develop a strategy that will get all the internal variables to the desired values.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 20$$$). Description of the test cases follows. The first line of each test case contains a single even integer $$$n$$$ ($$$2 \le n \le 10^3$$$), which is the number of internal variables. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, which are initial values of internal variables.

For each test case print the answer in the following format: The first line of output must contain the total number of actions $$$k$$$, which the strategy will perform. Note that you do not have to minimize $$$k$$$. The inequality $$$k \le 5\,000$$$ must be satisfied.  Each of the next $$$k$$$ lines must contain actions formatted as "type i j", where "type" is equal to "1" if the strategy needs to perform an assignment of the first type and "2" if the strategy needs to perform an assignment of the second type. Note that $$$i < j$$$ should hold. We can show that an answer always exists.

NoteFor the first sample test case one possible sequence of operations is as follows:  "2 1 2". Values of variables after performing the operation: [1, 0, 1, 1]  "2 1 2". Values of variables after performing the operation: [1, -1, 1, 1]  "2 1 3". Values of variables after performing the operation: [1, -1, 0, 1]  "2 1 3". Values of variables after performing the operation: [1, -1, -1, 1]  "2 1 4". Values of variables after performing the operation: [1, -1, -1, 0]  "2 1 4". Values of variables after performing the operation: [1, -1, -1, -1]  "1 1 2". Values of variables after performing the operation: [0, -1, -1, -1]  "1 1 2". Values of variables after performing the operation: [-1, -1, -1, -1] For the second sample test case one possible sequence of operations is as follows:  "2 1 4". Values of variables after performing the operation: [4, 3, 1, -2]  "1 2 4". Values of variables after performing the operation: [4, 1, 1, -2]  "1 2 4". Values of variables after performing the operation: [4, -1, 1, -2]  "1 2 4". Values of variables after performing the operation: [4, -3, 1, -2]  "1 3 4". Values of variables after performing the operation: [4, -3, -1, -2]  "1 1 2". Values of variables after performing the operation: [1, -3, -1, -2]  "1 1 2". Values of variables after performing the operation: [-2, -3, -1, -2]  "1 1 4". Values of variables after performing the operation: [-4, -3, -1, -2]

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

void swaptwo(int i, int j)
{
  int opcount = 6;
  int oplist = 0x9;
  while (opcount-- > 0) {
    if (oplist & 1)
      printf("1 %d %d\n", i, j);
    else
      printf("2 %d %d\n", i, j);
    oplist >>= 1;
  }
}

void main()
{
  int t, n;
  readf!" %d"(t);
  while (t--) {
    readf!" %d"(n);
    readln;
    auto a = readln.chomp.split.map!(to!int).array;

    writeln(n / 2 * 6);
    int idx = 1;
    while (idx <= a.length) {
      swaptwo(idx, idx + 1);
      idx += 2;
    }
  }
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		foreach (i; 0..n/2)
		{
			ans[ti] ~= [1, i+1, n-i];
			ans[ti] ~= [1, i+1, n-i];
			ans[ti] ~= [2, i+1, n-i];
			ans[ti] ~= [1, i+1, n-i];
			ans[ti] ~= [1, i+1, n-i];
			ans[ti] ~= [2, i+1, n-i];
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		writeln (n * 3);
		for (int i = 1; i <= n; i += 2)
		{
			writeln (1, " ", i, " ", i + 1);
			writeln (2, " ", i, " ", i + 1);
			writeln (1, " ", i, " ", i + 1);

			writeln (1, " ", i, " ", i + 1);
			writeln (2, " ", i, " ", i + 1);
			writeln (1, " ", i, " ", i + 1);
		}
	}
}

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

void swaptwo(int i, int j)
{
  int opcount = 6;
  int oplist = 0x9;
  while (opcount-- > 0) {
    if (oplist & 1)
      printf("1 %d %d\n", i, j);
    else
      printf("2 %d %d\n", i, j);
    oplist >>= 1;
  }
}

void main()
{
  int t, n;
  readf!" %d"(t);
  while (t--) {
    readf!" %d"(n);
    readln;
    auto a = readln.chomp.split.map!(to!int).array;

    writeln(n / 2 * 6);
    int idx = 0;
    while (idx < a.length) {
      swaptwo(idx, idx + 1);
      idx += 2;
    }
  }
}


Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it:Consider an $$$n$$$ by $$$n$$$ chessboard. Its rows are numbered from $$$1$$$ to $$$n$$$ from the top to the bottom. Its columns are numbered from $$$1$$$ to $$$n$$$ from the left to the right. A cell on an intersection of $$$x$$$-th row and $$$y$$$-th column is denoted $$$(x, y)$$$. The main diagonal of the chessboard is cells $$$(x, x)$$$ for all $$$1 \le x \le n$$$.A permutation of $$$\{1, 2, 3, \dots, n\}$$$ is written on the main diagonal of the chessboard. There is exactly one number written on each of the cells. The problem is to partition the cells under and on the main diagonal (there are exactly $$$1+2+ \ldots +n$$$ such cells) into $$$n$$$ connected regions satisfying the following constraints:  Every region should be connected. That means that we can move from any cell of a region to any other cell of the same region visiting only cells of the same region and moving from a cell to an adjacent cell.  The $$$x$$$-th region should contain cell on the main diagonal with number $$$x$$$ for all $$$1\le x\le n$$$.  The number of cells that belong to the $$$x$$$-th region should be equal to $$$x$$$ for all $$$1\le x\le n$$$.  Each cell under and on the main diagonal should belong to exactly one region.

The first line contains a single integer $$$n$$$ ($$$1\le n \le 500$$$) denoting the size of the chessboard. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$. $$$p_i$$$ is the number written on cell $$$(i, i)$$$. It is guaranteed that each integer from $$$\{1, \ldots, n\}$$$ appears exactly once in $$$p_1$$$, ..., $$$p_n$$$.

If no solution exists, output $$$-1$$$. Otherwise, output $$$n$$$ lines. The $$$i$$$-th line should contain $$$i$$$ numbers. The $$$j$$$-th number on the $$$i$$$-th line should be $$$x$$$ if cell $$$(i, j)$$$ belongs to the the region with $$$x$$$ cells.

NoteThe solutions to the examples are illustrated in the following pictures:

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 solve(const(int) N, const(int[]) P) {
  auto ans = new int[][](N + 2, N + 2);
  foreach (i; 1 .. N + 1) {
    int x = i, y = i;
    ans[x][y] = P[i];
    foreach (_; 1 .. P[i]) {
      if (y - 1 >= 1 && !ans[x][y - 1]) {
        ans[x][y - 1] = P[i];
        --y;
      } else if (x + 1 <= N && !ans[x + 1][y]) {
        ans[x + 1][y] = P[i];
        ++x;
      } else {
        assert(false);
      }
    }
  }
  foreach (i; 1 .. N + 1) {
    foreach (j; 1 .. i + 1) {
      if (j > 1) write(" ");
      write(ans[i][j]);
    }
    writeln;
  }
}

void main() {
  debug {
    foreach (n; 1 .. 8 + 1) {
      auto perm = iota(n + 1).array;
      do {
        writeln(perm);
        solve(n, perm);
      } while (perm[1 .. n + 1].nextPermutation);
    }
  }

  try {
    for (; ; ) {
      const N = readInt();
      auto P = new int[N + 1];
      foreach (i; 1 .. N + 1) {
        P[i] = readInt();
      }

      solve(N, P);
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto p = readln.splitter.map !(to !(int)).array;
		int [] [] answer;
		foreach (i; 0..n)
		{
			answer ~= new int [i + 1];
		}
		foreach (i; 0..n)
		{
			answer[i][i] = p[i];
		}
		foreach (d; 0..n - 1)
		{
			bool shift = false;
			foreach (i; d..n)
			{
				auto value = answer[i][i - d];
				if (value == d + 1)
				{
					shift = true;
				}
				else
				{
					if (shift)
					{
						answer[i][i - d - 1] = value;
					}
					else
					{
						answer[i + 1][i - d] = value;
					}
				}
			}
		}
		writefln !("%(%(%s %)\n%)") (answer);
	}
}


Recently, Norge found a string $$$s = s_1 s_2 \ldots s_n$$$ consisting of $$$n$$$ lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string $$$s$$$. Yes, all $$$\frac{n (n + 1)}{2}$$$ of them!A substring of $$$s$$$ is a non-empty string $$$x = s[a \ldots b] = s_{a} s_{a + 1} \ldots s_{b}$$$ ($$$1 \leq a \leq b \leq n$$$). For example, "auto" and "ton" are substrings of "automaton".Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only $$$k$$$ Latin letters $$$c_1, c_2, \ldots, c_k$$$ out of $$$26$$$.After that, Norge became interested in how many substrings of the string $$$s$$$ he could still type using his broken keyboard. Help him to find this number.

The first line contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq k \leq 26$$$) — the length of the string $$$s$$$ and the number of Latin letters still available on the keyboard. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains $$$k$$$ space-separated distinct lowercase Latin letters $$$c_1, c_2, \ldots, c_k$$$ — the letters still available on the keyboard.

Print a single number — the number of substrings of $$$s$$$ that can be typed using only available letters $$$c_1, c_2, \ldots, c_k$$$.

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
void main()
{
  int n, k; get(n, k);
  string str; get(str);
  bool[26] ap = false;
  foreach(i; 0 .. k)
    {
      string r; get(r);
      ap[r[0] - 'a'] = true;
    }
  int i = 0;
  long res = 0;
  for(; i < str.length;)
    {
      long count = 0;
      while(i < str.length && ap[str[i] - 'a'])
	{
	  count++;
	  i++;
	}
      res += count * (count + 1) / 2;
      if(!count)
	i++;
    }
  ans(res);
}

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;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto S = readln.chomp;
    auto A = readln.split.map!(a => a.front.to!dchar).array;

    auto B = new bool[](26);
    foreach (a; A) B[a-'a'] = true;

    long tmp = 0;
    long ans = 0;

    foreach (i; 0..N) {
        if (!B[S[i]-'a']) {
            ans += tmp * (tmp + 1) / 2;
            tmp = 0;
        } else {
            tmp += 1;
        }
    }

    ans += tmp * (tmp + 1) / 2;
    ans.writeln;
}

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(){
	int n = rint, k = rint;
	string s = rstring;
	char[] cs = readln.chomp.split.join.to!(char[]);

	bool[char] cset;
	foreach(c; cs) cset[c] = 1;

	long ans;
	long t;
	foreach(c; s){
		if(c !in cset){
			ans += t * (t + 1) / 2;
			t = 0;
		}
		else{
			t += 1;
		}
	}
	ans += t * (t + 1) / 2;

	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 n = RD!int;
	auto k = RD!int;
	auto s = RD!string;
	bool[char] set;
	foreach (i; 0..k)
	{
		auto c = RD!string;
		set[c[0]] = true;
	}

	long ans;
	long cnt;
	foreach (c; s)
	{
		if (set.get(c, false))
			++cnt;
		else
		{
			ans += cnt * (cnt+1) / 2;
			cnt = 0;
		}
	}
	ans += cnt * (cnt+1) / 2;
	cnt = 0;

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

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
void main()
{
  int n, k; get(n, k);
  string str; get(str);
  bool[26] ap = false;
  foreach(i; 0 .. k)
    {
      string r; get(r);
      ap[r[0] - 'a'] = true;
    }

  int i = 0;
  long res = 0;
  for(; i < str.length; i++)
    {
      int count = 0;
      while(i < str.length && ap[str[i] - 'a'])
	{
	  count++;
	  i++;
	}
      res += count * (count + 1) / 2;
    }
  ans(res);
}

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
void main()
{
  int n, k; get(n, k);
  string str; get(str);
  bool[26] ap = false;
  foreach(i; 0 .. k)
    {
      string r; get(r);
      ap[r[0] - 'a'] = true;
    }
  int i = 0;
  long res = 0;
  for(; i < str.length;)
    {
      int count = 0;
      while(i < str.length && ap[str[i] - 'a'])
	{
	  count++;
	  i++;
	}
      res += count * (count + 1) / 2;
      if(!count)
	i++;
    }
  ans(res);
}


Oleg came to see the maze of mirrors. The maze is a $$$n$$$ by $$$n$$$ room in which each cell is either empty or contains a mirror connecting opposite corners of this cell. Mirrors in this maze reflect light in a perfect way, which causes the interesting visual effects and contributes to the loss of orientation in the maze.Oleg is a person of curious nature, so he decided to install $$$n$$$ lasers facing internal of the maze on the south wall of the maze. On the north wall of the maze, Oleg installed $$$n$$$ receivers, also facing internal of the maze. Let's number lasers and receivers from west to east with distinct integers from $$$1$$$ to $$$n$$$. Each laser sends a beam of some specific kind and receiver with number $$$a_i$$$ should receive the beam sent from laser number $$$i$$$. Since two lasers' beams can't come to the same receiver, these numbers form a permutation — each of the receiver numbers occurs exactly once.You came to the maze together with Oleg. Help him to place the mirrors in the initially empty maze so that the maximum number of lasers' beams will come to the receivers they should. There are no mirrors outside the maze, so if the laser beam leaves the maze, it will not be able to go back.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the size of the maze. The second line contains a permutation of $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ defines the number of the receiver, to which the beam from $$$i$$$-th laser should come.

In the first line print the maximum possible number of laser beams, which can come to the receivers they should. In the next $$$n$$$ lines of length $$$n$$$ print the arrangement of mirrors, causing such number of laser beams to come where they should. If the corresponding cell is empty, print ".", otherwise print "/" or "\", depending on the orientation of the mirror. In your output north should be above, south should be below, and west and east should be on left and on the right respectively. It is allowed for laser beams to come not to the receivers they correspond to, but they are not counted in the answer. If there are multiple arrangements of mirrors leading to the optimal answer — print any of them.

NoteThe picture illustrates the arrangements of the mirrors in the first example.

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

void main ()
{
	auto n = readln.strip.to !(int);
	auto p = readln.splitter.map !(to !(int)).array;
	p[] -= 1;
	auto board = new char [] [] (n, n);
	foreach (ref line; board)
		line[] = '.';

	auto b = new bool [n];
	int k = 1, res = 0, prev = -1;
	foreach (i; 0..n)
	{
		res += (i == p[i]);
		if (i != p[i] && !b[i])
		{
			int m = k, j = i;
			b[i] = true;
			do
			{
				res += 1;
				auto dir = "\\/"[j < p[j]];
				board[k][j] = dir;
				board[k][p[j]] = dir;
				k += 1;
				j = p[j];
				b[j] = true;
			}
			while (p[j] != i);

			if (prev != -1)
			{
				res += 1;
				board[k][j] = '\\';
				board[k][prev] = '\\';
				board[0][prev] = '/';
				board[0][i] = '/';
				k += 1;
			}
			prev = i;

			bringToFront (board[1..m], board[m..k]);
		}
	}

	writeln (res);
	writefln ("%-(%s\n%)", board);
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto board = new char [] [] (n, n);
		foreach (ref line; board)
		{
			line[] = '.';
		}

		auto b = new bool [n];
		int k = 1;
		int res = 0;
		int prev = -1;
		foreach (i; 0..n)
		{
			if (i == p[i])
			{
				res += 1;
			}
			if (i != p[i] && !b[i])
			{
				int m = k;
				b[i] = true;
				int j = i;
				int last = -1;
				do
				{
					res += 1;
					debug {writeln ("?", k, " ", j);}
					if (j < p[j])
					{
						board[k][j] = '/';
						board[k][p[j]] = '/';
					}
					else
					{
						board[k][j] = '\\';
						board[k][p[j]] = '\\';
					}
					k += 1;
					last = j;
					j = p[j];
					b[j] = true;
				}
				while (p[j] != i);

				if (prev != -1)
				{
					res += 1;
					board[k][j] = '\\';
					board[k][prev] = '\\';
					board[0][prev] = '/';
					board[0][i] = '/';
					k += 1;
				}
				prev = i;

				debug {writeln (m, " ", k, "!");}
				bringToFront (board[1..m], board[m..k]);
			}
		}

		writeln (res);
		writefln ("%-(%s\n%)", board);
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto board = new char [] [] (n, n);
		foreach (ref line; board)
		{
			line[] = '.';
		}

		auto b = new bool [n];
		int k = 0;
		int res = 0;
		foreach (i; 0..n)
		{
			if (i == p[i])
			{
				res += 1;
			}
			if (i != p[i] && !b[i])
			{
				b[i] = true;
				int j = p[i];
				do
				{
					b[j] = true;
					res += 1;
					if (j < p[j])
					{
						board[k][j] = '/';
						board[k][p[j]] = '/';
					}
					else
					{
						board[k][j] = '\\';
						board[k][p[j]] = '\\';
					}
					k += 1;
					j = p[j];
				}
				while (j != i);
			}
		}

		writeln (res);
		writefln ("%-(%s\n%)", board);
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;
		auto board = new char [] [] (n, n);
		foreach (ref line; board)
		{
			line[] = '.';
		}

		auto b = new bool [n];
		int k = 0;
		foreach (i; 0..n)
		{
			if (i != p[i] && !b[i])
			{
				b[i] = true;
				int j = p[i];
				do
				{
					b[j] = true;
					if (j < p[j])
					{
						board[k][j] = '/';
						board[k][p[j]] = '/';
					}
					else
					{
						board[k][j] = '\\';
						board[k][p[j]] = '\\';
					}
					k += 1;
					j = p[j];
				}
				while (j != i);
			}
		}
		writefln ("%-(%s\n%)", board);
	}
}