Little Bolek has found a picture with n mountain peaks painted on it. The n painted peaks are represented by a non-closed polyline, consisting of 2n segments. The segments go through 2n + 1 points with coordinates (1, y1), (2, y2), ..., (2n + 1, y2n + 1), with the i-th segment connecting the point (i, yi) and the point (i + 1, yi + 1). For any even i (2 ≤ i ≤ 2n) the following condition holds: yi - 1 < yi and yi > yi + 1. We shall call a vertex of a polyline with an even x coordinate a mountain peak.   The figure to the left shows the initial picture, the figure to the right shows what the picture looks like after Bolek's actions. The affected peaks are marked red, k = 2.  Bolek fancied a little mischief. He chose exactly k mountain peaks, rubbed out the segments that went through those peaks and increased each peak's height by one (that is, he increased the y coordinate of the corresponding points). Then he painted the missing segments to get a new picture of mountain peaks. Let us denote the points through which the new polyline passes on Bolek's new picture as (1, r1), (2, r2), ..., (2n + 1, r2n + 1).Given Bolek's final picture, restore the initial one.

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 100). The next line contains 2n + 1 space-separated integers r1, r2, ..., r2n + 1 (0 ≤ ri ≤ 100) — the y coordinates of the polyline vertices on Bolek's picture. It is guaranteed that we can obtain the given picture after performing the described actions on some picture of mountain peaks.

Print 2n + 1 integers y1, y2, ..., y2n + 1 — the y coordinates of the vertices of the polyline on the initial picture. If there are multiple answers, output any one of them.

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

void main() {
    int n, k; readf("%d %d\n", &n, &k);
    int[] ys = stdin.readln.split.map!(to!int).array;
    Array!int cs;
    foreach (i; 0 .. n) {
        int x = i * 2 + 1;
        int y = ys[x] - 1;
        if (ys[x-1] < y && y > ys[x+1]) {
            cs.insert(x);
        }
    }
    for (int i = 0; i < k; i++) {
        ys[cs[i]]--;
    }
    write(ys[0]);
    foreach (y; ys[1 .. $]) {
        writef(" %d", y);
    }
    writeln;
}

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

void main() {
    int n, k; readf("%d %d\n", &n, &k);
    int[] ys = stdin.readln.split.map!(to!int).array;
    Array!int cs;
    foreach (i; 0 .. n) {
        int x = i * 2 + 1;
        if (ys[x-1] < ys[x] && ys[x] > ys[x+1]) {
            cs.insert(x);
        }
    }
    for (int i = 0; i < k; i++) {
        ys[cs[i]]--;
    }
    write(ys[0]);
    foreach (y; ys[1 .. $]) {
        writef(" %d", y);
    }
    writeln;
}


Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue.The distance between two tree nodes v and u is the number of edges in the shortest path between v and u.Xenia needs to learn how to quickly execute queries of two types:  paint a specified blue node in red;  calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries.

The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct.

For each second type query print the reply in a single line.

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

void main() {
  int n, m;
  readf(" %s %s", &n, &m);
  auto adj = new int[][n];
  foreach (i; 0..n - 1) {
    int u, v;
    readf(" %s %s", &u, &v);
    u--; v--;
    adj[u] ~= v;
    adj[v] ~= u;
  }

  // LCA

  auto depth = new int[n];
  auto jump = new int[20][n];
  auto tin = new int[n];
  auto tout = new int[n];
  int timer = -1;

  void dfsLCA(int u, int par, int dep) {
    depth[u] = dep;
    tin[u] = ++timer;
    jump[u][0] = par;
    foreach (i; 1..20) {
      if (jump[u][i - 1] != -1) {
        jump[u][i] = jump[jump[u][i - 1]][i - 1];
      }
    }
    foreach (v; adj[u]) {
      if (v != par) {
        dfsLCA(v, u, dep + 1);
      }
    }
    tout[u] = timer;
  }

  bool isAncestor(int u, int v) {
    return tin[u] <= tin[v] && tout[u] >= tout[v];
  }

  int getLCA(int u, int v) {
    if (depth[u] > depth[v]) {
      swap(u, v);
    }
    if (isAncestor(u, v)) {
      return u;
    }
    foreach_reverse (i; 0..20) {
      if (jump[v][i] != -1 && !isAncestor(jump[v][i], u)) {
        v = jump[v][i];
      }
    }
    return jump[v][0];
  }

  int getDistance(int u, int v) {
    int lca = getLCA(u, v);
    return depth[u] + depth[v] - 2 * depth[lca];
  }

  // centroid

  auto done = new bool[n];
  int centroid, centroidMax;

  int dfs(int u, int par, int sz) {
    int ret = 1;
    int mx = 0;
    foreach (v; adj[u]) {
      if (v != par && !done[v]) {
        int vs = dfs(v, u, sz);
        ret += vs;
        mx = max(mx, vs);
      }
    }
    if (sz < int.max) {
      mx = max(mx, sz - mx);
      if (mx < centroidMax) {
        centroidMax = mx;
        centroid = u;
      }
    }
    return ret;
  }

  auto parCentroid = new int[n];

  void decompose(int u, int prevCentroid) {
    int sz = dfs(u, -1, int.max);
    centroid = -1;
    centroidMax = int.max;
    dfs(u, -1, sz);
    u = centroid;
    parCentroid[u] = prevCentroid;
    done[u] = true;
    foreach (v; adj[u]) {
      if (!done[v]) {
        decompose(v, u);
      }
    }
  }

  auto nearest = new int[n];
  nearest[] = int.max / 2;

  void makeRed(int u) {
    int p = u;
    while (p != -1) {
      int dist = getDistance(p, u);
      nearest[p] = min(nearest[p], dist);
      p = parCentroid[p];
    }
  }

  int query(int u) {
    int ret = int.max;
    int p = u;
    while (p != -1) {
      int dist = getDistance(p, u);
      ret = min(ret, dist + nearest[p]);
      p = parCentroid[p];
    }
    return ret;
  }

  // GO!
  dfsLCA(0, -1, 0);

  decompose(0, -1);

  makeRed(0);

  while (m--) {
    int t, v;
    readf(" %s %s", &t, &v);
    v--;
    if (t == 1) {
      makeRed(v);
    } else {
      writeln(query(v));
    }
  }
}


Let $$$n$$$ be an integer. Consider all permutations on integers $$$1$$$ to $$$n$$$ in lexicographic order, and concatenate them into one big sequence $$$P$$$. For example, if $$$n = 3$$$, then $$$P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$$$. The length of this sequence is $$$n \cdot n!$$$.Let $$$1 \leq i \leq j \leq n \cdot n!$$$ be a pair of indices. We call the sequence $$$(P_i, P_{i+1}, \dots, P_{j-1}, P_j)$$$ a subarray of $$$P$$$. You are given $$$n$$$. Find the number of distinct subarrays of $$$P$$$. Since this number may be large, output it modulo $$$998244353$$$ (a prime number).

The only line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$), as described in the problem statement.

Output a single integer — the number of distinct subarrays, modulo $$$998244353$$$.

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 SuffixArray(T) {
  import std.algorithm : sort;
  int n;
  T[] ts;
  int[] us, su, lcp;
  this(T)(T[] ts) {
    n = cast(int)(ts.length);
    this.ts = ts;
    us = new int[n + 1];
    su = new int[n + 1];
    foreach (i; 0 .. n + 1) us[i] = i;
    us.sort!((u, v) => (cmp(u, v) < 0));
    auto vals = new int[n + 1], cnt = new int[n + 1], tmp = new int[n + 1];
    foreach (i; 0 .. n) vals[i + 1] = vals[i] + ((cmp(us[i], us[i + 1]) < 0) ? 1 : 0);
    for (int h = 1; ; h <<= 1) {
      int ahead(int i) {
        return (us[i] + h <= n) ? su[us[i] + h] : 0;
      }
      foreach (i; 0 .. n + 1) su[us[i]] = vals[i];
      if (vals[n] == n) break;
      cnt[] = 0;
      foreach (i; 0 .. n + 1) ++cnt[ahead(i)];
      foreach (j; 0 .. n) cnt[j + 1] += cnt[j];
      foreach_reverse (i; 0 .. n + 1) tmp[--cnt[ahead(i)]] = us[i];
      cnt[] = 0;
      foreach (i; 0 .. n + 1) ++cnt[su[tmp[i]]];
      foreach (j; 0 .. n) cnt[j + 1] += cnt[j];
      foreach_reverse (i; 0 .. n + 1) us[--cnt[su[tmp[i]]]] = tmp[i];
      foreach (i; 0 .. n) vals[i + 1] = vals[i] + ((su[us[i]] < su[us[i + 1]] || ahead(i) < ahead(i + 1)) ? 1 : 0);
    }
    lcp = new int[n];
    int h;
    foreach (u; 0 .. n) {
      for (int v = us[su[u] - 1]; cmp(u + h, v + h) == 0; ++h) {}
      lcp[su[u] - 1] = h;
      if (h > 0) --h;
    }
  }
  int cmp(int u, int v) const {
    return (u == n) ? ((v == n) ? 0 : -1) : (v == n) ? +1 : (ts[u] < ts[v]) ? -1 : (ts[u] > ts[v]) ? +1 : 0;
  }
  void print() const {
    import std.math : log10;
    import std.stdio : writefln;
    const numDigits = cast(int)(log10(n)) + 1;
    foreach (i; 0 .. n + 1) {
      writefln("%*d %s", numDigits, us[i], ts[us[i] .. $]);
    }
  }
}

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

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

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

