In the 2050 Conference, some people from the competitive programming community meet together and are going to take a photo. The $$$n$$$ people form a line. They are numbered from $$$1$$$ to $$$n$$$ from left to right. Each of them either holds a cardboard with the letter 'C' or a cardboard with the letter 'P'.Let $$$C=\{c_1,c_2,\dots,c_m\}$$$ $$$(c_1<c_2<\ldots <c_m)$$$ be the set of people who hold cardboards of 'C'. Let $$$P=\{p_1,p_2,\dots,p_k\}$$$ $$$(p_1<p_2<\ldots <p_k)$$$ be the set of people who hold cardboards of 'P'. The photo is good if and only if it satisfies the following constraints:   $$$C\cup P=\{1,2,\dots,n\}$$$  $$$C\cap P =\emptyset $$$.  $$$c_i-c_{i-1}\leq c_{i+1}-c_i(1< i <m)$$$.  $$$p_i-p_{i-1}\geq p_{i+1}-p_i(1< i <k)$$$. Given an array $$$a_1,\ldots, a_n$$$, please find the number of good photos satisfying the following condition: $$$$$$\sum\limits_{x\in C} a_x < \sum\limits_{y\in P} a_y.$$$$$$The answer can be large, so output it modulo $$$998\,244\,353$$$. Two photos are different if and only if there exists at least one person who holds a cardboard of 'C' in one photo but holds a cardboard of 'P' in the other.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 200\,000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq 200\,000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$200\,000$$$.

For each test case, output the answer modulo $$$998\,244\,353$$$ in a separate line.

NoteFor the first test case, there are $$$10$$$ possible good photos satisfying the condition: PPPPP, CPPPP, PCPPP, CCPPP, PCCPP, PCPCP, PPPPC, CPPPC, PCPPC, PPPCC.For the second test case, there are $$$7$$$ possible good photos satisfying the condition: PPPP, PCPP, PCCP, PPPC, PCPC, PPCC, PCCC.

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_) {
  import std.conv : to;
  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 == "^^") {
      if (a < 0) return (this = inv()^^(-a));
      ModInt t2 = this, te = ModInt(1);
      for (long e = a; e > 0; 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 { 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");
  }
  bool opCast(T: bool)() const { return (x != 0); }
  string toString() const { return x.to!string; }
}

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

void bAdd(T)(T[] bit, int pos, T val)
in {
  assert(0 <= pos && pos < bit.length, "bAdd: 0 <= pos < |bit| must hold");
}
do {
  for (int x = pos; x < bit.length; x |= x + 1) {
    bit[x] += val;
  }
}

// sum of [0, pos)
T bSum(T)(T[] bit, int pos)
in {
  assert(0 <= pos && pos <= bit.length, "bSum: 0 <= pos <= |bit| must hold");
}
do {
  T ret = 0;
  for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) {
    ret += bit[x];
  }
  return ret;
}

