You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?

The first line of the input contains single integer number n (1 ≤ n ≤ 1000) — amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers — endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points.

The first line should contain one integer number — the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any.

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, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	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)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in 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)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int N;
int[] A, B;

struct Interval {
	int s, t;
	int id;
}

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		A = new int[N];
		B = new int[N];
		foreach (i; 0 .. N) {
			A[i] = readInt;
			B[i] = readInt;
			if (A[i] > B[i]) {
				swap(A[i], B[i]);
			}
		}

		Interval[] as = new Interval[N];
		foreach (i; 0 .. N) {
			as[i] = Interval(A[i], B[i], i);
		}
		as.sort!((a, b) => (a.s != b.s) ? (a.s < b.s) : (a.t < b.t));
debug{
writeln(as);
}

		int[] dp = new int[N];
		foreach (i; 0 .. N) {
			dp[i] = 1;
			foreach (j; 0 .. i) {
				if (as[j].t < as[i].s) {
					chmax(dp[i], dp[j] + 1);
				}
			}
		}
debug{
writeln("dp = ",dp);
}

		const ans = reduce!max(0, dp);
		int[] ss = new int[ans + 1];
		int[] ts = new int[ans + 1];
		ss[] = int.min;
		ts[] = int.max;
		foreach (i; 0 .. N) {
			chmax(ss[dp[i]], as[i].s);
			chmin(ts[dp[i]], as[i].t);
		}
debug{
writeln(ss," ",ts);
}
		foreach (j; 1 .. ans + 1) {
			assert(ss[j] <= ts[j]);
		}

		writeln(ans);
		writeln(ss[1 .. $].to!string.removechars("[],"));

	}
	} catch (EOFException) {}
}

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

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto n = next!int;
  alias Ev = Tuple!(int, int, int);
  enum int closeEv = +1;
  enum int openEv = -1;
  auto evs = new Ev[](2 * n);
  foreach(i; 0 .. n)
    {
      int l = next!int;
      int h = next!int;
      if (l > h) swap(l, h);
      evs[2 * i] = Ev(l, openEv, i);
      evs[2 * i + 1] = Ev(h, closeEv, i);
    }
  auto alive = new bool[](n); alive[] = true;
  auto open = redBlackTree!int();
  auto nails = new int[](0);
  sort(evs);
  foreach(ev; evs)
    {
      int i = ev[2];
      int x = ev[0];
      int t = ev[1];
      if (!alive[i]) continue;
      if (t == closeEv)
	{
	  nails ~= x;
	  foreach(oi; open) alive[oi] = false;
	  open.clear;
	}
      else if (t == openEv)
	{
	  open.insert([i]);
	}
      else
	{
	  assert(0);
	}
    }
  nails.length.writeln;
  nails.each!(x => x.write(" "));
  writeln;
}

// INPUT

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

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

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


This is an interactive problem.Consider a fixed positive integer $$$n$$$. Two players, First and Second play a game as follows:  First considers the $$$2n$$$ numbers $$$1, 2, \dots, 2n$$$, and partitions them as he wants into $$$n$$$ disjoint pairs. Then, Second chooses exactly one element from each of the pairs that First created (he chooses elements he wants). To determine the winner of the game, we compute the sum of the numbers chosen by Second. If the sum of all these numbers is a multiple of $$$2n$$$, then Second wins. Otherwise, First wins.You are given the integer $$$n$$$. Your task is to decide which player you wish to play as and win the game.

NoteIn the first sample, $$$n = 2$$$, and you decide to play as Second. The judge chooses the pairs $$$(1, 2)$$$ and $$$(3, 4)$$$, and you reply with the numbers $$$1$$$ and $$$3$$$. This is a valid choice since it contains exactly one number from each pair, and the sum $$$1 + 3 = 4$$$ is divisible by $$$4$$$.In the second sample, $$$n = 2$$$ again, and you play as First. You choose the pairs $$$(2, 4)$$$ and $$$(1, 3)$$$. The judge fails to choose a number from each pair such that their sum is divisible by $$$4$$$, so the answer is correct.Note that the sample tests are just for illustration of the interaction protocol, and don't necessarily correspond to the behavior of the real interactor.

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

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

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

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