void main() {
  prepare();

  debug {
    enum lim = 6;
    foreach (n; 1 .. lim + 1) {
      int[] ts;
      auto perm = iota(n).array;
      do {
        ts ~= perm;
      } while (perm.nextPermutation);
      const sa = new SuffixArray!int(ts);
      long ans;
      foreach (i; 0 .. sa.n) {
        ans += (sa.n - sa.us[i + 1] - sa.lcp[i]);
      }
      // writeln(sa.lcp);
      writeln(sa.lcp.dup.sort.group.map!"a[1]");
      writeln(sa.lcp.sum);
      writeln(ans);
      stdout.flush;
    }
    // return;
  }

  try {
    for (; ; ) {
      const N = readInt();
      Mint ans;
      if (N == 1) {
        ans = 1;
      } else if (N == 2) {
        ans = 8;
      } else {
        /*
          n = 3: [3, 5, 6, 3, 1];
        */
        Mint small = 6, smallSum = 2 * 6;
        Mint large = 0, largeSum = 0;
        foreach (n; 4 .. N + 1) {
          // (n - 1, 1)
          const head = Mint(n - 2)^^2 + 1;
          // (n - 1, n)
          Mint mid = Mint(n - 1) * fac[n - 1];
          mid -= Mint(n - 1);
          mid -= head;
          mid -= small;
          mid -= (fac[n - 1] - Mint(n - 1));
          mid -= large;
          debug {
            writefln("n = %s: head = %s, mid = %s", n, head, mid);
          }
          smallSum += 1 * small;
          smallSum += 2 * head;
          smallSum *= Mint(n);
          small += head;
          small *= Mint(n);
          largeSum += 2 * large;
          largeSum += Mint(n + 2) * mid;
          largeSum *= Mint(n);
          large += mid;
          large *= Mint(n);
          debug {
            writefln("n = %s: small = %s, smallSum = %s", n, small, smallSum);
            writefln("n = %s: large = %s, largeSum = %s", n, large, largeSum);
          }
        }
        {
          // (N, 1)
          const head = Mint(N - 1)^^2 + 1;
          // (N, N + 1)
          Mint mid = Mint(N) * fac[N];
          mid -= Mint(N);
          mid -= head;
          mid -= small;
          mid -= (fac[N] - Mint(N));
          mid -= large;
          debug {
            writefln("N: head = %s, mid = %s", head, mid);
          }
          Mint sum;
          sum += 0 * Mint(N);
          sum += 1 * head;
          sum += smallSum;
          sum += Mint(N) * (fac[N] - Mint(N));
          sum += Mint(N + 1) * mid;
          sum += largeSum;
          debug {
            writefln("N: sum = %s", sum);
          }
          const l = Mint(N) * fac[N];
          ans = l * (l + 1) * Mint(2).inv - sum;
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


I have an undirected graph consisting of n nodes, numbered 1 through n. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself.I would like to create a new graph in such a way that:   The new graph consists of the same number of nodes and edges as the old graph.  The properties in the first paragraph still hold.  For each two nodes u and v, if there is an edge connecting them in the old graph, there is no edge connecting them in the new graph. Help me construct the new graph, or tell me if it is impossible.

The first line consists of two space-separated integers: n and m (1 ≤ m ≤ n ≤ 105), denoting the number of nodes and edges, respectively. Then m lines follow. Each of the m lines consists of two space-separated integers u and v (1 ≤ u, v ≤ n; u ≠ v), denoting an edge between nodes u and v.

If it is not possible to construct a new graph with the mentioned properties, output a single line consisting of -1. Otherwise, output exactly m lines. Each line should contain a description of edge in the same way as used in the input format.

NoteThe old graph of the first example:A possible new graph for the first example:In the second example, we cannot create any new graph.The old graph of the third example:A possible new graph for the third example:

import std.datetime;
import std.stdio;
import std.range;
import std.random;
import std.algorithm;

int main() {
    StopWatch sw;
    sw.start();
    int n, m;
    scanf("%d %d", &n, &m);
    int[][] g = new int[][](n);
    foreach (i; 0..m) {
        int a, b;
        scanf("%d %d", &a, &b); a--; b--;
        g[a] ~= b;
        g[b] ~= a;
    }
    foreach (i; 0..n) {
        sort(g[i]);
    }
    auto a = iota(n).array;
    auto rnd = Random(unpredictableSeed);
    while (true) {
        randomShuffle(a, rnd);
        int c = 0;
        foreach (i; 0..n) {
            int l = a[i], r = a[(i+1)%n];
            if (!assumeSorted(g[l]).canFind(r)) {
                c++;
            }
        }
        if (c >= m) {
            c = 0;
            foreach (i; 0..n) {
                int l = a[i], r = a[(i+1)%n];
                if (!assumeSorted(g[l]).canFind(r)) {
                    writef("%d %d\n", l+1, r+1);
                    c++;
                    if (c == m) break;
                }
            }
            return 0;
        }
        if (sw.peek().msecs > 1000) {
            break;
        }
    }
    writeln("-1");
    return 0;
}

import std.datetime;
import std.stdio;
import std.range;
import std.random;
import std.algorithm;

int main() {
    StopWatch sw;
    sw.start();
    int n, m;
    scanf("%d %d", &n, &m);
    int[][] g = new int[][](n);
    foreach (i; 0..m) {
        int a, b;
        scanf("%d %d", &a, &b); a--; b--;
        g[a] ~= b;
        g[b] ~= a;
    }
    foreach (i; 0..n) {
        sort(g[i]);
    }
    auto a = iota(n).array;
    auto rnd = Random(unpredictableSeed);
    while (true) {
        randomShuffle(a, rnd);
        int c = 0;
        foreach (i; 0..n) {
            int l = a[i], r = a[(i+1)%n];
            if (!assumeSorted(g[l]).canFind(r)) {
                c++;
            }
        }
        if (c >= m) {
            foreach (i; 0..n) {
                int l = a[i], r = a[(i+1)%n];
                if (!assumeSorted(g[l]).canFind(r)) {
                    writef("%d %d\n", l+1, r+1);
                    c--;
                    if (!c) break;
                }
            }
            return 0;
        }
        if (sw.peek().msecs > 1000) {
            break;
        }
    }
    writeln("-1");
    return 0;
}


Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handkerchief pattern should look like that:           0        0 1 0      0 1 2 1 0    0 1 2 3 2 1 0  0 1 2 3 4 3 2 1 00 1 2 3 4 5 4 3 2 1 0  0 1 2 3 4 3 2 1 0    0 1 2 3 2 1 0      0 1 2 1 0        0 1 0          0Your task is to determine the way the handkerchief will look like by the given n.

The first line contains the single integer n (2 ≤ n ≤ 9).

Print a picture for the given n. You should strictly observe the number of spaces before the first digit on each line. Every two adjacent digits in the same line should be separated by exactly one space. There should be no spaces after the last digit at the end of each line.

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

// main===================
void main(){
  auto n = readln.chomp.to!int;
  int[] base;
  foreach(i; 0..n+1){base ~= i;}
  foreach_reverse(i; 0..n){base ~= i;}

  int[][] all;
  foreach_reverse(i; 0..n+1){ all ~= base.map!(e => e-i).array;}
  foreach(i; 0..n){ all ~= base.map!(e => e-i-1).array;}

  foreach(i, l; all){
    string line;
    foreach(e; l){
      line ~= e>=0 ? "%d ".format(e) : "  ";
    }
    writeln(line.stripRight);
  }
}

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

// main===================
void main(){
  auto n = readln.chomp.to!int;
  int[] base;
  foreach(i; 0..n+1){base ~= i;}
  foreach_reverse(i; 0..n){base ~= i;}

  int[][] all;
  foreach_reverse(i; 0..n+1){ all ~= base.map!(e => e-i).array;}
  foreach(i; 0..n){ all ~= base.map!(e => e-i-1).array;}

  foreach(l; all){
    foreach(e; l){
      write(e>=0 ? "%d ".format(e) : "  ");
    }
    writeln;
  }
}

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

// main===================
void main(){
  auto n = readln.chomp.to!int;
  int[] base;
  foreach(i; 0..n+1){base ~= i;}
  foreach_reverse(i; 0..n){base ~= i;}

  int[][] all;
  foreach_reverse(i; 0..n+1){ all ~= base.map!(e => e-i).array;}
  foreach(i; 0..n){ all ~= base.map!(e => e-i-1).array;}

  foreach(l; all){
    foreach(e; l){
      write(e>=0 ? e.to!string: " ");
    }
    writeln;
  }
}

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

// main===================
void main(){
  auto n = readln.chomp.to!int;
  int[] base;
  foreach(i; 0..n+1){base ~= i;}
  foreach_reverse(i; 0..n){base ~= i;}

  int[][] all;
  foreach_reverse(i; 0..n+1){ all ~= base.map!(e => e-i).array;}
  foreach(i; 0..n){ all ~= base.map!(e => e-i-1).array;}

  foreach(l; all){
    char[] line;
    foreach(e; l){
      line ~= e>=0 ? "%d ".format(e) : "  ";
    }
    writeln(line.chomp);
  }
}

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

// main===================
void main(){
  auto n = readln.chomp.to!int;
  int[] base;
  foreach(i; 0..n+1){base ~= i;}
  foreach_reverse(i; 0..n){base ~= i;}

  int[][] all;
  foreach_reverse(i; 0..n+1){ all ~= base.map!(e => e-i).array;}
  foreach(i; 0..n){ all ~= base.map!(e => e-i-1).array;}

  foreach(l; all){
    char[] line;
    foreach(e; l){
      line ~= e>=0 ? "%d ".format(e) : "  ";
    }
    writeln(line.to!string.chomp);
  }
}


You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?

The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.

If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.

4
2
caa
cbb
3
cba
cba
cbb
4
ccab
cbac
bca
acbcc
4
acb
caf
c
cbafc

NoteIn the first test case, you can do the following:   Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.

import std.stdio;
import std.string;

T read(T)()
{
    T t;
    readf(" %s", &t);
    return t;
}

int main(string[] args)
{
    int T = read!int;

    foreach (t; 0..T)
    {
	int n = read!int;
	readln;
	int[char] inc;
	//string[] arr;
	foreach (i; 0..n)
	{
	    auto s = readln.strip;
	    foreach (c; s)
	    {
		int *p = c in inc;
		if (p !is null)
		    inc[c]++;
		else
		    inc[c] = 1;
	    }
	}

	bool success = true;
	foreach (i, k; inc)
	{
	    if (k % n != 0)
	    {
		success = false;
		writeln("NO");
		break;
	    }
	}
	if (success)
	    writeln("YES");
	//writeln (inc);
    }

    return 0;
}

// Vicfred
// https://codeforces.com/contest/1397/problem/A
// simulation, math
import std.conv;
import std.stdio;
import std.string;

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

    while(t--) {
        long[char] counter;

        long n = readln.chomp.to!long;
        string[] s;
        foreach(_; 0..n)
            s ~= readln.strip;
        foreach(str; s) {
            foreach(ch; str) {
                if(ch in counter)
                    counter[ch] += 1;
                else
                    counter[ch] = 1;
            }
        }

        string ans = "YES";
        foreach(value; counter.values) {
            if(value%n != 0) {
                ans = "NO";
                break;
            }
        }
        ans.writeln;
    }

}

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);
		int [char] d;
		foreach (i; 0..n)
		{
			foreach (char c; readln.strip)
			{
				d[c] += 1;
			}
		}
		writeln (d.byValue.all !(x => x % n == 0) ? "YES" : "NO");
	}
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto nt = next!int;
  foreach(t; 0 .. nt)
    {
      auto n = next!int;
      auto ss = next!string(n);
      int[char] cnt;
      foreach(s; ss)
        foreach(c; s)
          cnt.require(c, 0)++;
      if (cnt.byValue.all!(c => c % n == 0))
        writeln("YES");
      else
        writeln("NO");
    }
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byChunk;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 4096;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;

const KB = 1024;
const MB = 1024 * 1024;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto nt = next!int;
  foreach(t; 0 .. nt)
    {
      auto n = next!int;
      auto ss = next!string(n);
      int[char] cnt;
      foreach(s; ss)
        foreach(c; s)
          cnt.require(c, 0)++;
      if (cnt.byValue.all!(c => c % n == 0))
        writeln("YES");
      else
        writeln("NO");
    }
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byChunk;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = MB;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto cnt = new long[](26);
		foreach (i; 0..n)
		{
			auto s = RD!string;
			foreach (c; s)
			{
				auto num = c - 'a';
				++cnt[num];
			}
		}

		ans[ti] = true;
		foreach (i; 0..26)
		{
			if (cnt[i] % n)
			{
				ans[ti] = false;
				break;
			}
		}
	}

	foreach (e; ans)
		writeln(e ? "YES" : "NO");
	stdout.flush;
	debug readln;
}