void main() {
  debug {
    foreach (n; 1 .. 10 + 1) {
      int cnt;
      auto brt = new int[1 << n];
      foreach (p; 0 .. 1 << n) {
        int[][2] seqs;
        foreach (i; 0 .. n) {
          seqs[(p >> i) & 1] ~= i;
        }
        bool ok = true;
        foreach (j; 1 .. cast(int)(seqs[0].length) - 1) {
          ok = ok && (seqs[0][j] - seqs[0][j - 1] <= seqs[0][j + 1] - seqs[0][j]);
        }
        foreach (j; 1 .. cast(int)(seqs[1].length) - 1) {
          ok = ok && (seqs[1][j] - seqs[1][j - 1] >= seqs[1][j + 1] - seqs[1][j]);
        }
        if (ok) {
          int[2] mns = [n, n], mxs = [-1, -1];
          foreach (i; 0 .. n) {
            chmin(mns[(p >> i) & 1], i);
            chmax(mxs[(p >> i) & 1], i);
          }
          foreach (i; 0 .. n) {
            write((p >> i) & 1);
          }
          writeln(" ", seqs, " ", mns, " ", mxs);
          ++cnt;
          ++brt[p];
        }
      }
      writefln("n = %s: %s", n, cnt);
      stdout.flush;

      // s 0...0 01...01 1...1 t
      if (n >= 2) {
        auto grd = new int[1 << n];
        foreach (i; 0 .. n + 1) {
          ++grd[(1 << i) - 1];
        }
        foreach (i; 0 .. n + 1) for (int j = i + 2; j <= n; j += 2) {
          foreach (s; 0 .. 2) foreach (t; 0 .. 2) {
            if (i == 0 && s == 1) continue;
            if (j == n && t == 0) continue;
            int p;
            for (int k = i + 1; k < j; k += 2) p |= 1 << k;
            foreach (k; j .. n) p |= 1 << k;
            p &= ~(1 << 0);
            p &= ~(1 << (n - 1));
            p |= s << 0;
            p |= t << (n - 1);
            ++grd[p];
          }
        }
        writeln(brt);
        writeln(grd);
        stdout.flush;
        assert(brt == grd);
      }
    }
  }

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

        auto ASum = new long[N + 1];
        foreach (i; 0 .. N) {
          ASum[i + 1] = ASum[i] + A[i];
        }
        auto B0Sum = new long[N + 1];
        auto B1Sum = new long[N + 1];
        foreach (i; 0 .. N) {
          B0Sum[i + 1] = B1Sum[i];
          B1Sum[i + 1] = B0Sum[i] + A[i];
        }

        Mint ans;

        if (N == 1) {
          ans += 1;
        } else {
          // no 01
          foreach (i; 0 .. N + 1) {
            if (ASum[N] - ASum[i] < ASum[i]) {
              ans += 1;
            }
          }
          // [0, N)
          if (N % 2 == 0) {
            if (B0Sum[N] < B1Sum[N]) {
              ans += 1;
            }
          }
          // [0, *)
          for (int j = 2; j < N; j += 2) {
            if (B0Sum[j] + A[N - 1] < B1Sum[j] + (ASum[N - 1] - ASum[j])) {
              ans += 1;
            }
            if (B0Sum[j] < B1Sum[j] + (ASum[N - 1] - ASum[j]) + A[N - 1]) {
              ans += 1;
            }
          }
          // [*, N)
          for (int i = N - 2; i > 0; i -= 2) {
            if (A[0] + (ASum[i] - ASum[1]) + (B0Sum[N] - B0Sum[i]) < (B1Sum[N] - B1Sum[i])) {
              ans += 1;
            }
            if ((ASum[i] - ASum[1]) + (B0Sum[N] - B0Sum[i]) < A[0] + (B1Sum[N] - B1Sum[i])) {
              ans += 1;
            }
          }
          // [*, *)
          foreach (i0; [1, 2]) {
            foreach (s; 0 .. 2) foreach (t; 0 .. 2) {
              /*
                d - A[1, i) - B0[i, j) + B1[i, j) + A[j, N - 1)
                = d - ASum[i] + ASum[1] - B0Sum[j] + B0Sum[i] + B1Sum[j] - B1Sum[i] + ASum[N - 1] - ASum[j]
                = (d + ASum[1] + ASum[N - 1]) + (- ASum[i] + B0Sum[i] - B1Sum[i]) + (- B0Sum[j] + B1Sum[j] - ASum[j])

                d + f + g > 0
                g > -(d + f)
              */
              long d;
              (s == 0) ? (d -= A[0]) : (d += A[0]);
              (t == 0) ? (d -= A[N - 1]) : (d += A[N - 1]);
              d += ASum[1];
              d += ASum[N - 1];
              auto fs = new long[N + 1];
              auto gs = new long[N + 1];
              for (int i = i0; i < N; i += 2) {
                fs[i] -= ASum[i];
                fs[i] += B0Sum[i];
                fs[i] -= B1Sum[i];
                fs[i] = -(d + fs[i]);
              }
              for (int j = i0; j < N; j += 2) {
                gs[j] -= B0Sum[j];
                gs[j] += B1Sum[j];
                gs[j] -= ASum[j];
              }
              debug {
                writeln(i0, " ", s, " ", t, " ", fs, " ", gs);
              }
              long[] xs = fs ~ gs;
              xs = xs.sort.uniq.array;
              const xsLen = cast(int)(xs.length);
              auto bit = new int[xsLen];
              for (int i = i0; i < N; i += 2) {
                ans += bit.bSum(xs.lowerBound(gs[i]));
                bit.bAdd(xs.lowerBound(fs[i]), 1);
              }
            }
          }
        }

        debug {
          const n = N;
          auto grd = new int[1 << n];
          if (n <= 2) {
            grd[] = 1;
          } else {
            foreach (i; 0 .. n + 1) {
              ++grd[(1 << i) - 1];
            }
            foreach (i; 0 .. n + 1) for (int j = i + 2; j <= n; j += 2) {
              foreach (s; 0 .. 2) foreach (t; 0 .. 2) {
                if (i == 0 && s == 1) continue;
                if (j == n && t == 0) continue;
                int p;
                for (int k = i + 1; k < j; k += 2) p |= 1 << k;
                foreach (k; j .. n) p |= 1 << k;
                p &= ~(1 << 0);
                p &= ~(1 << (n - 1));
                p |= s << 0;
                p |= t << (n - 1);
                ++grd[p];
              }
            }
          }
          auto sums = new long[1 << n];
          foreach (i; 0 .. n) {
            foreach (p; 0 .. 1 << i) {
              sums[p | 1 << i] = sums[p] + A[i];
            }
          }
          int brt;
          foreach (p; 0 .. 1 << n) {
            if (grd[p]) {
              if (sums[$ - 1] - sums[p] < sums[p]) {
                debug {
                  write("ok ");
                  foreach (i; 0 .. n) {
                    write((p >> i) & 1);
                  }
                  writeln;
                }
                ++brt;
              }
            }
          }
          writeln("brt = ", brt);
          assert(brt == ans.x);
        }

        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


Friday is Polycarpus' favourite day of the week. Not because it is followed by the weekend, but because the lessons on Friday are 2 IT lessons, 2 math lessons and 2 literature lessons. Of course, Polycarpus has prepared to all of them, unlike his buddy Innocentius. Innocentius spent all evening playing his favourite game Fur2 and didn't have enough time to do the literature task. As Innocentius didn't want to get an F, he decided to do the task and read the book called "Storm and Calm" during the IT and Math lessons (he never used to have problems with these subjects). When the IT teacher Mr. Watkins saw this, he decided to give Innocentius another task so that the boy concentrated more on the lesson and less — on the staff that has nothing to do with IT. Mr. Watkins said that a palindrome is a string that can be read the same way in either direction, from the left to the right and from the right to the left. A concatenation of strings a, b is a string ab that results from consecutive adding of string b to string a. Of course, Innocentius knew it all but the task was much harder than he could have imagined. Mr. Watkins asked change in the "Storm and Calm" the minimum number of characters so that the text of the book would also be a concatenation of no more than k palindromes. Innocentius can't complete the task and therefore asks you to help him.

The first input line contains a non-empty string s which is the text of "Storm and Calm" (without spaces). The length of the string s does not exceed 500 characters. String s consists of uppercase and lowercase Latin letters. The second line contains a single number k (1 ≤ k ≤ |s|, where |s| represents the length of the string s).

Print on the first line the minimum number of changes that Innocentius will have to make. Print on the second line the string consisting of no more than k palindromes. Each palindrome should be non-empty and consist of uppercase and lowercase Latin letters. Use the character "+" (ASCII-code 43) to separate consecutive palindromes. If there exist several solutions, print any of them. The letters' case does matter, that is an uppercase letter is not considered equivalent to the corresponding lowercase letter.

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

string s; int K;

struct R {
    int from, to;
    int diff;
}

string modify(in string s) {
    int N = cast(int)(s.length);
    auto t = s[0 .. N / 2].dup;
    t.reverse;
    if (N & 1) {
        return s[0 .. N / 2] ~ s[N / 2] ~ t.idup;
    } else {
        return s[0 .. N / 2] ~ t.idup;
    }
}

void main() {
    s = readln.chomp;
    scanf("%d\n", &K);
    int N = cast(int)s.length;

    R[] rs;
    foreach (int i; 0 .. N) {
        foreach (int j; i + 1 .. N + 1) {
            int count(in string s) {
                int n = cast(int)s.length;
                int ret = 0;
                foreach (int i, c; s) {
                    if (c != s[n - 1 - i]) ret++;
                }
                return ret / 2;
            }
            rs ~= R(i, j, count(s[i .. j]));
        }
    }

    rs.sort!"a.from < b.from";
    const INF = 1<<28;
    auto dp = new int[][](K + 1, N + 1);
    auto prev = new int[][](K + 1, N + 1);
    foreach (k; 0 .. K + 1) dp[k][] = INF;
    for (int i = 0; i < N && rs[i].from == 0; i++) {
        dp[1][rs[i].to] = rs[i].diff;
        prev[1][rs[i].to] = rs[i].from;
    }
    foreach (k; 1 .. K) {
        foreach (n; 0 .. N) dp[k + 1][n] = min(dp[k + 1][n], dp[k][n]);
        foreach (r; rs) {
            if (dp[k + 1][r.to] > dp[k][r.from] + r.diff) {
                dp[k + 1][r.to] = dp[k][r.from] + r.diff;
                prev[k + 1][r.to] = r.from;
            }
        }
    }
    int ansCount = INF;
    int ansK = 0;
    foreach (int k; 0 .. K + 1) {
        if (ansCount > dp[k][N]) {
            ansCount = dp[k][N];
            ansK = k;
        }
    }
    writeln(ansCount);
    int n = N;
    int p = prev[ansK][N];
    string[] ans;
    int k = ansK;
    while (k > 0) {
        ans ~= s[p .. n];
        n = p;
        p = prev[--k][n];
    }
    ans.reverse;
    writeln(ans.map!(modify).join("+"));
    //foreach (l; dp[1 .. $]) l.writeln;
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

string s; int K;

struct R {
    int from, to;
    int diff;
}

string modify(in string s) {
    int N = cast(int)(s.length);
    auto t = s[0 .. N / 2].dup;
    t.reverse;
    if (N & 1) {
        return s[0 .. N / 2] ~ s[N / 2] ~ t.idup;
    } else {
        return s[0 .. N / 2] ~ t.idup;
    }
}

void main() {
    s = readln.chomp;
    scanf("%d\n", &K);
    int N = cast(int)s.length;

    R[] rs;
    foreach (int i; 0 .. N) {
        foreach (int j; i + 1 .. N + 1) {
            int count(in string s) {
                int n = cast(int)s.length;
                int ret = 0;
                foreach (int i, c; s) {
                    if (c != s[n - 1 - i]) ret++;
                }
                return ret / 2;
            }
            rs ~= R(i, j, count(s[i .. j]));
        }
    }

    rs.sort!"a.from < b.from";
    const INF = 1<<28;
    auto dp = new int[][](K + 1, N + 1);
    auto prev = new int[][](K + 1, N + 1);
    foreach (k; 0 .. K + 1) dp[k][] = INF;
    for (int i = 0; rs[i].from == 0; i++) {
        dp[1][rs[i].to] = rs[i].diff;
        prev[1][rs[i].to] = rs[i].from;
    }
    foreach (r; rs) {
        foreach (k; 1 .. K) {
            if (dp[k + 1][r.to] > dp[k][r.from] + r.diff) {
                dp[k + 1][r.to] = dp[k][r.from] + r.diff;
                prev[k + 1][r.to] = r.from;
            }
        }
    }
    int ansCount = INF;
    int ansK = 0;
    foreach (int k; 0 .. K + 1) {
        if (ansCount > dp[k][N]) {
            ansCount = dp[k][N];
            ansK = k;
        }
    }
    writeln(ansCount);
    int n = N;
    int p = prev[ansK][N];
    string[] ans;
    int k = ansK;
    while (k > 0) {
        ans ~= s[p .. n];
        n = p;
        p = prev[--k][n];
    }
    writeln(ans.map!(modify).join("+"));
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

string s; int K;

struct R {
    int from, to;
    int diff;
}

string modify(in string s) {
    int N = cast(int)(s.length);
    auto t = s[0 .. N / 2].dup;
    t.reverse;
    if (N & 1) {
        return s[0 .. N / 2] ~ s[N / 2] ~ t.idup;
    } else {
        return s[0 .. N / 2] ~ t.idup;
    }
}

void main() {
    s = readln.chomp;
    scanf("%d\n", &K);
    int N = cast(int)s.length;

    R[] rs;
    foreach (int i; 0 .. N) {
        foreach (int j; i + 1 .. N + 1) {
            int count(in string s) {
                int n = cast(int)s.length;
                int ret = 0;
                foreach (int i, c; s) {
                    if (c != s[n - 1 - i]) ret++;
                }
                return ret / 2;
            }
            rs ~= R(i, j, count(s[i .. j]));
        }
    }

    rs.sort!"a.from < b.from";
    const INF = 1<<28;
    auto dp = new int[][](K + 1, N + 1);
    auto prev = new int[][](K + 1, N + 1);
    foreach (k; 0 .. K + 1) dp[k][] = INF;
    for (int i = 0; i < N && rs[i].from == 0; i++) {
        dp[1][rs[i].to] = rs[i].diff;
        prev[1][rs[i].to] = rs[i].from;
    }
    foreach (k; 1 .. K) {
        foreach (n; 0 .. N) dp[k + 1][n] = min(dp[k + 1][n], dp[k][n]);
        foreach (r; rs) {
            if (dp[k + 1][r.to] > dp[k][r.from] + r.diff) {
                dp[k + 1][r.to] = dp[k][r.from] + r.diff;
                prev[k + 1][r.to] = r.from;
            }
        }
    }
    int ansCount = INF;
    int ansK = 0;
    foreach (int k; 0 .. K + 1) {
        if (ansCount > dp[k][N]) {
            ansCount = dp[k][N];
            ansK = k;
        }
    }
    writeln(ansCount);
    int n = N;
    int p = prev[ansK][N];
    string[] ans;
    int k = ansK;
    while (k > 0) {
        ans ~= s[p .. n];
        n = p;
        p = prev[--k][n];
    }
    writeln(ans.map!(modify).join("+"));
    //foreach (l; dp[1 .. $]) l.writeln;
}


You have a blackboard and initially only an odd number $$$x$$$ is written on it. Your goal is to write the number $$$1$$$ on the blackboard.You may write new numbers on the blackboard with the following two operations.   You may take two numbers (not necessarily distinct) already on the blackboard and write their sum on the blackboard. The two numbers you have chosen remain on the blackboard.  You may take two numbers (not necessarily distinct) already on the blackboard and write their bitwise XOR on the blackboard. The two numbers you have chosen remain on the blackboard.  Perform a sequence of operations such that at the end the number $$$1$$$ is on the blackboard.

The single line of the input contains the odd integer $$$x$$$ ($$$3 \le x \le 999,999$$$).

Print on the first line the number $$$q$$$ of operations you perform. Then $$$q$$$ lines should follow, each describing one operation.    The "sum" operation is described by the line "$$$a$$$ + $$$b$$$", where $$$a, b$$$ must be integers already present on the blackboard.  The "xor" operation is described by the line "$$$a$$$ ^ $$$b$$$", where $$$a, b$$$ must be integers already present on the blackboard.  The operation symbol (+ or ^) must be separated from $$$a, b$$$ by a whitespace. You can perform at most $$$100,000$$$ operations (that is, $$$q\le 100,000$$$) and all numbers written on the blackboard must be in the range $$$[0, 5\cdot10^{18}]$$$. It can be proven that under such restrictions the required sequence of operations exists. You can output any suitable sequence of operations.

import core.bitop;
import std.algorithm;
import std.conv;
import std.format;
import std.math;
import std.random;
import std.range;
import std.stdio;
import std.string;

auto gcdExt (long a, long b, ref long x, ref long y)
out (res)
{
	assert (a * x + b * y == res);
}
body
{
	if (a == 0)
	{
		x = 0;
		y = 1;
		return b;
	}
	auto res = gcdExt (b % a, a, y, x);
	x -= (b / a) * y;
	return res;
}

void main ()
{
	long n;
	while (readf !(" %s") (n) > 0)
	{
		string [] answer;
		answer ~= format !("%s ^ %s") (n, n); // zero

		void getMult (long v, long m)
		{
			if (m > 1)
			{
				answer ~= format !("%s + %s") (v, v);
				getMult (v * 2, m / 2);
				if (m & 1)
				{
					answer ~= format !("%s + %s")
					    ((v * 2) * (m / 2), v);
				}
			}
		}

		while (true)
		{
			auto a = uniform (1L, 11L);
//			auto b = uniform (1L, 1100L);
			auto b = n;
			auto na = n * a;
			auto nb = n * b;
			auto nc = na ^ nb;
			long x, y;
			if (gcdExt (na, nc, x, y) != 1L)
			{
				continue;
			}
			x = abs (x);
			y = abs (y);
			if ((na * x) / x != na || (nc * y) / y != nc)
			{
				continue;
			}
			if (((na * x) ^ (nc * y)) != 1L)
			{
				continue;
			}
			getMult (n, a);
			getMult (n, b);
			answer ~= format !("%s ^ %s") (na, nb);
			getMult (na, x);
			getMult (nc, y);
			answer ~= format !("%s ^ %s") (na * x, nc * y);
			break;
		}

		writeln (answer.length);
		foreach (ref line; answer)
		{
			writeln (line);
		}
	}
}

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

enum LIM = 4 * 10L^^18;

alias Line = Tuple!(char, "op", long, "a", long, "b");

void main() {
  debug {
    for (long n = 1; n < 10^^6; n += 2) {
      assert(gcd(n, n ^ (n << bsr(n))) == 1);
    }
  }

  try {
    for (; ; ) {
      const N = readLong();
      if (N == 1) {
        writeln(0);
        continue;
      }

      const K = bsr(N);
      const B = N ^ (N << K);

      Line[] ans;
      for (int i = 1; ; ++i) {
        if (N << i > LIM) {
          break;
        }
        ans ~= Line('+', N << (i - 1), N << (i - 1));
      }
      ans ~= Line('^', N, N << K);
      for (int i = 1; ; ++i) {
        if (B << i > LIM) {
          break;
        }
        ans ~= Line('+', B << (i - 1), B << (i - 1));
      }

      int L;
      for (L = 1; 1L << L < N * B; ++L) {}
      foreach (t; [1L << L, 1L << L | 1]) {
        foreach (y; 0 .. N) {
          if ((t - B * y) % N == 0) {
            const x = (t - B * y) / N;
            long sum;
            foreach (e; 0 .. bsr(x) + 1) {
              if ((x >> e) & 1) {
                if (sum > 0) {
                  ans ~= Line('+', sum, N << e);
                }
                sum += N << e;
              }
            }
            foreach (e; 0 .. bsr(y) + 1) {
              if ((y >> e) & 1) {
                if (sum > 0) {
                  ans ~= Line('+', sum, B << e);
                }
                sum += B << e;
              }
            }
            assert(sum == t);
            break;
          }
        }
      }
      ans ~= Line('^', 1L << L, 1L << L | 1);

      writeln(ans.length);
      foreach (ref line; ans) {
        writefln("%s %s %s", line.a, line.op, line.b);
      }
    }
  } catch (EOFException e) {
  }
}

import core.bitop;
import std.algorithm;
import std.conv;
import std.format;
import std.math;
import std.random;
import std.range;
import std.stdio;
import std.string;

auto gcdExt (long a, long b, ref long x, ref long y)
out (res)
{
	assert (a * x + b * y == res);
}
body
{
	if (a == 0)
	{
		x = 0;
		y = 1;
		return b;
	}
	auto res = gcdExt (b % a, a, y, x);
	x -= (b / a) * y;
	return res;
}

void main ()
{
	long n;
	while (readf !(" %s") (n) > 0)
	{
		string [] answer;
		answer ~= format !("%s ^ %s") (n, n); // zero

		void getMult (long v, long m)
		{
			if (m > 1)
			{
				answer ~= format !("%s + %s") (v, v);
				getMult (v * 2, m / 2);
				if (m & 1)
				{
					answer ~= format !("%s + %s")
					    ((v * 2) * (m / 2), v);
				}
			}
		}

		while (true)
		{
			auto a = uniform (1L, 1100L);
//			auto b = uniform (1L, 1100L);
			auto b = n;
			auto na = n * a;
			auto nb = n * b;
			auto nc = na ^ nb;
			long x, y;
			if (gcdExt (na, nc, x, y) != 1L)
			{
				continue;
			}
			x = abs (x);
			y = abs (y);
			if ((na * x) / x != na || (nc * y) / y != nc)
			{
				continue;
			}
			if (((na * x) ^ (nc * y)) != 1L)
			{
				continue;
			}
			getMult (n, a);
			getMult (n, b);
			answer ~= format !("%s ^ %s") (na, nb);
			getMult (na, x);
			getMult (nc, y);
			answer ~= format !("%s ^ %s") (na * x, nc * y);
			break;
		}

		writeln (answer.length);
		foreach (ref line; answer)
		{
			writeln (line);
		}
	}
}


You are given a positive integer $$$n$$$, it is guaranteed that $$$n$$$ is even (i.e. divisible by $$$2$$$).You want to construct the array $$$a$$$ of length $$$n$$$ such that:   The first $$$\frac{n}{2}$$$ elements of $$$a$$$ are even (divisible by $$$2$$$);  the second $$$\frac{n}{2}$$$ elements of $$$a$$$ are odd (not divisible by $$$2$$$);  all elements of $$$a$$$ are distinct and positive;  the sum of the first half equals to the sum of the second half ($$$\sum\limits_{i=1}^{\frac{n}{2}} a_i = \sum\limits_{i=\frac{n}{2} + 1}^{n} a_i$$$). If there are multiple answers, you can print any. It is not guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of the array. It is guaranteed that that $$$n$$$ is even (i.e. divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — "NO" (without quotes), if there is no suitable answer for the given test case or "YES" in the first line and any suitable array $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) satisfying conditions from the problem statement on the second line.

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!int;
        if ((N/2)%2 == 1) {
            writeln("NO");
            continue;
        }
        int[] as, bs;
        int x;
        foreach (_i; 0..N/2) {
            ++x;
            if (x%2 == 1) {
                bs ~= x++;
                as ~= x++;
            } else {
                as ~= x++;
                bs ~= x++;
            }
        }
        writeln("YES");
        writeln((as ~= bs).to!(string[]).join(" "));
    }
}

import std.stdio;

void main ()
{
	readln;
	int n;
	while (readf !(" %s") (n) > 0)
	{
		if (n % 4 == 0)
		{
			writeln ("YES");
			int [] a;
			int [] b;
			int cur = 0;
			for (int i = 0; i < n / 2; i += 2)
			{
				a ~= cur + 1;
				a ~= cur + 5;
				b ~= cur + 2;
				b ~= cur + 4;
				cur += 6;
			}
			writefln !("%(%s %)") (b ~ a);
		}
		else
		{
			writeln ("NO");
		}
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		foreach (i; 0..n/2)
		{
			ans[ti] ~= (i+1)*2;
		}
		foreach (i; 0..n/2)
		{
			if (i < n/4)
				ans[ti] ~= ans[ti][i]-1;
			else
				ans[ti] ~= ans[ti][i]+1;
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln("NO");
		else
		{
			writeln("YES");
			e.map!(to!string).join(" ").writeln;
		}
	}
	stdout.flush;
	debug readln;
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!int;
        if ((N/2)%2 == 1) {
            writeln("NO");
            continue;
        }
        int[] as, bs;
        int x;
        foreach (_i; 0..N/2) {
            ++x;
            if (x%2 == 1) {
                bs ~= x++;
                as ~= x++;
            } else {
                as ~= x++;
                bs ~= x++;
            }
        }
        writeln((as ~= bs).to!(string[]).join(" "));
    }
}


Polycarp has $$$n$$$ friends, the $$$i$$$-th of his friends has $$$a_i$$$ candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all $$$a_i$$$ to be the same. To solve this, Polycarp performs the following set of actions exactly once:   Polycarp chooses $$$k$$$ ($$$0 \le k \le n$$$) arbitrary friends (let's say he chooses friends with indices $$$i_1, i_2, \ldots, i_k$$$);  Polycarp distributes their $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies among all $$$n$$$ friends. During distribution for each of $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies he chooses new owner. That can be any of $$$n$$$ friends. Note, that any candy can be given to the person, who has owned that candy before the distribution process. Note that the number $$$k$$$ is not fixed in advance and can be arbitrary. Your task is to find the minimum value of $$$k$$$.For example, if $$$n=4$$$ and $$$a=[4, 5, 2, 5]$$$, then Polycarp could make the following distribution of the candies:   Polycarp chooses $$$k=2$$$ friends with indices $$$i=[2, 4]$$$ and distributes $$$a_2 + a_4 = 10$$$ candies to make $$$a=[4, 4, 4, 4]$$$ (two candies go to person $$$3$$$). Note that in this example Polycarp cannot choose $$$k=1$$$ friend so that he can redistribute candies so that in the end all $$$a_i$$$ are equal.For the data $$$n$$$ and $$$a$$$, determine the minimum value $$$k$$$. With this value $$$k$$$, Polycarp should be able to select $$$k$$$ friends and redistribute their candies so that everyone will end up with the same number of candies.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^4$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output:    the minimum value of $$$k$$$, such that Polycarp can choose exactly $$$k$$$ friends so that he can redistribute the candies in the desired way;  "-1" if no such value $$$k$$$ exists.

// Vicfred
// https://codeforces.com/contest/1538/problem/B
// basic math, greedy
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

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

    long total = a.sum();

    if(total % n != 0) {
        "-1".writeln;
        continue;
    }

    long candies = total / n;
    long ans = 0L;
    for(int i = 0; i < n; ++i) {
        if(a[i] > candies)
            ans += 1;
    }
    ans.writeln;
}
}

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