void main() {
  const N = readInt();
  if (N % 2 == 0) {
    writeln("First");
    stdout.flush;
    foreach (i; 0 .. 2 * N) {
      if (i > 0) write(" ");
      write(i % N + 1);
    }
    writeln;
    stdout.flush;
  } else {
    writeln("Second");
    stdout.flush;

    auto P = new int[2 * N];
    foreach (i; 0 .. 2 * N) {
      P[i] = readInt() - 1;
    }
    auto iss = new int[][N];
    foreach (i; 0 .. 2 * N) {
      iss[P[i]] ~= i;
    }

    auto vis = new bool[N];
    foreach (u; 0 .. N) {
      if (!vis[u]) {
        for (int v = u, x = u; !vis[v]; ) {
          vis[v] = true;
          const j = P[x];
          if (iss[j][0] != x) {
            swap(iss[j][0], iss[j][1]);
          }
          const vv = iss[j][1] % N;
          const xx = (iss[j][1] + N) % (2 * N);
          v = vv;
          x = xx;
        }
      }
    }
    debug {
      writeln("iss = ", iss);
    }

    long sum;
    foreach (j; 0 .. N) {
      sum += iss[j][0] + 1;
    }
    const s = (sum % (2 * N) == 0) ? 0 : 1;

    foreach (j; 0 .. N) {
      if (j > 0) write(" ");
      write(iss[j][s] + 1);
    }
    writeln;
    stdout.flush;
  }
}


Your friend has a hidden directed graph with n nodes.Let f(u, v) be true if there is a directed path from node u to node v, and false otherwise. For each pair of distinct nodes, u, v, you know at least one of the three statements is true:        Here AND, OR and XOR mean AND, OR and exclusive OR operations, respectively.You are given an n by n matrix saying which one of the three statements holds for each pair of vertices. The entry in the u-th row and v-th column has a single character.   If the first statement holds, this is represented by the character 'A'.  If the second holds, this is represented by the character 'O'.  If the third holds, this is represented by the character 'X'.  The diagonal of this matrix will only contain the character '-'. Note that it is possible that a pair of nodes may satisfy multiple statements, in which case, the character given will represent one of the true statements for that pair. This matrix is also guaranteed to be symmetric.You would like to know if there is a directed graph that is consistent with this matrix. If it is impossible, print the integer -1. Otherwise, print the minimum number of edges that could be consistent with this information.

The first line will contain an integer n (1 ≤ n ≤ 47), the number of nodes. The next n lines will contain n characters each: the matrix of what you know about the graph connectivity in the format described in the statement.

Print the minimum number of edges that is consistent with the given information, or -1 if it is impossible.

NoteSample 1: The hidden graph is a strongly connected graph. We can put all four nodes in a cycle.Sample 2: One valid graph is 3 → 1 → 2. For each distinct pair, exactly one of f(u, v), f(v, u) holds.

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

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

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

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

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

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

enum MO = 10^^9 + 403;
alias Mint = ModInt!MO;