You're given an integer $$$n$$$. For every integer $$$i$$$ from $$$2$$$ to $$$n$$$, assign a positive integer $$$a_i$$$ such that the following conditions hold:  For any pair of integers $$$(i,j)$$$, if $$$i$$$ and $$$j$$$ are coprime, $$$a_i \neq a_j$$$.  The maximal value of all $$$a_i$$$ should be minimized (that is, as small as possible). A pair of integers is called coprime if their greatest common divisor is $$$1$$$.

The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$).

Print $$$n-1$$$ integers, $$$a_2$$$, $$$a_3$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \leq a_i \leq n$$$).  If there are multiple solutions, print any of them.

NoteIn the first example, notice that $$$3$$$ and $$$4$$$ are coprime, so $$$a_3 \neq a_4$$$. Also, notice that $$$a=[1,2,3]$$$ satisfies the first condition, but it's not a correct answer because its maximal value is $$$3$$$.

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

immutable long MOD = 10^^9 + 7;
immutable long INF = 1L << 59;

void main() {
    auto N = readln.chomp.to!int;
    auto ans = new int[](N+1);

    int tmp = 1;
    foreach (i; 2..N+1) {
        if (ans[i] != 0) continue;
        for (int j = i; j <= N; j += i) {
            ans[j] = tmp;
        }
        tmp += 1;
    }

    ans[2..$].map!(to!string).join(" ").writeln;
}

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

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

    auto ans = new int[] (n+1);
    int cnt = 1;
    for (int i = 2; i <= n; ++i) {
        bool made = false;
        for (int j = i; j <= n; j += i) {
            if (ans[j] == 0) {
                ans[j] = cnt;
                made = true;
            }
        }

        if (made) { cnt += 1; }
    }

    ans[2 .. n+1].writefln!"%(%s %)";
}

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

int[] sieveArray (int n) {
  auto a = iota (0, n + 1).map! (i => (i & 1) ? i : 2).array;
  for (int p = 3; p * p <= n; p += 2) {
    if (a[p] == p) {
      foreach (o; iota (p * p, n + 1, 2 * p)) {
        if (a[o] == o) {
          a[o] = p;
        }
      }
    }
  }
  return a;
}

void main() {
  int n;
  readf (" %d", &n);
  auto s = sieveArray (n);
  int[int] h = [ 2 : 1 ];
  int idx = 1;
  foreach (i; iota (3, n + 1, 2)) {
    if (s[i] == i) {
      h[i] = ++idx;
    }
  }
  foreach (i; 2 .. n + 1) {
    s[i] = h[s[i]];
  }
  writefln ("%(%s %)", s[2 .. $]);
}

//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.bitmanip;

class PrimeTable {
  private:
  BitArray a;
  size_t n;
  public:
  bool isPrime (size_t i) const pure nothrow @nogc {
    return (i & 1) ? !a[i>>>1] : (i == 2);
  }
  int[] primes () const pure {
    int[] p;
    if (n > 2) {
      p ~= 2;
      p ~= (~a).bitsSet.map! (i => (2 * i + 1).to!int).array;
    }
    return p;
  }
  this (size_t _n) pure {
    n = _n;
    auto m = n >> 1;
    a.length = max (1, m);
    a[0] = true;
    foreach (i; 1 .. ceil((sqrt (n.to!(double)) - 1.0)).to!(size_t)) {
      if (!a[i]) {
        immutable k = (i << 1) + 1;
        for (size_t j = 2 * i * (i + 1); j < m; j += k) {
          a[j] = true;
        }
      }
    }
  }
}

void main() {
  int n;
  readf (" %d", &n);
  auto pt = new PrimeTable (n + 16);
  auto a = new int[n+1];
  int[] q;
  foreach (i; 2 .. n + 1) {
    if (pt.isPrime(i)) {
      q ~= i;
      a[i] = q.length.to!int;
    } else {
      foreach (k, j; q) {
        if ((i % j) == 0) {
          a[i] = k.to!int + 1;
          break;
        }
      }
    }
  }
  writefln ("%(%s %)", a[2 .. $]);
}