void main() {
    foreach(t; 0 .. to!int(readln.strip)) {
        int n = to!int(readln.strip);
        auto ar = readln.strip.split.map!(to!int);
        int sm = sum(ar);
        writeln((sm % n != 0) ? -1 : to!int(ar.count!(a => a > sm/n)));
    }
}

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!long).array;
    long sum = a.sum;
    if (sum % n != 0) {
      writeln(-1);
    } else {
      long avg = sum / n;
      writeln(a.count!(x => x > avg));
    }
  }
}


Ivan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2v - 1 for some integer v (v ≥ 0). Help Ivan, find the required quantity of numbers.

The first line contains integer n (1 ≤ n ≤ 105). The second input line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 2·109). It is guaranteed that a1 ≤ a2 ≤ ... ≤ an.

Print a single integer — the answer to the problem.

NoteIn the first sample you do not need to add anything, the sum of numbers already equals 23 - 1 = 7.In the second sample you need to add numbers 20, 21, 22.

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

int main() {
	int n;
	auto u = new RedBlackTree!(long);
	readf("%d\n", &n);
	string[] input = readln().split();
	foreach (s; input) {
		long a = to!long(s);
		while (a in u) {
			u.removeKey(a);
			a++;
		}
		u.stableInsert(a);
	}
	writeln(u.back() + 1 - u.length());
    return 0;
}