int solve(int n, bool[][] adj) {
  debug {
    writeln("solve ", n, " ", adj);
  }
  auto as = new int[n];
  foreach (u; 0 .. n) foreach (v; 0 .. n) {
    if (adj[u][v]) {
      as[u] |= 1 << v;
    }
  }
  if (n == 0) {
    return 0;
  }
  if (as.all!"a == 0") {
    return 1;
  }
  auto ind = new long[1 << n];
  ind[0] = 1;
  foreach (u; 0 .. n) {
    foreach (p; 0 .. 1 << u) {
      ind[p | 1 << u] = ind[p] + ind[p &~ as[u]];
    }
  }
  debug {
    writeln("ind = ", ind);
  }
  int lo = 1, hi = n;
  auto fs = new Mint[1 << n];
  for (; lo + 1 < hi; ) {
    const mid = (lo + hi) / 2;
    foreach (p; 0 .. 1 << n) {
      fs[p] = Mint(ind[p])^^mid;
    }
    Mint sum;
    foreach (p; 0 .. 1 << n) {
      sum += (-1)^^(popcnt(p) & 1) * fs[p];
    }
    (sum ? hi : lo) = mid;
  }
  return hi;
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new string[N];
      foreach (u; 0 .. N) {
        A[u] = readToken();
      }

      auto uf = new int[N];
      uf[] = -1;
      foreach (u; 0 .. N) foreach (v; u + 1 .. N) {
        if (A[u][v] == 'A') {
          uf.connect(u, v);
        }
      }
      bool ok = true;
      foreach (u; 0 .. N) foreach (v; u + 1 .. N) {
        if (A[u][v] == 'X') {
          ok = ok && (uf.root(u) != uf.root(v));
        }
      }
      if (ok) {
        int n;
        auto ids = new int[N];
        ids[] = -1;
        foreach (r; 0 .. N) {
          if (uf[r] < 0) {
            if (-uf[r] >= 2) {
              ids[r] = n++;
            }
          }
        }
        auto adj = new bool[][](n, n);
        foreach (u; 0 .. N) foreach (v; u + 1 .. N) {
          if (A[u][v] == 'X') {
            const x = ids[uf.root(u)];
            const y = ids[uf.root(v)];
            if (x != -1 && y != -1) {
              adj[x][y] = adj[y][x] = true;
            }
          }
        }
        const res = solve(n, adj);
        writeln(N - 1 + res);
      } else {
        writeln(-1);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

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

enum MO = 10^^9 + 403;
alias Mint = ModInt!MO;

int solve(int n, bool[][] adj) {
  debug {
    writeln("solve ", n, " ", adj);
  }
  auto as = new int[n];
  foreach (u; 0 .. n) foreach (v; 0 .. n) {
    if (adj[u][v]) {
      as[u] |= 1 << v;
    }
  }
  if (as.all!"a == 0") {
    return 1;
  }
  auto ind = new long[1 << n];
  ind[0] = 1;
  foreach (u; 0 .. n) {
    foreach (p; 0 .. 1 << u) {
      ind[p | 1 << u] = ind[p] + ind[p &~ as[u]];
    }
  }
  debug {
    writeln("ind = ", ind);
  }
  int lo = 1, hi = n;
  auto fs = new Mint[1 << n];
  for (; lo + 1 < hi; ) {
    const mid = (lo + hi) / 2;
    foreach (p; 0 .. 1 << n) {
      fs[p] = Mint(ind[p])^^mid;
    }
    foreach (u; 0 .. n) {
      foreach (p; 0 .. 1 << n) {
        if (!(p & 1 << u)) {
          fs[p | 1 << u] -= fs[p];
        }
      }
    }
    (fs[$ - 1] ? hi : lo) = mid;
  }
  return hi;
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new string[N];
      foreach (u; 0 .. N) {
        A[u] = readToken();
      }

      auto uf = new int[N];
      uf[] = -1;
      foreach (u; 0 .. N) foreach (v; u + 1 .. N) {
        if (A[u][v] == 'A') {
          uf.connect(u, v);
        }
      }
      bool ok = true;
      foreach (u; 0 .. N) foreach (v; u + 1 .. N) {
        if (A[u][v] == 'X') {
          ok = ok && (uf.root(u) != uf.root(v));
        }
      }
      if (ok) {
        int n;
        auto ids = new int[N];
        ids[] = -1;
        foreach (r; 0 .. N) {
          if (uf[r] < 0) {
            if (-uf[r] >= 2) {
              ids[r] = n++;
            }
          }
        }
        auto adj = new bool[][](n, n);
        foreach (u; 0 .. N) foreach (v; u + 1 .. N) {
          if (A[u][v] == 'X') {
            const x = ids[uf.root(u)];
            const y = ids[uf.root(v)];
            if (x != -1 && y != -1) {
              adj[x][y] = adj[y][x] = true;
            }
          }
        }
        const res = solve(n, adj);
        writeln(N - 1 + res);
      } else {
        writeln(-1);
      }
    }
  } catch (EOFException e) {
  }
}


Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is ci. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya.Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values x, such that Arya will be able to make x using some subset of coins with the sum k.Formally, Pari wants to know the values x such that there exists a subset of coins with the sum k such that some subset of this subset has the sum x, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum x using these coins.

The first line contains two integers n and k (1  ≤  n, k  ≤  500) — the number of coins and the price of the chocolate, respectively. Next line will contain n integers c1, c2, ..., cn (1 ≤ ci ≤ 500) — the values of Pari's coins. It's guaranteed that one can make value k using these coins.

First line of the output must contain a single integer q— the number of suitable values x. Then print q integers in ascending order — the values that Arya can make for some subset of coins of Pari that pays for the chocolate.

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

immutable int NA = -1;