import std.typecons;
import core.stdc.stdio;
import std.stdio;
import std.algorithm;
import std.range;

alias PII = Tuple!(int, int);
alias PLL = Tuple!(long, long);

void main()
{
    uint n;
    scanf("%d", &n);

    bool[] primes = new bool[n + 1];
    int[] ans = new int[n + 1];
    fill(primes, true);

    int c = 0;

    foreach (i; 2 .. n + 1)
        if (primes[i])
        {
            c++;
            ans[i] = c;
            for (auto j = i * i; j <= n; j += i)
            {
                primes[j] = false;
                ans[j] = c;
            }
        }

    writefln("%(%d%| %)", ans[2 .. n + 1]);
}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto N = RD!int;
	auto A = new long[](N-1);
	long num = 1;
	foreach (i; 2..N+1)
	{
		if (A[i-2] != 0) continue;

		for (int j = i; j <= N; j += i)
		{
			A[j-2] = num;
		}
		++num;
	}

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


Nastya baked $$$m$$$ pancakes and spread them on $$$n$$$ dishes. The dishes are in a row and numbered from left to right. She put $$$a_i$$$ pancakes on the dish with the index $$$i$$$.Seeing the dishes, Vlad decided to bring order to the stacks and move some pancakes. In one move, he can shift one pancake from any dish to the closest one, that is, select the dish $$$i$$$ ($$$a_i > 0$$$) and do one of the following: if $$$i > 1$$$, put the pancake on a dish with the previous index, after this move $$$a_i = a_i - 1$$$ and $$$a_{i - 1} = a_{i - 1} + 1$$$; if $$$i < n$$$, put the pancake on a dish with the following index, after this move $$$a_i = a_i - 1$$$ and $$$a_{i + 1} = a_{i + 1} + 1$$$.Vlad wants to make the array $$$a$$$non-increasing, after moving as few pancakes as possible. Help him find the minimum number of moves needed for this.The array $$$a=[a_1, a_2,\dots,a_n]$$$ is called non-increasing if $$$a_i \ge a_{i+1}$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$.

The first line of the input contains two numbers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 250$$$) — the number of dishes and the number of pancakes, respectively. The second line contains $$$n$$$ numbers $$$a_i$$$ ($$$0 \le a_i \le m$$$), the sum of all $$$a_i$$$ is equal to $$$m$$$.

Print a single number: the minimum number of moves required to make the array $$$a$$$ non-increasing.

NoteIn the first example, you first need to move the pancake from the dish $$$1$$$, after which $$$a = [4, 4, 2, 3, 3, 3]$$$. After that, you need to move the pancake from the dish $$$2$$$ to the dish $$$3$$$ and the array will become non-growing $$$a = [4, 3, 3, 3, 3, 3]$$$.

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

immutable int infinity = 10 ^^ 9;

int [] [] go (int [] [] f, int pos, int [] a, int n, int m, int [] s)
{
	int limitPrev = m / (pos + !pos) + 1;
	int nextPos = pos + 1;
	int limitNext = m / nextPos + 1;
	auto g = new int [] [] (m + 1, limitNext + 2);
	foreach (ref line; g)
	{
		line[] = infinity;
	}
	foreach (total; 0..m + 1)
	{
		foreach (prev; 0..limitPrev + 1)
		{
			int cur = f[total][prev];
			if (cur >= infinity)
			{
				continue;
			}
			int limit = min (prev, limitNext, m - total);
			foreach (next; 0..limit + 1)
			{
				int value = abs (s[pos] - total);
				value += cur;
				g[total + next][next] = min
				    (g[total + next][next], value);
			}
		}
	}
	return g;
}

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		n += 1;
		a ~= 0;
		auto s = [0];
		foreach (ref c; a)
		{
			s ~= s.back + c;
		}
		auto f = new int [] [] (m + 1, m + 2);
		foreach (ref line; f)
		{
			line[] = infinity;
		}
		f[0][m] = 0;
		for (int pos = 0; pos < n; pos++)
		{
			f = go (f, pos, a, n, m, s);
		}
		writeln (f[m][0]);
	}
}


There is a matrix A of size x × y filled with integers. For every ,  Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i < x;  (i, j + 1) — only if j < y;  (i - 1, j) — only if i > 1;  (i, j - 1) — only if j > 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?

The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.

If all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO. Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.

NoteThe matrix and the path on it in the first test looks like this:  Also there exist multiple correct answers for both the first and the third examples.

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	readln;

	auto arr = readln.strip.splitter.map!(to!int).array;
	auto pairs = zip(arr, arr[1..$]);

	auto y = pairs.map!(a => abs(a[0] - a[1])).filter!(a => a && a != 1).chain([ 1 ]).front;

	foreach(u, v; pairs)
	{
		auto d = abs(u - v);

		if(d != y && (d != 1 || min(u, v) % y == 0))
		{
			`NO`.writeln;
			return;
		}
	}

	writefln("YES\n%u %u", 10 ^^ 9, y);
}

import core.stdc.math;
import core.stdc.stdio;
import core.stdc.stdlib;
import std.algorithm;
int n,y=1;
int[200005] a;
void main()
{
	scanf("%d",&n);
	for (int i=1;i<=n;++i) scanf("%d",&a[i]);
	for (int i=2;i<=n;++i) y=max(y,abs(a[i]-a[i-1]));
	for (int i=2;i<=n;++i)
	{
		if (y!=1 && (a[i-1]+1==a[i] || a[i-1]-1==a[i]))
		{
			if ((a[i-1]-1)/y!=(a[i]-1)/y)
			{
				puts("NO");
				exit(0);
			}
		}
		else if (a[i-1]+y!=a[i] && a[i-1]-y!=a[i])
		{
			puts("NO");
			exit(0);
		}
	}
	printf("YES\n1000000000 %d\n",y);
}

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

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///int length
		int sz(T)(ref const T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int n;
	read(n);
	auto a = arread!int;
	if (n == 1)
	{
		return writefln("YES\n%d %d", 1, a[0]);
	}
	int d = abs(a[0] - a[1]);
	foreach (i; 1 .. n - 1)
	{
		if (d == 1)
			d = abs(a[i] - a[i + 1]);
		else if (abs(a[i] - a[i + 1]) != 1)
		{
			if (d != abs(a[i] - a[i + 1]))
				return writeln("NO");
		}
	}
	if (d == 0)
		return writeln("NO");
	if (d == 1)
		return writefln("YES\n%d %d", 10 ^^ 9, 10 ^^ 9);
	int y = d, x = 10 ^^ 9;
	int x0 = (a[0] + d - 1) / d, y0 = a[0] - d * (x0 - 1);
	foreach (i; 1 .. n)
	{
		auto t = a[i] - a[i - 1];
		if (abs(t) > 1)
		{
			x0 += (t < 0 ? -1 : 1);
		}
		else
		{
			y0 += (t < 0 ? -1 : 1);
		}
		if (x0 < 1 || x0 > x || y0 < 1 || y0 > y)
			return writeln("NO");
	}
	writefln("YES\n%d %d", x, y);
}

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	readln;

	int x, p, m;

	foreach(i, n; readln.strip.splitter.map!(to!int).enumerate)
	{
		if(i)
		{
			auto d = abs(n - p);

			if(!d)
			{
				`NO`.writeln;
				return;
			}

			if(d > 1)
			{
				if(x)
				{
					if(d != x)
					{
						`NO`.writeln;
						return;
					}
				}
				else
				{
					x = d;
				}
			}
		}

		if(m < n)
		{
			m = n;
		}

		p = n;
	}

	if(!x)
	{
		x = m;
	}

	writefln("YES\n%u %u", 1 + m / x, x);
}

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	readln;

	int x, p, m;

	foreach(i, n; readln.strip.splitter.map!(to!int).enumerate)
	{
		if(i)
		{
			auto d = abs(n - p);

			if(d > 1)
			{
				if(x)
				{
					if(d != x)
					{
						`NO`.writeln;
						return;
					}
				}
				else
				{
					x = d;
				}
			}
		}

		if(m < n)
		{
			m = n;
		}

		p = n;
	}

	writefln("YES\n%u %u", m / x, x);
}

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	readln;

	auto arr = readln.strip.splitter.map!(to!int).array;
	auto pairs = zip(arr, arr[1..$]);

	auto y = pairs.map!(a => abs(a[0] - a[1])).filter!(a => a != 1).chain([ 1 ]).front;

	foreach(u, v; pairs)
	{
		auto d = abs(u - v);

		if(d != y || d != 1 || min(u, v) % y == 0)
		{
			`NO`.writeln;
			return;
		}
	}

	writefln("YES\n%u %u", 10 ^^ 9, y);
}

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

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///int length
		int sz(T)(ref const T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int n;
	read(n);
	auto a = arread!int;
	if (n == 1)
	{
		return writefln("YES\n%d %d", 1, a[0]);
	}
	int d = abs(a[0] - a[1]);
	foreach (i; 1 .. n - 1)
	{
		if (d == 1)
			d = abs(a[i] - a[i + 1]);
		else if (abs(a[i] - a[i + 1]) != 1)
		{
			if (d != abs(a[i] - a[i + 1]))
				return writeln("NO");
		}
	}
	if (d == 0)
		return writeln("NO");
	if (d == 1)
		return writefln("YES\n%d %d", 10 ^^ 9, 10 ^^ 9);
	int y = d, x = 10 ^^ 9;
	int x0 = (a[0] + d - 1) / d, y0 = a[0] - d * (x0 - 1);
	foreach (i; 1 .. n)
	{
		auto t = a[i] - a[i - 1];
		if (abs(t) > 1)
		{
			x0 += (t < 0 ? -1 : 1);
		}
		else
		{
			y0 += (t < 0 ? -1 : 1);
		}
		if (x0 < 1 || x0 > x || y0 < 1 || y0 > y)
			return writeln("NO");
	}
	writefln("YES\n%d %d", y, x);
}

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

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///int length
		int sz(T)(ref const T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int n;
	read(n);
	auto a = arread!int;
	if (n == 1)
	{
		return writefln("YES\n%d %d", 1, a[0]);
	}
	int d = abs(a[0] - a[1]);
	foreach (i; 1 .. n - 1)
	{
		if (d == 1)
			d = abs(a[i] - a[i + 1]);
		else if (abs(a[i] - a[i + 1]) != 1)
		{
			if (d != abs(a[i] - a[i + 1]))
				return writeln("NO");
		}
	}
	if (d == 0)
		return writeln("NO");
	if (d == 1)
		return writefln("YES\n%d %d", 10 ^^ 9, 10 ^^ 9);
	int x = d, y = 10 ^^ 9;
	int x0 = (a[0] + d - 1) / d, y0 = a[0] - d * (x0 - 1);
	foreach (i; 1 .. n)
	{
		auto t = a[i] - a[i - 1];
		if (abs(t) > 1)
		{
			y0 += (t < 0 ? -1 : 1);
		}
		else
		{
			x0 += (t < 0 ? -1 : 1);
		}
		if (x0 < 1 || x0 > x || y0 < 1 || y0 > y)
			return writeln("No");
	}
	writefln("YES\n%d %d", y, x);
}

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

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///int length
		int sz(T)(ref const T a) if (hasLength!T)
		{
			return cast(int) a.length;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int n;
	read(n);
	auto a = arread!int;
	if (n == 1)
	{
		return writefln("YES\n%d %d", 1, a[0]);
	}
	int d = abs(a[0] - a[1]);
	foreach (i; 1 .. n - 1)
	{
		if (d == 1)
			d = abs(a[i] - a[i + 1]);
		else if (abs(a[i] - a[i + 1]) != 1)
		{
			if (d != abs(a[i] - a[i + 1]))
				return writeln("NO");
		}
	}
	if (d == 0)
		return writeln("NO");
	if (d == 1)
		return writefln("YES\n%d %d", 10 ^^ 9, 10 ^^ 9);
	int x = d, y = 10 ^^ 9;
	int x0 = (a[0] + d - 1) / d, y0 = a[0] - d * (x0 - 1);
	foreach (i; 1 .. n)
	{
		auto t = a[i] - a[i - 1];
		if (abs(t) > 1)
		{
			y0 += (t < 0 ? -1 : 1);
		}
		else
		{
			x0 += (t < 0 ? -1 : 1);
		}
		if (x0 < 1 || x0 > x || y0 < 1 || y0 > y)
			return writeln("NO");
	}
	writefln("YES\n%d %d", y, x);
}