Alice and Bob are playing a game on a line with $$$n$$$ cells. There are $$$n$$$ cells labeled from $$$1$$$ through $$$n$$$. For each $$$i$$$ from $$$1$$$ to $$$n-1$$$, cells $$$i$$$ and $$$i+1$$$ are adjacent.Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers $$$x_1, x_2, \ldots, x_k$$$ in order. In the $$$i$$$-th question, Bob asks Alice if her token is currently on cell $$$x_i$$$. That is, Alice can answer either "YES" or "NO" to each Bob's question.At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.You are given $$$n$$$ and Bob's questions $$$x_1, \ldots, x_k$$$. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions. Let $$$(a,b)$$$ denote a scenario where Alice starts at cell $$$a$$$ and ends at cell $$$b$$$. Two scenarios $$$(a_i, b_i)$$$ and $$$(a_j, b_j)$$$ are different if $$$a_i \neq a_j$$$ or $$$b_i \neq b_j$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n,k \leq 10^5$$$) — the number of cells and the number of questions Bob asked. The second line contains $$$k$$$ integers $$$x_1, x_2, \ldots, x_k$$$ ($$$1 \leq x_i \leq n$$$) — Bob's questions.

Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.

NoteThe notation $$$(i,j)$$$ denotes a scenario where Alice starts at cell $$$i$$$ and ends at cell $$$j$$$.In the first example, the valid scenarios are $$$(1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5)$$$. For example, $$$(3,4)$$$ is valid since Alice can start at cell $$$3$$$, stay there for the first three questions, then move to cell $$$4$$$ after the last question. $$$(4,5)$$$ is valid since Alice can start at cell $$$4$$$, stay there for the first question, the move to cell $$$5$$$ for the next two questions. Note that $$$(4,5)$$$ is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.In the second example, Alice has no valid scenarios.In the last example, all $$$(i,j)$$$ where $$$|i-j| \leq 1$$$ except for $$$(42, 42)$$$ are valid scenarios.

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

void main ()
{
	int n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto x = readln.splitter.map !(to !(int)).array;
		int [int] first;
		int [int] last;
		foreach (i, ref cur; x)
		{
			if (cur !in first)
			{
				first[cur] = i;
			}
			last[cur] = i;
		}

		bool canBe (int a, int b)
		{
			if (a !in first)
			{
				return true;
			}
			int step = first[a];
			if (b !in last)
			{
				return true;
			}
			return step > last[b];
		}

		int res = 0;
		foreach (a; 1..n + 1)
		{
			foreach (b; max (a - 1, 1)..min (a + 1, n) + 1)
			{
				if (canBe (a, b))
				{
					res += 1;
				}
			}
		}
		writeln (res);
	}
}

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

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

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

void main() {
  auto r = new InputReader;
  immutable n = r.next!int;
  immutable k = r.next!int;
  immutable a = r.nextA!int(k).idup;
  auto c = new int[n + 1];
  auto first = new int[n+1];
  first[] = int.max;
  auto last = new int[n+1];
  last[] = int.min;
  foreach_reverse (i, j; a) {
    first[j] = i.to!int;
    ++c[j];
  }
  foreach (i, j; a) {
    last[j] = i.to!int;
  }
  int res;
  foreach (i; 1 .. n + 1) {
    foreach (delta; -1 .. 2) {
      int j = i + delta;
      if (j >= 1 && j <= n) {
        if (first[i] > last[j]) ++res;
      }
    }
  }
  writeln (res);
}


Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.Their algorithm will be tested on an array of integers, where the $$$i$$$-th integer represents the color of the $$$i$$$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than $$$k$$$, and each color should belong to exactly one group.Finally, the students will replace the color of each pixel in the array with that color’s assigned group key.To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $$$k$$$ to the right.   To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.

The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq k \leq 256$$$), the number of pixels in the image, and the maximum size of a group, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$0 \leq p_i \leq 255$$$), where $$$p_i$$$ is the color of the $$$i$$$-th pixel.

Print $$$n$$$ space-separated integers; the lexicographically smallest possible array that represents the image after applying the Posterization filter.

NoteOne possible way to group colors and assign keys for the first sample:Color $$$2$$$ belongs to the group $$$[0,2]$$$, with group key $$$0$$$.Color $$$14$$$ belongs to the group $$$[12,14]$$$, with group key $$$12$$$.Colors $$$3$$$ and $$$4$$$ belong to group $$$[3, 5]$$$, with group key $$$3$$$.Other groups won't affect the result so they are not listed here.

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

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;
    int[int] B;
    auto ans = new int[](N);

    foreach (i; 0..N) {
        if (A[i] in B) {
            ans[i] = B[A[i]];
            continue;
        }

        int k = max(0, A[i] - K + 1);
        while (k in B && A[i] - B[k] >= K) ++k;

        if (k in B) {
            ans[i] = B[k];
            foreach (j; k..A[i]+1) B[j] = B[k];
        } else {
            ans[i] = k;
            foreach (j; k..A[i]+1) B[j] = k;
        }
    }

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

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;
import std.numeric;

void main()
{
	int n, k;
	readln.chomp.split.tie(n, k);
	int[] p = readln.chomp.split.map!(to!int).array;
	int ite = 0;
	int[] ans;
	RedBlackTree!int tree = new RedBlackTree!int();
	RedBlackTree!int done = new RedBlackTree!int();
	tree.insert(ite);
	done.insert(ite);
	foreach (q; p) {
		int t = tree.lowerBound(q + 1).back;
		debug verbose(q, t, tree);
		if (q - t > k - 1) {
			auto arr = done.lowerBound(t + k);
			if (!arr.empty) {
				t = max(t, arr.back);
			}
			t = max(t + 1, q - k + 1);
			debug verbose("NEW", t);
			tree.insert(t);
		}
		ans ~= t;
		done.insert(q);
	}
	foreach (i, d; ans) {
		if (i) write = " ";
		d.write;
	}
	writeln;
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}