void main ()
{
	int n;
	int k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto c = readln.split.map !(to !(int)).array;

		auto f = new bool [] [] (k + 1, k + 1);
		f[0][0] = true;
		foreach (cur; c)
		{
			foreach_reverse (i; 0..k + 1)
			{
				foreach_reverse (j; 0..k + 1)
				{
					if (i >= cur)
					{
						f[i][j] |= f[i - cur][j];
					}
					if (j >= cur)
					{
						f[i][j] |= f[i][j - cur];
					}
				}
			}
		}

		int [] ans = (k + 1).iota.filter !(x => f[x][k - x]).array;
		writefln ("%s\n%(%s %)", ans.length, ans);
	}
}


When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.

The first line contains a single integer $$$n$$$ ($$$1 \leqslant n \leqslant 10^5$$$) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'. It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit $$$0$$$ or "one" which corresponds to the digit $$$1$$$.

Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.

NoteIn the first example, the correct initial ordering is "zero".In the second example, the correct initial ordering is "oneonezero".

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const S = readToken();

      const z = S.count('z');
      const n = S.count('n');
      int ou;
      foreach (i; 0 .. n) {
        if (ou++) write(" ");
        write(1);
      }
      foreach (i; 0 .. z) {
        if (ou++) write(" ");
        write(0);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}

import std.stdio;
int main()
{
	int a=0;
	readf(" %d", &a);
	string s;
	readf(" %s", &s);
	char[] m = s.dup;
	int n=0;
	for (int i=0; i<a; i++)
	{
		if (m[i]=='n')
		{
			n=n+1;
		}
	}
	for (int i=0; i<n; i++)
	{
		writeln(1);
	}
	for (int i=0; i<((a-n*3)/4); i++)
	{
		writeln(0);
	}
	return 0;
}

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; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } 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 = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto s = RD!string;
	long[char] cnt;
	cnt['n'] = 0;
	cnt['z'] = 0;
	foreach (c; s)
	{
		++cnt[c];
	}

	long[] ans;
	foreach (i; 0..cnt['n'])
		ans ~= 1;
	foreach (i; 0..cnt['z'])
		ans ~= 0;
	ans.map!(to!string).join(" ").writeln;
	stdout.flush();
	debug readln();
}


International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.You are given a list of abbreviations. For each of them determine the year it stands for.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of abbreviations to process.  Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.

For each abbreviation given in the input, find the year of the corresponding Olympiad.

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 s = readln.strip;
		auto t = s[4..$];
		auto v = t.to !(long);
		long n = 1989 - 1;
		int len = 1;
		while (len <= t.length)
		{
			do
			{
				n += 10L ^^ (len - 1);
			}
			while (n.text[$ - len..$] != t[$ - len..$]);
			len++;
		}
		writeln (n);
	}
}


You are given a rectangular matrix of size $$$n \times m$$$ consisting of integers from $$$1$$$ to $$$2 \cdot 10^5$$$.In one move, you can:  choose any element of the matrix and change its value to any integer between $$$1$$$ and $$$n \cdot m$$$, inclusive;  take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some $$$j$$$ ($$$1 \le j \le m$$$) and set $$$a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j}$$$ simultaneously.  Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this:  In other words, the goal is to obtain the matrix, where $$$a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$$$ (i.e. $$$a_{i, j} = (i - 1) \cdot m + j$$$) with the minimum number of moves performed.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5, n \cdot m \le 2 \cdot 10^5$$$) — the size of the matrix. The next $$$n$$$ lines contain $$$m$$$ integers each. The number at the line $$$i$$$ and position $$$j$$$ is $$$a_{i, j}$$$ ($$$1 \le a_{i, j} \le 2 \cdot 10^5$$$).

Print one integer — the minimum number of moves required to obtain the matrix, where $$$a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$$$ ($$$a_{i, j} = (i - 1)m + j$$$).