The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.

The first input line contains an integer n (2 ≤ n ≤ 100). The second line contains n - 1 integers di (1 ≤ di ≤ 100). The third input line contains two integers a and b (1 ≤ a < b ≤ n). The numbers on the lines are space-separated.

Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.

import std.c.stdio;

void main() {
  int n; scanf("%d", &n);
  int[] d = new int[n];
  int a, b;
  for (int i = 0; i < n - 1; i++) {
    scanf("%d", &d[i]);
  }
  scanf("%d %d", &a, &b);
  int x = 0;
  for (int i = a; i < b; i++) {
    x += d[i - 1];
  }
  printf("%d\n", x);
}

module _38a;

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

int main()
{
	auto n = 0;
	readf!"%d"(n);
	readln();
	auto d = new int[n-1];
	for (auto i = 0; i < (n-1); i++) {
		scanf("%d", &d[i]);
	}
	readln();

	auto from_lv =0 , to_lv=0;
	readf!"%d %d"(from_lv, to_lv);
	readln();

	auto spent_years = 0;
	for (auto i = from_lv; i < to_lv; i++) {
		spent_years += d[i-1];
	}

	writefln("%d", spent_years);
    return 0;
}

import std.stdio;

void assert_solve(int r,int[] ds, int a, int b){
  int sol = solve(ds,a,b);
  if (sol != r){
    writefln("Test %s-(%s,%s): Expected %s, got %s",ds,a,b,r,sol);
    assert(false);
  }
}

unittest{
  assert_solve(5,[0,5,6],1,2);
  assert_solve(11,[0,5,6],1,3);
}

int solve(int[] ds,int a,int b){
  ds[0] = 0;
  for(int i = 1; i < ds.length; i++){
    ds[i] += ds[i-1];
  }
  return ds[b-1] - ds[a-1];
}

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

  int[] ds = new int[n];
  for(int i = 1; i < n; i++){
    readf("%s ",ds.ptr+i);
  }

  int a,b;
  readf("%s %s\n",&a,&b);

  writeln(solve(ds,a,b));
}


Sereja has m non-empty sets of integers A1, A2, ..., Am. What a lucky coincidence! The given sets are a partition of the set of all integers from 1 to n. In other words, for any integer v (1 ≤ v ≤ n) there is exactly one set At such that . Also Sereja has integer d.Sereja decided to choose some sets from the sets he has. Let's suppose that i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ m) are indexes of the chosen sets. Then let's define an array of integers b, sorted in ascending order, as a union of the chosen sets, that is, . We'll represent the element with number j in this array (in ascending order) as bj. Sereja considers his choice of sets correct, if the following conditions are met:b1 ≤ d; bi + 1 - bi ≤ d (1 ≤ i < |b|); n - d + 1 ≤ b|b|.Sereja wants to know what is the minimum number of sets (k) that he can choose so that his choice will be correct. Help him with that.

The first line contains integers n, m, d (1 ≤ d ≤ n ≤ 105, 1 ≤ m ≤ 20). The next m lines contain sets. The first number in the i-th line is si (1 ≤ si ≤ n). This number denotes the size of the i-th set. Then the line contains si distinct integers from 1 to n — set Ai. It is guaranteed that the sets form partition of all integers from 1 to n.

In a single line print the answer to the problem — the minimum value k at the right choice.

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, m, d;
	while (readf (" %s %s %s", &n, &m, &d) > 0)
	{
		auto a = new int [n];
		a[] = -1;
		foreach (i; 0..m)
		{
			int len;
			readf (" %s", &len);
			foreach (j; 0..len)
			{
				int x;
				readf (" %s", &x);
				x--;
				enforce (a[x] == -1);
				a[x] = i;
			}
		}
		foreach (i; 0..n)
		{
			enforce (a[i] != -1);
		}

		int m2 = 1 << m;
		auto v = new bool [m2];
		v[] = false;
		auto c = new int [m];
		c[] = 0;
		int mask = 0;
		foreach (i; 0..n)
		{
			int cur = a[i];
			if (c[cur] == 0)
			{
				mask |= 1 << cur;
			}
			c[cur]++;
			if (i >= d)
			{
				int prev = a[i - d];
				c[prev]--;
				if (c[prev] == 0)
				{
					mask &= ~(1 << prev);
				}
			}
			if (i >= d - 1)
			{
				v[m2 - 1 - mask] = true;
			}
		}

		foreach_reverse (s; 0..m2)
		{
			foreach (i; 0..m)
			{
				if (s & (1 << i))
				{
					debug {writeln (s, " ", i, " ",
					                s ^ (1 << i));}
					v[s ^ (1 << i)] |= v[s];
				}
			}
		}

		long res = m;
		foreach (s; 0..m2)
		{
			if (!v[s])
			{
				res = min (res, popcnt (s));
			}
		}
		writeln (res);
	}
}

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