import std.algorithm, std.container, std.conv, std.math, std.range, std.typecons, std.stdio, std.string;

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n, k; readV(n, k);
  int[] p; readA(n, p);

  auto g = new int[](256); g[] = -1;

  auto calcGroup(int pi)
  {
    if (g[pi] >= 0) return g[pi];
    foreach_reverse (pj; max(0, pi-k+1)..pi) {
      if (g[pj] >= 0) {
        if (pi-g[pj]+1 <= k) {
          g[pj+1..pi+1][] = g[pj];
          return g[pj];
        } else {
          g[pj+1..pi+1][] = pj+1;
          return pj+1;
        }
      }
    }
    auto j = max(0, pi-k+1);
    g[j..pi+1] = j;
    return j;
  }

  foreach (i, pi; p)
    write(calcGroup(pi), " ");
}

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

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

  const int m=256;
  auto root=new int[](m);
  fill(root, -1);
  int[] val;
  foreach(i; 0..n){
    if(root[a[i]]<0){
    //   auto left=max(0, a[i]-k+1);
    //   while(root[left]>=0) left++;
    //   for(int j=left; j<min(m, left+k); j++) root[j]=left;
      auto left=a[i];
      for(int j=left; j>=0; j--){
        if(root[j]>=0){
          left=j; break;
        }
      }
      if(left<a[i]){
        if(a[i]-root[left]+1<=k){
          for(int j=left+1; j<=a[i]; j++){
            root[j]=root[left];
          }
        }else{
          for(int j=max(left+1, a[i]-k+1); j<=a[i]; j++){
            root[j]=max(left+1, a[i]-k+1);
          }
        }
      }else{
        for(int j=max(0, a[i]-k+1); j<=a[i]; j++){
          root[j]=max(0, a[i]-k+1);
        }
      }
    }
    val~=root[a[i]];
  }
  writefln("%(%s %)", val);
}

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

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;
import std.numeric;

void main()
{
	int n, k;
	readln.chomp.split.tie(n, k);
	int[] p = readln.chomp.split.map!(to!int).array;
	int ite = 0;
	int[] ans;
	RedBlackTree!int tree = new RedBlackTree!int();
	RedBlackTree!int done = new RedBlackTree!int();
	tree.insert(ite);
	done.insert(ite);
	foreach (q; p) {
		int t = tree.lowerBound(q + 1).back;
		debug verbose(q, t, tree);
		if (q - t > k - 1) {
			auto arr = done.upperBound(t);
			if (!arr.empty) {
				t = max(t, arr.front);
			}
			t = max(t + 1, q - k + 1);
			t = min(t, 255);
			debug verbose("NEW", t);
			tree.insert(t);
		}
		ans ~= t;
		done.insert(q);
	}
	foreach (i, d; ans) {
		if (i) write = " ";
		d.write;
	}
	writeln;
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;
import std.numeric;

void main()
{
	int n, k;
	readln.chomp.split.tie(n, k);
	int[] p = readln.chomp.split.map!(to!int).array;
	int ite = 0;
	int[] ans;
	RedBlackTree!int tree = new RedBlackTree!int();
	RedBlackTree!int done = new RedBlackTree!int();
	tree.insert(ite);
	done.insert(ite);
	foreach (q; p) {
		int t = tree.lowerBound(q + 1).back;
		debug verbose(q, t, tree);
		if (q - t > k - 1) {
			auto arr = done.upperBound(t);
			if (!arr.empty) {
				t = max(t, min(t + k - 1, arr.front));
			}
			t = max(t + 1, q - k + 1);
			debug verbose("NEW", t);
			tree.insert(t);
		}
		ans ~= t;
		done.insert(q);
	}
	foreach (i, d; ans) {
		if (i) write = " ";
		d.write;
	}
	writeln;
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;
import std.numeric;

void main()
{
	int n, k;
	readln.chomp.split.tie(n, k);
	int[] p = readln.chomp.split.map!(to!int).array;
	int ite = 0;
	int[] ans;
	RedBlackTree!int tree = new RedBlackTree!int();
	RedBlackTree!int done = new RedBlackTree!int();
	tree.insert(ite);
	done.insert(ite);
	foreach (q; p) {
		int t = tree.lowerBound(q + 1).back;
		debug verbose(q, t, tree);
		if (q - t > k - 1) {
			t = max(t + 1, q - k + 1);
			t = max(t, min(done.upperBound(t).front + 1, t + k - 1));
			debug verbose("NEW", t);
			tree.insert(t);
		}
		ans ~= t;
		done.insert(q);
	}
	foreach (i, d; ans) {
		if (i) write = " ";
		d.write;
	}
	writeln;
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;
import std.numeric;

void main()
{
	int n, k;
	readln.chomp.split.tie(n, k);
	int[] p = readln.chomp.split.map!(to!int).array;
	int ite = 0;
	int[] ans;
	RedBlackTree!int tree = new RedBlackTree!int();
	RedBlackTree!int done = new RedBlackTree!int();
	tree.insert(ite);
	done.insert(ite);
	foreach (q; p) {
		int t = tree.lowerBound(q + 1).back;
		debug verbose(q, t, tree);
		if (q - t > k - 1) {
			auto arr = done.upperBound(t);
			if (!arr.empty) {
				t = max(t, arr.front);
			}
			t = max(t + 1, q - k + 1);
			debug verbose("NEW", t);
			tree.insert(t);
		}
		ans ~= t;
		done.insert(q);
	}
	foreach (i, d; ans) {
		if (i) write = " ";
		d.write;
	}
	writeln;
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;
import std.numeric;

void main()
{
	int n, k;
	readln.chomp.split.tie(n, k);
	int[] p = readln.chomp.split.map!(to!int).array;
	int ite = 0;
	int[] ans;
	RedBlackTree!int tree = new RedBlackTree!int();
	RedBlackTree!int done = new RedBlackTree!int();
	tree.insert(ite);
	done.insert(ite);
	foreach (q; p) {
		int t = tree.lowerBound(q + 1).back;
		debug verbose(q, t, tree);
		if (q - t > k - 1) {
			t = max(t + 1, q - k + 1);
			t = max(t, min(done.upperBound(t).front + 1, t + k));
			debug verbose("NEW", t);
			tree.insert(t);
		}
		ans ~= t;
		done.insert(q);
	}
	foreach (i, d; ans) {
		if (i) write = " ";
		d.write;
	}
	writeln;
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}


The only difference between easy and hard versions is constraints.If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.A session has begun at Beland State University. Many students are taking exams.Polygraph Poligrafovich is going to examine a group of $$$n$$$ students. Students will take the exam one-by-one in order from $$$1$$$-th to $$$n$$$-th. Rules of the exam are following:  The $$$i$$$-th student randomly chooses a ticket.  if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam.  if the student finds the ticket easy, he spends exactly $$$t_i$$$ minutes to pass the exam. After it, he immediately gets a mark and goes home. Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.The duration of the whole exam for all students is $$$M$$$ minutes ($$$\max t_i \le M$$$), so students at the end of the list have a greater possibility to run out of time to pass the exam.For each student $$$i$$$, you should count the minimum possible number of students who need to fail the exam so the $$$i$$$-th student has enough time to pass the exam.For each student $$$i$$$, find the answer independently. That is, if when finding the answer for the student $$$i_1$$$ some student $$$j$$$ should leave, then while finding the answer for $$$i_2$$$ ($$$i_2>i_1$$$) the student $$$j$$$ student does not have to go home.

The first line of the input contains two integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le M \le 2 \cdot 10^7$$$) — the number of students and the total duration of the exam in minutes, respectively. The second line of the input contains $$$n$$$ integers $$$t_i$$$ ($$$1 \le t_i \le 100$$$) — time in minutes that $$$i$$$-th student spends to answer to a ticket. It's guaranteed that all values of $$$t_i$$$ are not greater than $$$M$$$.

Print $$$n$$$ numbers: the $$$i$$$-th number must be equal to the minimum number of students who have to leave the exam in order to $$$i$$$-th student has enough time to pass the exam.

NoteThe explanation for the example 1.Please note that the sum of the first five exam times does not exceed $$$M=15$$$ (the sum is $$$1+2+3+4+5=15$$$). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are $$$0$$$.In order for the $$$6$$$-th student to pass the exam, it is necessary that at least $$$2$$$ students must fail it before (for example, the $$$3$$$-rd and $$$4$$$-th, then the $$$6$$$-th will finish its exam in $$$1+2+5+6=14$$$ minutes, which does not exceed $$$M$$$).In order for the $$$7$$$-th student to pass the exam, it is necessary that at least $$$3$$$ students must fail it before (for example, the $$$2$$$-nd, $$$5$$$-th and $$$6$$$-th, then the $$$7$$$-th will finish its exam in $$$1+3+4+7=15$$$ minutes, which does not exceed $$$M$$$).

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

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

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

    auto rbt = make!(RedBlackTree!(int, "a < b", true));
    int s = 0;
    int minans = 0;
    int[] res;
    foreach (e; arr) {
        int curans = minans;
        int curs = s;
        foreach_reverse (big; rbt) {
            if (curs + e <= m) { break; }

            curs -= big;
            curans += 1;
        }

        rbt.insert(e);
        s += e;

        while (s > m) {
            s -= rbt.back;
            rbt.removeBack();
            minans += 1;
        }

        res ~= curans;
    }

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

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

immutable int limit = 101;

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		readln;
		auto t = readln.splitter.map !(to !(int)).array;
		auto c = new int [limit];

		int [] ans;
		foreach (int num, ref value; t)
		{
			auto r = m - value;
			int cur = 0;
			foreach (i; 1..limit)
			{
				auto add = min (r / i, c[i]);
				cur += add;
				r -= add * i;
			}
			ans ~= num - cur;
			c[value] += 1;
		}
		writefln ("%(%s %)", ans);
	}
}

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

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

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

    auto rbt = make!(RedBlackTree!int);
    int s = 0;
    foreach (e; arr) {
        int ans = 0;
        int curs = s;
        foreach_reverse (big; rbt) {
            if (curs + e <= m) { break; }

            curs -= big;
            ans += 1;
        }

        rbt.insert(e);
        s += e;

        ans.writeln;
    }
}

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

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

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

    auto rbt = make!(RedBlackTree!int);
    int s = 0;
    int[] res;
    foreach (e; arr) {
        int ans = 0;
        int curs = s;
        foreach_reverse (big; rbt) {
            if (curs + e <= m) { break; }

            curs -= big;
            ans += 1;
        }

        rbt.insert(e);
        s += e;

        res ~= ans;
    }

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

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

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

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

    auto rbt = make!(RedBlackTree!(int, "a < b", true));
    int s = 0;
    int[] res;
    foreach (e; arr) {
        int ans = 0;
        int curs = s;
        foreach_reverse (big; rbt) {
            if (curs + e <= m) { break; }

            curs -= big;
            ans += 1;
        }

        rbt.insert(e);
        s += e;

        while (rbt.length > 100) {
            rbt.removeFront();
        }

        res ~= ans;
    }

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