NoteIn the first example, you can set $$$a_{1, 1} := 7, a_{1, 2} := 8$$$ and $$$a_{1, 3} := 9$$$ then shift the first, the second and the third columns cyclically, so the answer is $$$6$$$. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is $$$0$$$.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is $$$2$$$.

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

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

    int[][] arr;
    foreach (i; 0 .. n) {
        arr ~= readln.chomp.split.map!(to!int).array;
    }

    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            arr[i][j] -= 1;
        }
    }

    int ans = 0;
    foreach (col; 0 .. m) {
        auto dst = new int[] (n);
        dst[] = 0;
        foreach (rw; 0 .. n) {
            if (arr[rw][col] >= n*m) { continue; }

            int md = arr[rw][col] % m;
            if (md != col) { continue; }

            int rwval = arr[rw][col] / m;
            int curdst = rw >= rwval ? rw - rwval : rw + 1 + n-1 - rwval;

            dst[curdst] += 1;
        }

        int colsum = n;
        foreach (d; 0 .. n) {
            colsum = min(colsum, d + n - dst[d]);
        }

        ans += colsum;
    }

    ans.writeln;
}

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

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

    int[][] arr;
    foreach (i; 0 .. n) {
        arr ~= readln.chomp.split.map!(to!int).array;
    }

    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            arr[i][j] -= 1;
        }
    }

    int ans = 0;
    foreach (col; 0 .. m) {
        auto dst = new int[] (n);
        dst[] = 0;
        foreach (rw; 0 .. n) {
            if (arr[rw][col] >= n*m) { continue; }

            int md = arr[rw][col] % m;
            if (md != col) { continue; }

            int rwval = arr[rw][col] / m;
            int curdst = (rw - rwval + n) % n;

            dst[curdst] += 1;
        }

        int colsum = n;
        foreach (d; 0 .. n) {
            colsum = min(colsum, d + n - dst[d]);
        }

        ans += colsum;
    }

    ans.writeln;
}

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

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

		int res = 0;
		foreach (j; 0..m)
		{
			auto d = n.iota.array;
			d[] += n;
			foreach (i; 0..n)
			{
				if (a[i][j] < n * m && a[i][j] % m == j)
				{
					d[(i + n - a[i][j] / m) % n] -= 1;
				}
			}
			res += minElement (d);
		}
		writeln (res);
	}
}

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

string[] tokens;

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

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