void main ()
{
	int n, m, d;
	while (readf (" %s %s %s", &n, &m, &d) > 0)
	{
		auto a = new int [n];
		a[] = -1;
		foreach (i; 0..m)
		{
			int len;
			readf (" %s", &len);
			foreach (j; 0..len)
			{
				int x;
				readf (" %s", &x);
				x--;
				a[x] = i;
			}
		}
		foreach (i; 0..n)
		{
			assert (a[i] != -1);
		}

		int m2 = 1 << m;
		auto v = new bool [m2];
		v[] = false;
		auto c = new int [m];
		c[] = 0;
		int mask = 0;
		foreach (i; 0..n)
		{
			int cur = a[i];
			if (c[cur] == 0)
			{
				mask |= 1 << cur;
			}
			c[cur]++;
			if (i >= d)
			{
				int prev = a[i - d];
				c[prev]--;
				if (c[prev] == 0)
				{
					mask &= ~(1 << prev);
				}
			}
			v[m2 - 1 - mask] = true;
		}

		foreach_reverse (s; 0..m2)
		{
			foreach (i; 0..m)
			{
				if (s & (1 << i))
				{
					debug {writeln (s, " ", i, " ",
					                s ^ (1 << i));}
					v[s ^ (1 << i)] |= v[s];
				}
			}
		}

		long res = m;
		foreach (s; 0..m2)
		{
			if (!v[s])
			{
				res = min (res, popcnt (s));
			}
		}
		writeln (res);
	}
}

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

void main ()
{
	int n, m, d;
	while (readf (" %s %s %s", &n, &m, &d) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..m)
		{
			int len;
			readf (" %s", &len);
			foreach (j; 0..len)
			{
				int x;
				readf (" %s", &x);
				x--;
				a[x] = i;
			}
		}

		int m2 = 1 << m;
		auto v = new bool [m2];
		v[] = false;
		auto c = new int [m];
		c[] = 0;
		int mask = 0;
		foreach (i; 0..n)
		{
			int cur = a[i];
			if (c[cur] == 0)
			{
				mask |= 1 << cur;
			}
			c[cur]++;
			if (i >= d)
			{
				int prev = a[i - d];
				c[prev]--;
				if (c[prev] == 0)
				{
					mask &= ~(1 << prev);
				}
			}
			v[m2 - 1 - mask] = true;
		}

		foreach_reverse (s; 0..m2)
		{
			foreach (i; 0..m)
			{
				if (s & (1 << i))
				{
					debug {writeln (s, " ", i, " ",
					                s ^ (1 << i));}
					v[s ^ (1 << i)] |= v[s];
				}
			}
		}

		long res = m;
		foreach (s; 0..m2)
		{
			if (!v[s])
			{
				res = min (res, popcnt (s));
			}
		}
		writeln (res);
	}
}

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

void main ()
{
	int n, m, d;
	while (readf (" %s %s %s", &n, &m, &d) > 0)
	{
		auto a = new int [n];
		a[] = -1;
		foreach (i; 0..m)
		{
			int len;
			readf (" %s", &len);
			foreach (j; 0..len)
			{
				int x;
				readf (" %s", &x);
				x--;
				enforce (a[x] == -1);
				a[x] = i;
			}
		}
		foreach (i; 0..n)
		{
			enforce (a[i] != -1);
		}

		int m2 = 1 << m;
		auto v = new bool [m2];
		v[] = false;
		auto c = new int [m];
		c[] = 0;
		int mask = 0;
		foreach (i; 0..n)
		{
			int cur = a[i];
			if (c[cur] == 0)
			{
				mask |= 1 << cur;
			}
			c[cur]++;
			if (i >= d)
			{
				int prev = a[i - d];
				c[prev]--;
				if (c[prev] == 0)
				{
					mask &= ~(1 << prev);
				}
			}
			v[m2 - 1 - mask] = true;
		}

		foreach_reverse (s; 0..m2)
		{
			foreach (i; 0..m)
			{
				if (s & (1 << i))
				{
					debug {writeln (s, " ", i, " ",
					                s ^ (1 << i));}
					v[s ^ (1 << i)] |= v[s];
				}
			}
		}

		long res = m;
		foreach (s; 0..m2)
		{
			if (!v[s])
			{
				res = min (res, popcnt (s));
			}
		}
		writeln (res);
	}
}

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

void main ()
{
	int n, m, d;
	while (readf (" %s %s %s", &n, &m, &d) > 0)
	{
		auto a = new int [n];
		a[] = -1;
		foreach (i; 0..m)
		{
			int len;
			readf (" %s", &len);
			foreach (j; 0..len)
			{
				int x;
				readf (" %s", &x);
				x--;
				assert (a[x] == -1);
				a[x] = i;
			}
		}
		foreach (i; 0..n)
		{
			assert (a[i] != -1);
		}

		int m2 = 1 << m;
		auto v = new bool [m2];
		v[] = false;
		auto c = new int [m];
		c[] = 0;
		int mask = 0;
		foreach (i; 0..n)
		{
			int cur = a[i];
			if (c[cur] == 0)
			{
				mask |= 1 << cur;
			}
			c[cur]++;
			if (i >= d)
			{
				int prev = a[i - d];
				c[prev]--;
				if (c[prev] == 0)
				{
					mask &= ~(1 << prev);
				}
			}
			v[m2 - 1 - mask] = true;
		}

		foreach_reverse (s; 0..m2)
		{
			foreach (i; 0..m)
			{
				if (s & (1 << i))
				{
					debug {writeln (s, " ", i, " ",
					                s ^ (1 << i));}
					v[s ^ (1 << i)] |= v[s];
				}
			}
		}

		long res = m;
		foreach (s; 0..m2)
		{
			if (!v[s])
			{
				res = min (res, popcnt (s));
			}
		}
		writeln (res);
	}
}


You are given a prime number $$$n$$$, and an array of $$$n$$$ integers $$$b_1,b_2,\ldots, b_n$$$, where $$$0 \leq b_i < n$$$ for each $$$1 \le i \leq n$$$.You have to find a matrix $$$a$$$ of size $$$n \times n$$$ such that all of the following requirements hold:  $$$0 \le a_{i,j} < n$$$ for all $$$1 \le i, j \le n$$$.  $$$a_{r_1, c_1} + a_{r_2, c_2} \not\equiv a_{r_1, c_2} + a_{r_2, c_1} \pmod n$$$ for all positive integers $$$r_1$$$, $$$r_2$$$, $$$c_1$$$, and $$$c_2$$$ such that $$$1 \le r_1 < r_2 \le n$$$ and $$$1 \le c_1 < c_2 \le n$$$. $$$a_{i,i} = b_i$$$ for all $$$1 \le i \leq n$$$. Here $$$x \not \equiv y \pmod m$$$ denotes that $$$x$$$ and $$$y$$$ give different remainders when divided by $$$m$$$.If there are multiple solutions, output any. It can be shown that such a matrix always exists under the given constraints.

The first line contains a single positive integer $$$n$$$ ($$$2 \le n < 350$$$).  The second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i < n$$$) — the required values on the main diagonal of the matrix. It is guaranteed that $$$n$$$ is prime.

Print $$$n$$$ lines. On the $$$i$$$-th line, print $$$n$$$ integers $$$a_{i, 1}, a_{i, 2}, \ldots, a_{i, n}$$$, each separated with a space. If there are multiple solutions, output any.

NoteIn the first example, the answer is valid because all entries are non-negative integers less than $$$n = 2$$$, and $$$a_{1,1}+a_{2,2} \not\equiv a_{1,2}+a_{2,1} \pmod 2$$$ (because $$$a_{1,1}+a_{2,2} = 0 + 0 \equiv 0 \pmod 2$$$ and $$$a_{1,2}+a_{2,1} = 1 + 0 \equiv 1 \pmod 2 $$$). Moreover, the values on the main diagonals are equal to $$$0,0$$$ as required.In the second example, the answer is correct because all entries are non-negative integers less than $$$n = 3$$$, and the second condition is satisfied for all quadruplets $$$(r_1, r_2, c_1, c_2)$$$. For example:   When $$$r_1=1$$$, $$$r_2=2$$$, $$$c_1=1$$$ and $$$c_2=2$$$, $$$a_{1,1}+a_{2,2} \not\equiv a_{1,2}+a_{2,1} \pmod 3$$$ because $$$a_{1,1}+a_{2,2} = 1 + 1 \equiv 2 \pmod 3$$$ and $$$a_{1,2}+a_{2,1} = 2 + 1 \equiv 0 \pmod 3 $$$.  When $$$r_1=2$$$, $$$r_2=3$$$, $$$c_1=1$$$, and $$$c_2=3$$$, $$$a_{2,1}+a_{3,3} \not\equiv a_{2,3}+a_{3,1} \pmod 3$$$ because $$$a_{2,1}+a_{3,3} = 1 + 1 \equiv 2 \pmod 3$$$ and $$$a_{2,3}+a_{3,1} = 0 + 1 \equiv 1 \pmod 3 $$$.  Moreover, the values on the main diagonal are equal to $$$1,1,1$$$ as required.

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