We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).

The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings. Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.

Print any suitable string s, or -1 if such string doesn't exist.

NoteIn the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.In the third example it's impossible to obtain given strings by aforementioned operations.

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

void main() {
    int k,n;
    scan(k,n);

    auto s = new char[][](k, 0);
    foreach (i ; 0 .. k) {
        s[i] = readln.chomp.to!(char[]);
    }

    auto ss = s.sort().uniq.array;
    k = ss.length.to!int;

    if (k == 1) {
        swap(ss[0][0], ss[0][1]);
        writeln(ss[0]);
        return;
    }
    else {
        auto acnt = countAlpha(ss[0]);
        auto bcnt = countAlpha(ss[1]);

        if (acnt != bcnt) {
            writeln(-1);
            return;
        }

        int dp = acnt.reduce!max;
        auto kouho = new char[][](0, 0);
        auto dif = new int[](0);

        foreach (i ; 0 .. n) {
            if (ss[0][i] != ss[1][i]) {
                dif ~= i;
            }
        }

        if (dif.length < 2 || dif.length > 4) {
            writeln(-1);
            return;
        }
        else if (dif.length > 2) {
            foreach (x ; 0 .. dif.length) {
                foreach (y ; x + 1 .. dif.length) {
                    auto sk = ss[0].dup;
                    swap(sk[dif[x]], sk[dif[y]]);
                    kouho ~= sk;
                }
            }
        }
        else {
            if (dp < 2) {
                writeln(-1);
                return;
            }

            kouho ~= ss[0];
            kouho ~= ss[1];

            int i = dif[0], j = dif[1];
            char a = ss[0][i], b = ss[0][j];

            foreach (x ; 0 .. n) {
                if (x == i || x == j) continue;

                if (ss[0][x] == a) {
                    auto sk = ss[0].dup;
                    sk[j] = a, sk[x] = b;
                    kouho ~= sk;
                }
                else if (ss[0][x] == b) {
                    auto sk = ss[0].dup;
                    sk[i] = b, sk[x] = a;
                    kouho ~= sk;
                }
            }
        }

        debug {
            writeln(kouho);
        }

        foreach (i ; 0 .. k) {
            auto ccnt = countAlpha(ss[i]);

            if (acnt != ccnt) {
                writeln(-1);
                return;
            }

            auto ok = new bool[](kouho.length);

            foreach (int idx, sk ; kouho) {
                int df;

                foreach (j ; 0 .. n) {
                    df += (ss[i][j] != sk[j]);
                }

                if (df == 2 || (df == 0 && dp > 1)) {
                    ok[idx] = 1;
                }
            }

            kouho = iota(kouho.length).filter!(i => ok[i]).map!(i => kouho[i]).array;

            debug {
                kouho.writeln;
            }
        }

        if (kouho.empty) {
            writeln(-1);
        }
        else {
            writeln(kouho[0]);
        }
    }
}

int[] countAlpha(char[] s) {
    auto cnt = new int[](26);
    s.each!(ch => cnt[ch - 'a']++);
    return cnt;
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

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

void main() {
    int k,n;
    scan(k,n);

    auto s = new char[][](k, 0);
    foreach (i ; 0 .. k) {
        s[i] = readln.chomp.to!(char[]);
    }

    auto ss = s.sort().uniq.array;

    if (ss.length == 1) {
        swap(ss[0][0], ss[0][1]);
        writeln(ss[0]);
        return;
    }
    else {
        auto acnt = countAlpha(ss[0]);
        auto bcnt = countAlpha(ss[1]);

        if (acnt != bcnt) {
            writeln(-1);
            return;
        }

        int dp = acnt.reduce!max;
        auto kouho = new char[][](0, 0);
        auto dif = new int[](0);

        foreach (i ; 0 .. n) {
            if (ss[0][i] != ss[1][i]) {
                dif ~= i;
            }
        }

        if (dif.length == 1 || dif.length > 4) {
            writeln(-1);
            return;
        }
        else if (dif.length > 2) {
            foreach (x ; 0 .. dif.length) {
                foreach (y ; x + 1 .. dif.length) {
                    auto sk = ss[0].dup;
                    swap(sk[dif[x]], sk[dif[y]]);
                    kouho ~= sk;
                }
            }
        }
        else {
            if (dp < 2) {
                writeln(-1);
                return;
            }

            kouho ~= ss[0];
            kouho ~= ss[1];

            int i = dif[0], j = dif[1];
            char a = ss[0][i], b = ss[0][j];

            foreach (x ; 0 .. n) {
                if (x == i || x == j) continue;

                if (ss[0][x] == a) {
                    auto sk = ss[0].dup;
                    sk[j] = a, sk[x] = b;
                    kouho ~= sk;
                }
                else if (ss[0][x] == b) {
                    auto sk = ss[0].dup;
                    sk[i] = b, sk[x] = a;
                    kouho ~= sk;
                }
            }
        }

        debug {
            writeln(kouho);
        }

        foreach (i ; 0 .. k) {
            auto ccnt = countAlpha(ss[i]);

            if (acnt != ccnt) {
                writeln(-1);
                return;
            }

            auto ok = new bool[](kouho.length);

            foreach (int idx, sk ; kouho) {
                int df;

                foreach (j ; 0 .. n) {
                    df += (ss[i][j] != sk[j]);
                }

                if (df == 2 || (df == 0 && dp > 1)) {
                    ok[idx] = 1;
                }
            }

            kouho = iota(kouho.length).filter!(i => ok[i]).map!(i => kouho[i]).array;

            debug {
                kouho.writeln;
            }
        }

        if (kouho.empty) {
            writeln(-1);
        }
        else {
            writeln(kouho[0]);
        }
    }
}

int[] countAlpha(char[] s) {
    auto cnt = new int[](26);
    s.each!(ch => cnt[ch - 'a']++);
    return cnt;
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


Alina has a bracket sequence $$$s$$$ of length $$$2n$$$, consisting of $$$n$$$ opening brackets '(' and $$$n$$$ closing brackets ')'. As she likes balance, she wants to turn this bracket sequence into a balanced bracket sequence.In one operation, she can reverse any substring of $$$s$$$.What's the smallest number of operations that she needs to turn $$$s$$$ into a balanced bracket sequence? It can be shown that it's always possible in at most $$$n$$$ operations.As a reminder, a sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters + and 1. For example, sequences (())(), (), and (()(())) are balanced, while )(, ((), and (()))( are not.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains a string $$$s$$$ of length $$$2n$$$, consisting of $$$n$$$ opening and $$$n$$$ closing brackets. The sum of $$$n$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.

For each test case, in the first line output a single integer $$$k$$$ $$$(0 \le k \le n)$$$  — the smallest number of operations required. The $$$i$$$-th of the next $$$k$$$ lines should contain two integers $$$l_i, r_i$$$ ($$$1 \le l_i \le r_i \le 2n$$$), indicating that in the $$$i$$$-th operation, Alina will reverse the substring $$$s_ls_{l+1} \ldots s_{r-1}s_r$$$. Here the numeration starts from $$$1$$$. If there are multiple sequences of operations with the smallest length which transform the sequence into a balanced one, you can output any of them.

NoteIn the first test case, the string is already balanced.In the second test case, the string will be transformed as follows: ())((()))( $$$\to$$$ ()()(()))( $$$\to$$$ ()()(())(), where the last string is balanced.In the third test case, the string will be transformed to ((()))((())), which is balanced.

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

enum FAIL = [-1];

int N;
string S;

int[] hs;
int im;

int[] solve0() {
  foreach (i; 0 .. 2 * N + 1) {
    if (hs[i] < 0) {
      return FAIL;
    }
  }
  return [];
}

int[] solve1() {
  int a = -1, b = -1;
  foreach         (i; 0 .. 2 * N + 1) if (hs[i] < 0) { a = i - 1; break; }
  foreach_reverse (i; 0 .. 2 * N + 1) if (hs[i] < 0) { b = i + 1; break; }
  assert(hs[a] == 0);
  assert(hs[b] == 0);
  debug {
    writeln("  a = ", a, ", b = ", b);
  }

  if (im <= a) return [im, 2 * N];
  if (b <= im) return [0, im];

  int am, bm;
  foreach (i; 0 .. a + 1)     if (hs[am] < hs[i]) am = i;
  foreach (i; b .. 2 * N + 1) if (hs[bm] < hs[i]) bm = i;
  debug {
    writeln("  am = ", am, ", bm = ", bm);
  }
  if (hs[am] + hs[bm] - hs[im] >= 0) {
    return [am, bm];
  }

  return FAIL;
}

int[] solve2() {
  return [0, im, im, 2 * N];
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        N = readInt;
        S = readToken;

        hs = new int[2 * N + 1];
        foreach (i; 0 .. 2 * N) {
          hs[i + 1] = hs[i] + ((S[i] == '(') ? +1 : -1);
        }
        im = 0;
        foreach (i; 0 .. 2 * N + 1) {
          if (hs[im] < hs[i]) {
            im = i;
          }
        }
        debug {
          writeln("  hs = ", hs);
          writeln("  im = ", im);
        }

        int[] ans;

        ans = solve0;
        if (ans != FAIL) {
          debug {
            writeln("  ", S);
          }
          writeln(0);
          continue;
        }
        ans = solve1;
        if (ans != FAIL) {
          debug {
            auto cs = S.dup;
            cs[ans[0] .. ans[1]].reverse;
            writeln("  ", cs);
          }
          writeln(1);
          writeln(ans[0] + 1, " ", ans[1]);
          continue;
        }
        ans = solve2;
        if (ans != FAIL) {
          debug {
            auto cs = S.dup;
            cs[ans[0] .. ans[1]].reverse;
            cs[ans[2] .. ans[3]].reverse;
            writeln("  ", cs);
          }
          writeln(2);
          writeln(ans[0] + 1, " ", ans[1]);
          writeln(ans[2] + 1, " ", ans[3]);
          continue;
        }

        assert(false);
      }
    }
  } catch (EOFException e) {
  }
}

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);
		n *= 2;
		auto a = readln.strip.map !(q{[-1, +1][a == '(']}).array;

		bool isOk ()
		{
			int bal = 0;
			foreach (i; 0..n)
			{
				bal += a[i];
				if (bal < 0)
				{
					return false;
				}
			}
			return true;
		}

		bool solve (int [] [] actions)
		{
			foreach (ref line; actions)
			{
				reverse (a[line[0]..line[1]]);
			}
			if (isOk ())
			{
				writeln (actions.length);
				foreach (ref line; actions)
				{
					writeln (line[0] + 1, " ", line[1]);
				}
				return true;
			}
			foreach_reverse (ref line; actions)
			{
				reverse (a[line[0]..line[1]]);
			}
			return false;
		}

		if (solve ([])) continue;

		{
			int lo = 0;
			int bestLo = 0;
			int cur = 0;
			foreach (i; 0..n)
			{
				cur += a[i];
				if (bestLo < cur)
				{
					bestLo = cur;
					lo = i + 1;
				}
				if (cur < 0)
				{
					break;
				}
			}

			int hi = n;
			int bestHi = 0;
			cur = 0;
			foreach_reverse (i; 0..n)
			{
				cur -= a[i];
				if (bestHi < cur)
				{
					bestHi = cur;
					hi = i;
				}
				if (cur < 0)
				{
					break;
				}
			}

			if (solve ([[lo, hi]])) continue;
		}

		{
			int p = 0;
			int up = 0;
			int cur = 0;
			foreach (i; 0..n)
			{
				cur += a[i];
				if (up < cur)
				{
					up = cur;
					p = i + 1;
				}
			}
			if (solve ([[0, p], [p, n]])) continue;
		}

		assert (false);
	}
}

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