void main()
{
    int n = readInt;
    int m = readInt;
    int[][] a = new int[][n];
    for (int i = 0; i < n; ++i)
    {
        a[i] = new int[m];
        for (int j = 0; j < m; ++j)
        {
            a[i][j] = readInt - 1;
        }
    }

    int[] count = new int[n];

    int result = 0;
    for (int j = 0; j < m; ++j)
    {
        fill(count, 0);
        for (int i = 0; i < n; ++i)
        {
            int x = a[i][j];
            if (x < n * m && x % m == j)
            {
                count[(i + n - (x - j) / m) % n]++;
            }
        }
        int best = n;
        for (int i = 0; i < n; ++i)
        {
            int x = a[i][j];
            if (x < n * m && x % m == j)
            {
                int moves = (i + n - (x - j) / m) % n;
                best = min(best, n - count[moves] + moves);
            }
        }
        result += best;
    }
    writeln(result);
}

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

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

    auto arr = new int[][] (n);
    foreach (i; 0 .. n) {
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            arr[i][j] -= 1;
        }
    }

    int ans = 0;
    foreach (col; 0 .. m) {
        auto dst = new int[] (n);
        dst[] = 0;
        foreach (rw; 0 .. n) {
            int md = arr[rw][col] % m;
            if (md != col) { continue; }

            int rwval = arr[rw][col] / m;
            int curdst = rw >= rwval ? rw - rwval : rw + n-1 - rwval;

            dst[curdst] += 1;
        }

        int colsum = n;
        foreach (d; 0 .. n) {
            colsum = min(colsum, d + n - dst[d]);
        }

        ans += colsum;
    }

    ans.writeln;
}

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

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

    auto arr = new int[][] (n);
    foreach (i; 0 .. n) {
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            arr[i][j] -= 1;
        }
    }

    int ans = 0;
    foreach (col; 0 .. m) {
        auto dst = new int[] (n);
        foreach (rw; 0 .. n) {
            int md = arr[rw][col] % m;
            if (md != col) { continue; }

            int rwval = arr[rw][col] / m;
            int curdst = (rw - rwval + n) % n;

            dst[curdst] += 1;
        }

        int colsum = n-1;
        foreach (d; 0 .. n) {
            colsum = min(colsum, d + n - dst[d]);
        }

        ans += colsum;
    }

    ans.writeln;
}

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

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

    auto arr = new int[][] (n);
    foreach (i; 0 .. n) {
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            arr[i][j] -= 1;
        }
    }

    int ans = 0;
    foreach (col; 0 .. m) {
        auto dst = new int[] (n);
        foreach (rw; 0 .. n) {
            int md = arr[rw][col] % m;
            if (md != col) { continue; }

            int rwval = arr[rw][col] / m;
            int curdst = rw >= rwval ? rw - rwval : rw + n-1 - rwval;

            dst[curdst] += 1;
        }

        int colsum = n;
        foreach (d; 0 .. n) {
            colsum = min(colsum, d + n - dst[d]);
        }

        ans += colsum;
    }

    ans.writeln;
}

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

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

    auto arr = new int[][] (n);
    foreach (i; 0 .. n) {
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            arr[i][j] -= 1;
        }
    }

    int ans = 0;
    foreach (col; 0 .. m) {
        auto dst = new int[] (n);
        foreach (rw; 0 .. n) {
            int md = arr[rw][col] % m;
            if (md != col) { continue; }

            int rwval = arr[rw][col] / m;
            int curdst = rw >= rwval ? rw - rwval : rw + n-1 - rwval;

            dst[curdst] += 1;
        }

        int colsum = n-1;
        foreach (d; 0 .. n) {
            colsum = min(colsum, d + n - dst[d]);
        }

        ans += colsum;
    }

    ans.writeln;
}

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

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

    auto arr = new int[][] (n);
    foreach (i; 0 .. n) {
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            arr[i][j] -= 1;
        }
    }

    int ans = 0;
    foreach (col; 0 .. m) {
        auto dst = new int[] (n);
        dst[] = 0;
        foreach (rw; 0 .. n) {
            if (arr[rw][col] >= n*m) { continue; }

            int md = arr[rw][col] % m;
            if (md != col) { continue; }

            int rwval = arr[rw][col] / m;
            int curdst = rw >= rwval ? rw - rwval : rw + n-1 - rwval;

            dst[curdst] += 1;
        }

        int colsum = n;
        foreach (d; 0 .. n) {
            colsum = min(colsum, d + n - dst[d]);
        }

        ans += colsum;
    }

    ans.writeln;
}

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

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

    auto arr = new int[][] (n);
    foreach (i; 0 .. n) {
        arr[i] = readln.chomp.split.map!(to!int).array;
    }

    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            arr[i][j] -= 1;
        }
    }

    int ans = 0;
    foreach (col; 0 .. m) {
        auto dst = new int[] (n);
        foreach (rw; 0 .. n) {
            int md = arr[rw][col] % m;
            if (md != col) { continue; }

            int rwval = arr[rw][col] / m;
            int curdst = (rw - rwval + n-1) % (n-1);

            dst[curdst] += 1;
        }

        int colsum = n-1;
        foreach (d; 0 .. n) {
            colsum = min(colsum, d + n - dst[d]);
        }

        ans += colsum;
    }

    ans.writeln;
}

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

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

    int[][] arr;
    foreach (i; 0 .. n) {
        arr ~= readln.chomp.split.map!(to!int).array;
    }

    foreach (i; 0 .. n) {
        foreach (j; 0 .. m) {
            arr[i][j] -= 1;
        }
    }

    int ans = 0;
    foreach (col; 0 .. m) {
        auto dst = new int[] (n);
        dst[] = 0;
        foreach (rw; 0 .. n) {
            if (arr[rw][col] >= n*m) { continue; }

            int md = arr[rw][col] % m;
            if (md != col) { continue; }

            int rwval = arr[rw][col] / m;
            int curdst = rw >= rwval ? rw - rwval : rw + n-1 - rwval;

            dst[curdst] += 1;
        }

        int colsum = n;
        foreach (d; 0 .. n) {
            colsum = min(colsum, d + n - dst[d]);
        }

        ans += colsum;
    }

    ans.writeln;
}

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

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

		int res = 0;
		foreach (j; 0..m)
		{
			auto d = n.iota.array;
			d[] += n;
			foreach (i; 0..n)
			{
				if (a[i][j] % m == j)
				{
					d[(i + n - a[i][j] / m) % n] -= 1;
				}
			}
			res += minElement (d);
		}
		writeln (res);
	}
}

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

string[] tokens;

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

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