const bool dbg = true;
void DBG(alias x)() { static if (dbg) stderr.writefln("DBG: %s = %s", x.stringof, x); }
void MSG(in string x) { static if (dbg) stderr.writefln("MSG: %s", x); }

void main() {
    int N = readln.chomp.to!int;
    auto B = readln.chomp.split(" ").map!(to!int).array;
    auto A = new int[][](N, N);
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            A[i][j] = (B[i] + (i - j) * i + N * N) % N;
        }
    }
    foreach (L; A) {
        writefln("%(%s %)", L);
    }

    /*
    bool check() {
        for (int i = 0; i < N; i++) {
            for (int j = i+1; j < N; j++) {
                for (int x = 0; x < N; x++) {
                    for (int y = x+1; y < N; y++) {
                        int a = A[i][x] + A[j][y];
                        int b = A[j][x] + A[i][y];
                        if (a % N == b % N) {
                            writeln([i, j, x, y]);
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    assert(check());
    */
}


Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?

The first input line contains integer n (1 ≤ n ≤ 105) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.

Output the amount of ways to cut the stripe into two non-empty pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string read_string() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int read_int() {
                return read_string.to!int;
        }
        double read_double() {
                return read_string.to!double;
        }
}

void main() {
        IO cin;
        int t = 1;
        // t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                int[] arr = new int[n];
                foreach (ref i; arr) i = cin.read_int;

                int[] sum_for = new int[n];
                sum_for[0] = arr[0];
                for (int i = 1; i < n; i++) {
                        sum_for[i] += arr[i] + sum_for[i - 1];
                }

                reverse(arr);

                int[] sum_back = new int[n];
                sum_back[0] = arr[0];
                for (int i = 1; i < n; i++) {
                        sum_back[i] += arr[i] + sum_back[i - 1];
                }

                int count = 0;
                for (int i = 0; i < n - 1; i++) {
                        if (sum_for[i] == sum_back[n - 2 - i])
                                count++;
                }

                writeln(count);
        }
}

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

void main()
{
    readln;
    auto ns = readln.split.map!(to!int);
    auto a = (0~ns.cumulativeFold!"a+b".array)[1..$-1];
    auto b = (ns.retro.cumulativeFold!"a+b".array.retro.array ~ 0)[1..$-1];
    writeln(a.zip(b).count!"a[0]==a[1]");
}

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

void main()
{
    readln;
    auto ns = readln.split.map!(to!int);
    auto a = chain(only(0), ns.cumulativeFold!"a+b").array.dropOne.dropBackOne;
    auto b = chain(only(0), ns.retro.cumulativeFold!"a+b").array.retro.dropOne.dropBackOne;
    writeln(a.zip(b).count!"a[0]==a[1]");
}

import std.algorithm;
import std.stdio;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		auto s = reduce !("a + b") (0, a);
		int res;
		if (s % 2 == 0)
		{
			s >>= 1;
			int t;
			foreach (i; 0..n - 1)
			{
				t += a[i];
				if (t == s)
				{
					res++;
				}
			}
		}
		writeln (res);
	}
}

import core.bitop;
import std.array;
import std.exception;
import std.format;

/**
 *  On the Web: $(WEB en.wikipedia.org/wiki/Fenwick_tree).
 */
struct FenwickTree (T)
 if (is (typeof (T.init + T.init) : T))
{
	private T [] table;
	private int ptwo;

	@property int length ()
	{
		return table.length;
	}

	this (int size)
	{
		enforce (size > 0);
		table.length = size;
		ptwo = 1 << bsr (size);
	}

	/**
	 *  Add delta to data[index].
	 *
	 *  Complexity: $(BIGOH log(n))
	 */
	void add (T2 = T) (int index, T2 delta = 1)
	{
		for ( ; index < length; index |= (index + 1))
		{
			table[index] += delta;
		}
	}

	/**
	 *  Find the sum of data[0..limit].
	 *
	 *  Complexity: $(BIGOH log(n))
	 */
	T2 sum (T2 = T) (int limit)
	{
		T2 res;
		for (limit--; limit >= 0; limit = (limit & (limit + 1)) - 1)
		{
			res += table[limit];
		}
		return res;
	}

	/**
	 *  Find the sum of data[left..right].
	 *
	 *  Complexity: $(BIGOH log(n))
	 */
	T2 sum (T2 = T) (int left, int right)
	{
		return sum !(T2) (right) - sum !(T2) (left);
	}

	/**
	 *  Find leftmost position such that sum of data[0..position] >= bound.
	 *
	 *  Returns length if no such position can be found.
	 *
	 *  Complexity: $(BIGOH log(n))
	 */
	int find (T2 = T) (T2 bound)
	{
		T2 csum;
		int position = 0;
		for (int cur = ptwo; cur > 0; cur >>= 1)
		{
			int npos = position + cur;
			if ((npos <= length) &&
			    csum + table[npos - 1] < bound)
			{
				position = npos;
				csum += table[npos - 1];
			}
		}
		return position;
       	}

	/**
	 *  Print the contents of table to a string.
	 *
	 *  Complexity: $(BIGOH (n))
	 */
	string toString ()
	{
		auto writer = appender !(string) ();
		foreach (i, c; table)
		{
			formattedWrite (writer, "sum[%s..%s] = %s\n",
			                (i + 1) & i, i + 1, c);
		}
		return writer.data;
	}
}

unittest
{
	immutable int MAX_N = 20;
	auto t = FenwickTree !(int) (MAX_N);
	foreach (i; 0..MAX_N)
	{
		t.add (i, i);
	}
	assert (t.sum (MAX_N) == 190);
	assert (t.sum !(long) (MAX_N) == 190);
	assert (t.find (int.min) == 0);
	assert (t.find (54) == 10);
	assert (t.find (55) == 10);
	assert (t.find (56) == 11);
	assert (t.find (long.max) == t.length);
	assert (t.sum (10) == 45);
	assert (t.sum (10, 20) == 190 - 45);
	foreach (i; 0..MAX_N)
	{
		assert (t.sum (i) == t.sum (0, i));
		assert (t.sum (0, i) + t.sum (i, MAX_N) == 190);
	}
	assert (t.toString () ==
	        "sum[0..1] = 0\n" ~
	        "sum[0..2] = 1\n" ~
	        "sum[2..3] = 2\n" ~
	        "sum[0..4] = 6\n" ~
	        "sum[4..5] = 4\n" ~
	        "sum[4..6] = 9\n" ~
	        "sum[6..7] = 6\n" ~
	        "sum[0..8] = 28\n" ~
	        "sum[8..9] = 8\n" ~
	        "sum[8..10] = 17\n" ~
	        "sum[10..11] = 10\n" ~
	        "sum[8..12] = 38\n" ~
	        "sum[12..13] = 12\n" ~
	        "sum[12..14] = 25\n" ~
	        "sum[14..15] = 14\n" ~
	        "sum[0..16] = 120\n" ~
	        "sum[16..17] = 16\n" ~
	        "sum[16..18] = 33\n" ~
	        "sum[18..19] = 18\n" ~
	        "sum[16..20] = 70\n"
	        );
}

import std.algorithm;
import std.stdio;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		auto t = FenwickTree !(int) (n);
		foreach (i; 0..n)
		{
			t.add (i, a[i]);
		}
		int res = 0;
		foreach (i; 1..n)
		{
			if (t.sum (0, i) == t.sum (i, n))
			{
				res++;
			}
		}
		writeln (res);
	}
}

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.range, std.regex;

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

//	chmin/chmax
void chmin(T)(ref T t, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int N;
long[] A;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		A = new long[N];
		foreach (i; 0 .. N) {
			A[i] = readLong;
		}

		const total = reduce!"a + b"(0L, A);
		long sum;
		int ans;
		foreach (i; 0 .. N - 1) {
			sum += A[i];
			if (sum == total - sum) {
				++ans;
			}
		}
		writeln(ans);
	}
	} catch (EOFException) {}
}

import core.bitop;
import std.array;
import std.exception;
import std.format;

/**
 *  On the Web: $(WEB en.wikipedia.org/wiki/Fenwick_tree).
 */