enum FAIL = [-1];

int N;
string S;

int[] hs;
int im;

int[] solve0() {
  foreach (i; 0 .. 2 * N + 1) {
    if (hs[i] < 0) {
      return FAIL;
    }
  }
  return [];
}

int[] solve1() {
  int a = -1, b = -1;
  foreach         (i; 0 .. 2 * N + 1) if (hs[i] < 0) { a = i - 1; break; }
  foreach_reverse (i; 0 .. 2 * N + 1) if (hs[i] < 0) { b = i + 1; break; }
  assert(hs[a] == 0);
  assert(hs[b] == 0);
  debug {
    writeln("  a = ", a, ", b = ", b);
  }

  if (im <= a) return [im, 2 * N];
  if (b <= im) return [0, im];

  int am, bm;
  foreach (i; 0 .. a + 1)     if (hs[am] < hs[i]) am = i;
  foreach (i; b .. 2 * N + 1) if (hs[bm] < hs[i]) bm = i;
  debug {
    writeln("  am = ", am, ", bm = ", bm);
  }
  if (hs[am] + hs[bm] - hs[im] >= 0) {
    return [am, bm];
  }

  return FAIL;
}

int[] solve2() {
  return [0, im, im, 2 * N];
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        N = readInt;
        S = readToken;

        hs = new int[2 * N + 1];
        foreach (i; 0 .. 2 * N) {
          hs[i + 1] = hs[i] + ((S[i] == '(') ? +1 : -1);
        }
        foreach (i; 0 .. 2 * N + 1) {
          if (hs[im] < hs[i]) {
            im = i;
          }
        }
        debug {
          writeln("  hs = ", hs);
          writeln("  im = ", im);
        }

        int[] ans;

        ans = solve0;
        if (ans != FAIL) {
          writeln(0);
          continue;
        }
        ans = solve1;
        if (ans != FAIL) {
          writeln(1);
          writeln(ans[0] + 1, " ", ans[1]);
          continue;
        }
        ans = solve2;
        if (ans != FAIL) {
          writeln(2);
          writeln(ans[0] + 1, " ", ans[1]);
          writeln(ans[2] + 1, " ", ans[3]);
          continue;
        }

        assert(false);
      }
    }
  } catch (EOFException e) {
  }
}


In distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time "0 hours", instead of it "n hours" is used. When local time in the 1-st timezone is 1 hour, local time in the i-th timezone is i hours.Some online programming contests platform wants to conduct a contest that lasts for an hour in such a way that its beginning coincides with beginning of some hour (in all time zones). The platform knows, that there are ai people from i-th timezone who want to participate in the contest. Each person will participate if and only if the contest starts no earlier than s hours 00 minutes local time and ends not later than f hours 00 minutes local time. Values s and f are equal for all time zones. If the contest starts at f hours 00 minutes local time, the person won't participate in it.Help platform select such an hour, that the number of people who will participate in the contest is maximum.

The first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of hours in day. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 10 000), where ai is the number of people in the i-th timezone who want to participate in the contest. The third line contains two space-separated integers s and f (1 ≤ s < f ≤ n).

Output a single integer — the time of the beginning of the contest (in the first timezone local time), such that the number of participants will be maximum possible. If there are many answers, output the smallest among them.

NoteIn the first example, it's optimal to start competition at 3 hours (in first timezone). In this case, it will be 1 hour in the second timezone and 2 hours in the third timezone. Only one person from the first timezone won't participate.In second example only people from the third and the fourth timezones will participate.

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

void main(){

	int n, w, d, f, s, cnt = 0;
	int[100010] a;

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

	for (int i = 1; i <= n; ++i){
		if (i < n) readf("%s ", &a[i]);
		else readf("%s", &a[i]);
	}

	readln;

	readf("%d %d", &s, &f);
	readln;

	for (int i = s; i <= f - 1; ++i) d += a[i];

	for (int i = 1; i <= n; ++i){
		if (d > cnt) d = cnt, w = i;
		--s, --f;
		if (s < 1) s += n;
		if (f < 1) f += n;
		d = d - a[f] + a[s];
	}

	writeln(w);
}


Allen wants to enter a fan zone that occupies a round square and has $$$n$$$ entrances.There already is a queue of $$$a_i$$$ people in front of the $$$i$$$-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute.Allen uses the following strategy to enter the fan zone:   Initially he stands in the end of the queue in front of the first entrance.  Each minute, if he is not allowed into the fan zone during the minute (meaning he is not the first in the queue), he leaves the current queue and stands in the end of the queue of the next entrance (or the first entrance if he leaves the last entrance). Determine the entrance through which Allen will finally enter the fan zone.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of entrances. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the number of people in queues. These numbers do not include Allen.

Print a single integer — the number of entrance that Allen will use.

NoteIn the first example the number of people (not including Allen) changes as follows: $$$[\textbf{2}, 3, 2, 0] \to [1, \textbf{2}, 1, 0] \to [0, 1, \textbf{0}, 0]$$$. The number in bold is the queue Alles stands in. We see that he will enter the fan zone through the third entrance.In the second example the number of people (not including Allen) changes as follows: $$$[\textbf{10}, 10] \to [9, \textbf{9}] \to [\textbf{8}, 8] \to [7, \textbf{7}] \to [\textbf{6}, 6] \to \\ [5, \textbf{5}] \to [\textbf{4}, 4] \to [3, \textbf{3}] \to [\textbf{2}, 2] \to [1, \textbf{1}] \to [\textbf{0}, 0]$$$.In the third example the number of people (not including Allen) changes as follows: $$$[\textbf{5}, 2, 6, 5, 7, 4] \to [4, \textbf{1}, 5, 4, 6, 3] \to [3, 0, \textbf{4}, 3, 5, 2] \to \\ [2, 0, 3, \textbf{2}, 4, 1] \to [1, 0, 2, 1, \textbf{3}, 0] \to [0, 0, 1, 0, 2, \textbf{0}]$$$.

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()
{
    readln;

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

    auto ans = 1;
    auto mn = 10L ^^ 10;
    foreach (i, e; a) {
        auto now = i + (max(0L, e - i + a.length - 1) / a.length) * a.length;
        if (now < mn) mn = now, ans = cast(int) i + 1;
    }

    ans.writeln;
}

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()
{
    readln;

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

    auto ans = 1, mn = 10 ^^ 9;
    foreach (i, e; a) {
        auto now = i + (max(0, e - i + a.length - 1) / a.length) * a.length;
        if (now < mn) mn = cast(int) now, ans = cast(int) i + 1;
    }

    ans.writeln;
}

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()
{
    readln;

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

    auto ans = 0, mn = 10 ^^ 9;
    foreach (i, e; a) {
        auto now = i + (max(0, e - i + a.length - 1) / a.length) * a.length;
        if (now < mn) mn = cast(int) now, ans = cast(int) i + 1;
    }

    ans.writeln;
}