void main()
{
    int n = readInt;
    int m = readInt;
    int[][] a = new int[][n];
    for (int i = 0; i < n; ++i)
    {
        a[i] = new int[m];
        for (int j = 0; j < m; ++j)
        {
            a[i][j] = readInt - 1;
        }
    }

    int[] count = new int[n];

    int result = 0;
    for (int j = 0; j < m; ++j)
    {
        fill(count, 0);
        for (int i = 0; i < n; ++i)
        {
            int x = a[i][j];
            if (x % m == j)
            {
                count[(i + n - (x - j) / m) % n]++;
            }
        }
        int best = n;
        for (int i = 0; i < n; ++i)
        {
            int x = a[i][j];
            if (x % m == j)
            {
                int moves = (i + n - (x - j) / m) % n;
                best = min(best, n - count[moves] + moves);
            }
        }
        result += best;
    }
    writeln(result);
}


Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the sbegin and ending with the send (it is possible sbegin = send), the given string t has. Substrings are different if and only if their contents aren't equal, their positions of occurence don't matter. Petya wasn't quite good at math, that's why he couldn't count this number. Help him!

The input file consists of three lines. The first line contains string t. The second and the third lines contain the sbegin and send identificators, correspondingly. All three lines are non-empty strings consisting of lowercase Latin letters. The length of each string doesn't exceed 2000 characters.

Output the only number — the amount of different substrings of t that start with sbegin and end with send.

NoteIn the third sample there are four appropriate different substrings. They are: ab, abab, ababab, abababab.In the fourth sample identificators intersect.

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

class Trie
{
    protected class Node
    {
        bool flag;
        Node[26] children;
        this()
        {
            flag = false;
        }
    }

    protected Node root;
    protected Node prev;

    this()
    {
        root = new Node();
        prev = root;
    }

    protected Tuple!(bool, Node) insert(char ch, Node node, bool flag)
    {
        auto p = ch - 'a';
        if (!node.children[p])
        {
            node.children[p] = new Node();
        }
        node = node.children[p];
        node.flag = flag;
        return tuple(true, node);
    }

    bool persistentInsert(char ch, bool flag)
    {
        auto ret = insert(ch, prev, flag);
        if (ret[0])
        {
            prev = ret[1];
        }
        return ret[0];
    }

    protected int _countFlag(Node node)
    {
        if (!node)
        {
            return 0;
        }
        auto res = 0;
        if (node.flag)
        {
            ++ res;
        }
        foreach (i; 0 .. 26)
        {
            auto ret = _countFlag(node.children[i]);
            res += ret;
        }
        return res;
    }

    int countFlag()
    {
        return _countFlag(root);
    }

    void resetPrev()
    {
        prev = root;
    }
}

void solve(string t, string sb, string se)
{
    auto n = cast(int)t.length;
    auto bn = cast(int)sb.length;
    auto ff = new bool[n + 1];
    for (int i = 0; i < n && n - i >= bn; ++ i)
    {
        int j, k;
        for (j = i, k = 0; j < n && k < bn; ++ j, ++ k)
        {
            if (t[j] != sb[k])
            {
                break;
            }
        }
        ff[i] = k == bn ? true : false;
    }
    auto en = cast(int)se.length;
    auto bf = new bool[n + 1];
    for (int i = en - 1; i < n; ++ i)
    {
        int j, k;
        for (j = i, k = en - 1; j >= 0 && k >= 0; -- j, -- k)
        {
            if (t[j] != se[k])
            {
                break;
            }
        }
        bf[i] = k < 0 ? true : false;
    }
    auto trie = new Trie();
    foreach (i; 0 .. n)
    {
        trie.resetPrev();
        int bound;
        for (bound = n - 1; bound >= i; -- bound)
        {
            if (ff[i] && bf[bound] && bound - i + 1 >= bn && bound - i + 1 >= en)
            {
                break;
            }
        }
        foreach (j; i .. bound + 1)
        {
            if (ff[i] && bf[j] && j - i + 1 >= bn && j - i + 1 >= en)
            {
                trie.persistentInsert(t[j], true);
            }
            else
            {
                trie.persistentInsert(t[j], false);
            }
        }
    }
    auto ans = trie.countFlag();
    writeln(ans);
}

int main(string[] args)
{
    string t, sb, se;
    t = readln().strip();
    sb = readln().strip();
    se = readln().strip();
    solve(t, sb, se);
    return 0;
}


There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.Also, each minute Vasya's bank account receives C·k, where k is the amount of received but unread messages.Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.Determine the maximum amount of money Vasya's bank account can hold after T minutes.

The first line contains five integers n, A, B, C and T (1 ≤ n, A, B, C, T ≤ 1000). The second string contains n integers ti (1 ≤ ti ≤ T).

Output one integer  — the answer to the problem.