struct FenwickTree (T)
 if (is (typeof (T.init + T.init) : T))
{
	private T [] table;
	private int ptwo;

	@property int length ()
	{
		return table.length;
	}

	this (int size)
	{
		enforce (size > 0);
		table.length = size;
		ptwo = 1 << bsr (size);
	}

	/**
	 *  Add delta to data[index].
	 *
	 *  Complexity: $(BIGOH log(n))
	 */
	void add (T2 = T) (int index, T2 delta = 1)
	{
		for ( ; index < length; index |= (index + 1))
		{
			table[index] += delta;
		}
	}

	/**
	 *  Find the sum of data[0..limit].
	 *
	 *  Complexity: $(BIGOH log(n))
	 */
	T2 sum (T2 = T) (int limit)
	{
		T2 res;
		for (limit--; limit >= 0; limit = (limit & (limit + 1)) - 1)
		{
			res += table[limit];
		}
		return res;
	}

	/**
	 *  Find the sum of data[left..right].
	 *
	 *  Complexity: $(BIGOH log(n))
	 */
	T2 sum (T2 = T) (int left, int right)
	{
		return sum !(T2) (right) - sum !(T2) (left);
	}

	/**
	 *  Find leftmost position such that sum of data[0..position] >= bound.
	 *
	 *  Returns length if no such position can be found.
	 *
	 *  Complexity: $(BIGOH log(n))
	 */
	int find (T2 = T) (T2 bound)
	{
		T2 csum;
		int position = 0;
		for (int cur = ptwo; cur > 0; cur >>= 1)
		{
			int npos = position + cur;
			if ((npos <= length) &&
			    csum + table[npos - 1] < bound)
			{
				position = npos;
				csum += table[npos - 1];
			}
		}
		return position;
       	}

	/**
	 *  Print the contents of table to a string.
	 *
	 *  Complexity: $(BIGOH (n))
	 */
	string toString ()
	{
		auto writer = appender !(string) ();
		foreach (i, c; table)
		{
			formattedWrite (writer, "sum[%s..%s] = %s\n",
			                (i + 1) & i, i + 1, c);
		}
		return writer.data;
	}
}

unittest
{
	immutable int MAX_N = 20;
	auto t = FenwickTree !(int) (MAX_N);
	foreach (i; 0..MAX_N)
	{
		t.add (i, i);
	}
	assert (t.sum (MAX_N) == 190);
	assert (t.sum !(long) (MAX_N) == 190);
	assert (t.find (int.min) == 0);
	assert (t.find (54) == 10);
	assert (t.find (55) == 10);
	assert (t.find (56) == 11);
	assert (t.find (long.max) == t.length);
	assert (t.sum (10) == 45);
	assert (t.sum (10, 20) == 190 - 45);
	foreach (i; 0..MAX_N)
	{
		assert (t.sum (i) == t.sum (0, i));
		assert (t.sum (0, i) + t.sum (i, MAX_N) == 190);
	}
	assert (t.toString () ==
	        "sum[0..1] = 0\n" ~
	        "sum[0..2] = 1\n" ~
	        "sum[2..3] = 2\n" ~
	        "sum[0..4] = 6\n" ~
	        "sum[4..5] = 4\n" ~
	        "sum[4..6] = 9\n" ~
	        "sum[6..7] = 6\n" ~
	        "sum[0..8] = 28\n" ~
	        "sum[8..9] = 8\n" ~
	        "sum[8..10] = 17\n" ~
	        "sum[10..11] = 10\n" ~
	        "sum[8..12] = 38\n" ~
	        "sum[12..13] = 12\n" ~
	        "sum[12..14] = 25\n" ~
	        "sum[14..15] = 14\n" ~
	        "sum[0..16] = 120\n" ~
	        "sum[16..17] = 16\n" ~
	        "sum[16..18] = 33\n" ~
	        "sum[18..19] = 18\n" ~
	        "sum[16..20] = 70\n"
	        );
}

import std.algorithm;
import std.stdio;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		auto t = FenwickTree !(int) (n);
		foreach (i; 0..n)
		{
			t.add (i, a[i]);
		}
		int res = 0;
		foreach (i; 1..n - 1)
		{
			if (t.sum (0, i) == t.sum (i, n))
			{
				res++;
			}
		}
		writeln (res);
	}
}


Bajtek, known for his unusual gifts, recently got an integer array $$$x_0, x_1, \ldots, x_{k-1}$$$.Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array $$$a$$$ of length $$$n + 1$$$. As a formal description of $$$a$$$ says, $$$a_0 = 0$$$ and for all other $$$i$$$ ($$$1 \le i \le n$$$) $$$a_i = x_{(i-1)\bmod k} + a_{i-1}$$$, where $$$p \bmod q$$$ denotes the remainder of division $$$p$$$ by $$$q$$$.For example, if the $$$x = [1, 2, 3]$$$ and $$$n = 5$$$, then:  $$$a_0 = 0$$$,  $$$a_1 = x_{0\bmod 3}+a_0=x_0+0=1$$$,  $$$a_2 = x_{1\bmod 3}+a_1=x_1+1=3$$$,  $$$a_3 = x_{2\bmod 3}+a_2=x_2+3=6$$$,  $$$a_4 = x_{3\bmod 3}+a_3=x_0+6=7$$$,  $$$a_5 = x_{4\bmod 3}+a_4=x_1+7=9$$$. So, if the $$$x = [1, 2, 3]$$$ and $$$n = 5$$$, then $$$a = [0, 1, 3, 6, 7, 9]$$$.Now the boy hopes that he will be able to restore $$$x$$$ from $$$a$$$! Knowing that $$$1 \le k \le n$$$, help him and find all possible values of $$$k$$$ — possible lengths of the lost array.

The first line contains exactly one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the length of the array $$$a$$$, excluding the element $$$a_0$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^6$$$). Note that $$$a_0$$$ is always $$$0$$$ and is not given in the input.

The first line of the output should contain one integer $$$l$$$ denoting the number of correct lengths of the lost array. The second line of the output should contain $$$l$$$ integers — possible lengths of the lost array in increasing order.

NoteIn the first example, any $$$k$$$ is suitable, since $$$a$$$ is an arithmetic progression.Possible arrays $$$x$$$:  $$$[1]$$$ $$$[1, 1]$$$ $$$[1, 1, 1]$$$ $$$[1, 1, 1, 1]$$$  $$$[1, 1, 1, 1, 1]$$$In the second example, Bajtek's array can have three or five elements.Possible arrays $$$x$$$:  $$$[1, 2, 2]$$$ $$$[1, 2, 2, 1, 2]$$$For example, $$$k = 4$$$ is bad, since it leads to $$$6 + x_0 = 8$$$ and $$$0 + x_0 = 1$$$, which is an obvious contradiction.In the third example, only $$$k = n$$$ is good.Array $$$[1, 4, -2]$$$ satisfies the requirements.Note that $$$x_i$$$ may be negative.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		a = 0 ~ a;
		auto b = new int [n];
		foreach (i; 0..n)
		{
			b[i] = a[i + 1] - a[i];
		}

		int [] ans;
		foreach (d; 1..n + 1)
		{
			if (b[0..$ - d] == b[d..$])
			{
				ans ~= d;
			}
		}
		writeln (ans.length);
		writefln ("%(%s %)", ans);
	}
}


Polycarp is practicing his problem solving skill. He has a list of $$$n$$$ problems with difficulties $$$a_1, a_2, \dots, a_n$$$, respectively. His plan is to practice for exactly $$$k$$$ days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all $$$n$$$ problems in exactly $$$k$$$ days.Thus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in $$$k$$$ days he will solve all the $$$n$$$ problems.The profit of the $$$j$$$-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the $$$j$$$-th day (i.e. if he solves problems with indices from $$$l$$$ to $$$r$$$ during a day, then the profit of the day is $$$\max\limits_{l \le i \le r}a_i$$$). The total profit of his practice is the sum of the profits over all $$$k$$$ days of his practice.You want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all $$$n$$$ problems between $$$k$$$ days satisfying the conditions above in such a way, that the total profit is maximum.For example, if $$$n = 8, k = 3$$$ and $$$a = [5, 4, 2, 6, 5, 1, 9, 2]$$$, one of the possible distributions with maximum total profit is: $$$[5, 4, 2], [6, 5], [1, 9, 2]$$$. Here the total profit equals $$$5 + 6 + 9 = 20$$$.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the number of problems and the number of days, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$) — difficulties of problems in Polycarp's list, in the order they are placed in the list (i.e. in the order Polycarp will solve them).

In the first line of the output print the maximum possible total profit. In the second line print exactly $$$k$$$ positive integers $$$t_1, t_2, \dots, t_k$$$ ($$$t_1 + t_2 + \dots + t_k$$$ must equal $$$n$$$), where $$$t_j$$$ means the number of problems Polycarp will solve during the $$$j$$$-th day in order to achieve the maximum possible total profit of his practice. If there are many possible answers, you may print any of them.

NoteThe first example is described in the problem statement.In the second example there is only one possible distribution.In the third example the best answer is to distribute problems in the following way: $$$[1, 2000], [2000, 2]$$$. The total profit of this distribution is $$$2000 + 2000 = 4000$$$.

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

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

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

    auto mxs = arr.dup.enumerate(1).array.sort!((a, b) => a[1] < b[1]).tail(k);

    debug { mxs.writeln; }

    auto sm = mxs.map!(t => t[1]).sum;

    auto idcs = mxs.map!(t => t[0]).array.sort.array;

    idcs = [0] ~ idcs.dropBackOne ~ [n];

    auto ans = zip(idcs, idcs.dropOne).map!(t => t[1] - t[0]);

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