You are given a range of positive integers from $$$l$$$ to $$$r$$$.Find such a pair of integers $$$(x, y)$$$ that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$.If there are multiple answers, print any of them.You are also asked to answer $$$T$$$ independent queries.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of queries. Each of the next $$$T$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 998244353$$$) — inclusive borders of the range. It is guaranteed that testset only includes queries, which have at least one suitable pair.

Print $$$T$$$ lines, each line should contain the answer — two integers $$$x$$$ and $$$y$$$ such that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$. The answer in the $$$i$$$-th line should correspond to the $$$i$$$-th query from the input. If there are multiple answers, print any of them.

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

void main() {
    int t;
    readf!" %s"(t);

    foreach (i; 0 .. t) {
        int l,r;
        readf!" %s %s"(l,r);

        writeln(l," ",2*l);
    }
}

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;

void main() {
    auto T = readln.chomp.to!int;
    while (T--) {
        auto s = readln.split.map!(to!long);
        auto l = s[0];
        auto r = s[1];
        writeln(l, " ", l * 2);
    }
}

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

  int t;
  rd(t);
  while (t--) {
    int l, r;
    rd(l, r);
    writeln(l, " ", l * 2);
  }

}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}

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

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

void main() {
  GC.disable();

  int T;
  readf(" %s", T);
  foreach(i; 0 .. T) {
    long l, r;
    readf(" %s %s", l, r);
    writef("%s %s\n", l, l*2);
  }

}


One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.

The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).

In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.

import std.stdio, std.string;

int r[1010][1010];
int a[1000010][2];

void solve(int n, int k)
{
    if (k > n * (n - 1) / 2)
    {
        printf("-1\n");
        return;
    }
    foreach (int i; 0 .. n)
    {
        foreach (int j; 0 .. n)
        {
            r[i][j] = 0;
        }
    }
    int idx = 0;
    foreach (int i; 0 .. n)
    {
        int cnt = 0;
        for (int j = 0; cnt < k && j < n; ++ j)
        {
            if (j == i || r[i][j] == 1)
            {
                continue;
            }
            a[idx][0] = i + 1;
            a[idx][1] = j + 1;
            ++ idx;
            r[i][j] = r[j][i] = 1;
            ++ cnt;
        }
        if (cnt < k)
        {
            printf("-1\n");
            return;
        }
    }
    printf("%d\n", n * k);
    foreach (int i; 0 .. n * k)
    {
        printf("%d %d\n", a[i][0], a[i][1]);
    }
}

void main(string[] args)
{
    int n, k;
    while (scanf("%d%d", &n, &k) == 2)
    {
        solve(n, k);
    }
}

import std.stdio;
import std.typecons;

void main()
{
	uint n, k;

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

	uint pairs = n * (n - 1) / 2;

	if(pairs < k * n)
	{
		writeln("-1");
		return;
	}

	uint[] wins = new uint[n + 1];
	uint[] losses = new uint[n + 1];

	uint maxLosses = n - 1 - k;

	Tuple!(uint, uint)[] lines;

	for(uint i = 1; i <= n; i++)
	{
		for(uint j = i + 1; j <= n; j++)
		{
			if(wins[i] < k && losses[j] < maxLosses)
			{
				wins[i]++;
				losses[j]++;
				lines ~= Tuple!(uint, uint)(i, j);
			}
			else if(wins[j] < k && losses[i] < maxLosses)
			{
				wins[j]++;
				losses[i]++;
				lines ~= Tuple!(uint, uint)(j, i);
			}
		}
	}

	writeln(lines.length);
	foreach(line; lines)
	{
		writeln(line[0], " ", line[1]);
	}
}

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		if (k + k < n)
		{
			writeln (n * k);
			foreach (i; 0..n)
			{
				foreach (j; 1..k + 1)
				{
					writeln (i + 1, ' ', (i + j) % n + 1);
				}
			}
		}
		else
		{
			writeln (-1);
		}
	}
}

module football;
import std.stdio, std.array, std.range, std.string, std.typecons;
import std.algorithm, std.container, std.math, std.numeric, std.random;
void scan(T...)(ref T args) { foreach (ref arg; args) readf(" %s", &arg); }
void minify(T)(ref T a, in T b) { if (a > b) a = b; }
void maxify(T)(ref T a, in T b) { if (a < b) a = b; }
void ewriteln(T...)(T args) { stderr.writeln("\033[35m", args, "\033[0m"); }

int n, k;
void readInput() {
	scan(n, k);
}

void tc() {
	readInput();
	if (2*k > n-1) { writeln("-1"); return; }
	writeln(n * k);
	foreach (i; 0..n) {
		foreach (j; 0..k) {
			writeln(i + 1, " ", (i+j+1)%n+1);
		}
	}
}

void main() { tc(); }

import std.stdio;
import std.typecons;

void main()
{
	uint n, k;

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

	uint pairs = n * (n - 1);

	if(pairs < k * n)
	{
		writeln("-1");
		return;
	}

	uint[] wins = new uint[n + 1];

	Tuple!(uint, uint)[] lines;

	for(uint i = 1; i <= n; i++)
	{
		for(uint j = i + 1; j <= n; j++)
		{
			if(wins[i] < k)
			{
				wins[i]++;
				lines ~= Tuple!(uint, uint)(i, j);
			}
			else if(wins[j] < k)
			{
				wins[j]++;
				lines ~= Tuple!(uint, uint)(j, i);
			}
		}
	}

	writeln(lines.length);
	foreach(line; lines)
	{
		writeln(line[0], " ", line[1]);
	}
}

import std.stdio;
import std.typecons;

void main()
{
	uint n, k;

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

	uint pairs = n * (n - 1);

	if(pairs < k * n)
	{
		writeln("-1");
		return;
	}

	uint[] wins = new uint[n + 1];
	uint[] losses = new uint[n + 1];

	uint maxLosses = n - 1 - k;

	Tuple!(uint, uint)[] lines;

	for(uint i = 1; i <= n; i++)
	{
		for(uint j = i + 1; j <= n; j++)
		{
			if(wins[i] < k && losses[j] < maxLosses)
			{
				wins[i]++;
				losses[j]++;
				lines ~= Tuple!(uint, uint)(i, j);
			}
			else if(wins[j] < k && losses[i] < maxLosses)
			{
				wins[j]++;
				losses[i]++;
				lines ~= Tuple!(uint, uint)(j, i);
			}
		}
	}

	writeln(lines.length);
	foreach(line; lines)
	{
		writeln(line[0], " ", line[1]);
	}
}


You have a long stick, consisting of $$$m$$$ segments enumerated from $$$1$$$ to $$$m$$$. Each segment is $$$1$$$ centimeter long. Sadly, some segments are broken and need to be repaired.You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length $$$t$$$ placed at some position $$$s$$$ will cover segments $$$s, s+1, \ldots, s+t-1$$$.You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap.Time is money, so you want to cut at most $$$k$$$ continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 10^5$$$, $$$n \le m \le 10^9$$$, $$$1 \le k \le n$$$) — the number of broken segments, the length of the stick and the maximum number of pieces you can use. The second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le m$$$) — the positions of the broken segments. These integers are given in increasing order, that is, $$$b_1 < b_2 < \ldots < b_n$$$.

Print the minimum total length of the pieces.

NoteIn the first example, you can use a piece of length $$$11$$$ to cover the broken segments $$$20$$$ and $$$30$$$, and another piece of length $$$6$$$ to cover $$$75$$$ and $$$80$$$, for a total length of $$$17$$$.In the second example, you can use a piece of length $$$4$$$ to cover broken segments $$$1$$$, $$$2$$$ and $$$4$$$, and two pieces of length $$$1$$$ to cover broken segments $$$60$$$ and $$$87$$$.

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;

void main() {
    auto s = readln.split.map!(to!int).array;
    auto N = s[0];
    auto M = s[1].to!long;
    auto K = s[2].to!long;
    auto A = readln.split.map!(to!long).array;

    if (N == 1) {
        writeln(1);
        return;
    }

    auto B = (N-1).iota.map!(i => A[i+1] - A[i] - 1).array;
    B.sort!"a > b";

    long ans = A.back - A.front + 1;
    long cnt = 1;
    int p = 0;

    while (cnt < K && p < B.length) {
        ans -= B[p];
        p += 1;
        cnt += 1;
    }

    ans.writeln;
}

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

void main ()
{
	int n, m, k;
	while (readf (" %s %s %s", &n, &m, &k) > 0)
	{
		readln;
		auto b = readln.splitter.map !(to !(int)).array;
		auto c = iota (n - 1).map !(i => b[i + 1] - b[i] - 1).array;
		sort (c);
		long res = n;
		res += sum (c[0..n - k], 0L);
		writeln (res);
	}
}