NoteIn the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, n·A = 20 in total.In the second sample the messages can be read at any integer moment.In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4·3) + (5 - 3·3) + (5 - 2·3) + (5 - 1·3) + 5 =  - 5 points. This is 35 in total.

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

void main() {
	auto args = readln.chomp.split.map!(to!int).array;
	int n = args[0];
	int A = args[1];
	int B = args[2];
	int C = args[3];
	int T = args[4];
	int[] t = readln.chomp.split.map!(to!int).array;
	int[][][] dp = new int[][][](T + 2, T + 2, 2);
	int[int] dic;
	for (int i = 1; i <= T; ++i) {
		dic[i] = 0;
	}
	foreach (v; t) {
		++dic[v];
	}
	debug stderr.writeln(dic);
	for (int i = 1; i <= T; ++i) {
		for (int j = 1; j <= i; ++j) {
			debug stderr.writeln(tuple(i, j, 1));
			{
				dp[i + 1][j][1] = dp[i][j][1] + dic[j] * C;
				debug stderr.writefln("\tdp[%d][%d][1] = %d (%d + %d * %d)", i + 1, j, dp[i + 1][j][0], dp[i][j][1], dic[j], C);
			}
			{
				int pena = A - (i - j) * B;
				dp[i + 1][j][0] = max(dp[i][j][0], dp[i][j][1] + dic[j] * pena);
				debug stderr.writefln("\tdp[%d][%d][0] = %d (max(%d, %d + %d * %d)", i + 1, j, dp[i + 1][j][0], dp[i][j][0], dp[i][j][1], dic[j], pena);
			}
		}
	}
	int sum = 0;
	for (int i = 1; i <= T; ++i) {
		debug stderr.writefln("\t(%d) : %d", i, dp[T + 1][i][0]);
		sum += dp[T + 1][i][0];
	}
	sum.writeln;
}

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

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

void main()
{
  int n, a, b, c, te; readV(n, a, b, c, te);
  int[] t; readA(n, t);

  auto ans = 0;
  foreach (ti; t) {
    if (b > c) {
      ans += a;
    } else {
      ans += a + (c-b)*(te-ti);
    }
  }

  writeln(ans);
}


You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime.  Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.

NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime.  The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto g = new int [] [n];
		auto u = new int [n];
		auto v = new int [n];
		foreach (i; 0..n - 1)
		{
			readf !(" %s %s") (u[i], v[i]);
			u[i] -= 1;
			v[i] -= 1;
			g[u[i]] ~= i;
			g[v[i]] ~= i;
		}
		readln;
		if (g.any !(q{a.length > 2}))
		{
			writeln (-1);
		}
		else
		{
			auto w = new int [n - 1];
			auto x = n.iota.countUntil !(i => g[i].length < 2)
			    .to !(int);
			auto y = g[x].front;
			foreach (k; 0..n - 1)
			{
				w[y] = 2 + k % 2;
				x = x ^ u[y] ^ v[y];
				y = y ^ g[x].front ^ g[x].back;
			}
			writefln !("%(%s %)") (w);
		}
	}
}


Polycarp remembered the $$$2020$$$-th year, and he is happy with the arrival of the new $$$2021$$$-th year. To remember such a wonderful moment, Polycarp wants to represent the number $$$n$$$ as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$.For example, if:   $$$n=4041$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2021$$$;  $$$n=4042$$$, then the number $$$n$$$ can be represented as the sum $$$2021 + 2021$$$;  $$$n=8081$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2020 + 2020 + 2021$$$;  $$$n=8079$$$, then the number $$$n$$$ cannot be represented as the sum of the numbers $$$2020$$$ and $$$2021$$$. Help Polycarp to find out whether the number $$$n$$$ can be represented as the sum of a certain number of numbers $$$2020$$$ and a certain number of numbers $$$2021$$$.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$) — the number that Polycarp wants to represent as the sum of the numbers $$$2020$$$ and $$$2021$$$.

For each test case, output on a separate line:    "YES" if the number $$$n$$$ is representable as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T);
    while (T--) {
        int N; get(N);
        int x;
        while (N >= 2020) {
            N -= 2020;
            ++x;
        }
        writeln(x >= N ? "YES" : "NO");
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto cnt = n / 2020;
		auto rem = n % 2020;
		ans[ti] = rem <= cnt;
	}

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

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

immutable int base = 2020;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto q = n / base;
		auto r = n % base;
		writeln ((q >= base) || (q >= r) ? "YES" : "NO");
	}
}