This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution.Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computersPolycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices.Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node.Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture.    (1) — bus, (2) — ring, (3) — star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown.

The first line contains two space-separated integers n and m (4 ≤ n ≤ 105; 3 ≤ m ≤ 105) — the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≤ xi, yi ≤ n) — the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself.

In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes).

bus topology
ring topology
star topology
unknown topology

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

void main() {
    int m, n; readf("%d %d\n", &m, &n);
    int[] c = new int[m];
    foreach (i; 0 .. n) {
        int x, y; readf("%d %d\n", &x, &y); x--, y--;
        c[x]++, c[y]++;
    }
    if (!c.find(n).empty) {
        writeln("star topology");
    } else if (c.count(1) == 2 && c.count(2) == m - 2) {
        writeln("bus topology");
    } else if (c.count(2) == m) {
        writeln("ring topology");
    } else {
        writeln("unknown topology");
    }
}

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

int [] [] a;
bool [] b;
int [] d;
int n, m;

void recur (int w)
{
	if (b[w])
	{
		return;
	}
	b[w] = true;
	foreach (c; a[w])
	{
		recur (c);
	}
}

void main ()
{
	while (readf (" %s %s", &n, &m) > 0)
	{
		a = new int [] [n];
		d = new int [n];
		foreach (i; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--;
			v--;
			a[u] ~= v;
			a[v] ~= u;
			d[u]++;
			d[v]++;
		}

		b = new bool [n];
		recur (0);
		bool ok = true;
		foreach (i; 0..n)
		{
			ok &= b[i];
		}

		auto s = new int [n + m + 1];
		foreach (i; 0..n)
		{
			s[d[i]]++;
		}
		debug {writeln (ok);}

		if (ok && s[1] == 2 && s[2] == n - 2)
		{
			writeln ("bus topology");
		}
		else if (ok && s[2] == n)
		{
			writeln ("ring topology");
		}
		else if (ok && s[1] == n - 1 && s[n - 1] == 1)
		{
			writeln ("star topology");
		}
		else
		{
			writeln ("unknown topology");
		}
	}
}

module sigod.codeforces.p292B;

import std.algorithm;
import std.stdio;
import std.typecons;

private {
	enum BUS = "bus topology";
	enum RING = "ring topology";
	enum STAR = "star topology";
	enum UNKNOWN = "unknown topology";
}

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

	int[] vertex = new int[n];

	foreach (i; 0 .. m) {
		int x, y;
		stdin.readf(" %s %s", &x, &y);

		++vertex[x - 1];
		++vertex[y - 1];
	}

	vertex.sort();

	auto g = vertex.group();

	if (n == m + 1) {
		if (equal(g, [tuple(1, 2u), tuple(2, cast(uint) n - 2)][])) {
			stdout.writeln(BUS);
		}
		else if (equal(g, [tuple(1, n - 1), tuple(n - 1, 1)][])) {
			stdout.writeln(STAR);
		}
		else {
			stdout.writeln(UNKNOWN);
		}
	}
	else if (n == m && equal(g, [tuple(2, n)][])) {
		stdout.writeln(RING);
	}
	else {
		stdout.writeln(UNKNOWN);
	}
}

module sigod.codeforces.p292B;

import std.algorithm;
import std.stdio;
import std.typecons;

private {
	enum BUS = "bus topology";
	enum RING = "ring topology";
	enum STAR = "star topology";
	enum UNKNOWN = "unknown topology";
}

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

	byte[] vertex = new byte[n];

	foreach (i; 0 .. m) {
		int x, y;
		stdin.readf(" %s %s", &x, &y);

		++vertex[x - 1];
		++vertex[y - 1];
	}

	vertex.sort();

	auto g = vertex.group();

	if (n == m + 1) {
		if (equal(g, [tuple(1, 2u), tuple(2, cast(uint) n - 2)][])) {
			stdout.writeln(BUS);
		}
		else if (equal(g, [tuple(1, n - 1), tuple(n - 1, 1)][])) {
			stdout.writeln(STAR);
		}
		else {
			stdout.writeln(UNKNOWN);
		}
	}
	else if (n == m && equal(g, [tuple(2, n)][])) {
		stdout.writeln(RING);
	}
	else {
		stdout.writeln(UNKNOWN);
	}
}


This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of $$$m$$$ and the time limit. You need to solve both subtasks in order to hack this one.There are $$$n+1$$$ distinct colours in the universe, numbered $$$0$$$ through $$$n$$$. There is a strip of paper $$$m$$$ centimetres long initially painted with colour $$$0$$$. Alice took a brush and painted the strip using the following process. For each $$$i$$$ from $$$1$$$ to $$$n$$$, in this order, she picks two integers $$$0 \leq a_i < b_i \leq m$$$, such that the segment $$$[a_i, b_i]$$$ is currently painted with a single colour, and repaints it with colour $$$i$$$. Alice chose the segments in such a way that each centimetre is now painted in some colour other than $$$0$$$. Formally, the segment $$$[i-1, i]$$$ is painted with colour $$$c_i$$$ ($$$c_i \neq 0$$$). Every colour other than $$$0$$$ is visible on the strip.Count the number of different pairs of sequences $$$\{a_i\}_{i=1}^n$$$, $$$\{b_i\}_{i=1}^n$$$ that result in this configuration. Since this number may be large, output it modulo $$$998244353$$$.

The first line contains a two integers $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 500$$$, $$$n = m$$$) — the number of colours excluding the colour $$$0$$$ and the length of the paper, respectively. The second line contains $$$m$$$ space separated integers $$$c_1, c_2, \ldots, c_m$$$ ($$$1 \leq c_i \leq n$$$) — the colour visible on the segment $$$[i-1, i]$$$ after the process ends. It is guaranteed that for all $$$j$$$ between $$$1$$$ and $$$n$$$ there is an index $$$k$$$ such that $$$c_k = j$$$. Note that since in this subtask $$$n = m$$$, this means that $$$c$$$ is a permutation of integers $$$1$$$ through $$$n$$$.

Output a single integer — the number of ways Alice can perform the painting, modulo $$$998244353$$$.

NoteIn the first example, there are $$$5$$$ ways, all depicted in the figure below. Here, $$$0$$$ is white, $$$1$$$ is red, $$$2$$$ is green and $$$3$$$ is blue.Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour $$$2$$$.

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

struct ModInt(long M) {
  long x;
  this(in ModInt a) { x = a.x; }
  this(in long a) { x = a % M; if (x < 0) x += M; }
  ModInt opUnary(string op)() if (op == "-") { return ModInt(-x); }
  ref ModInt opOpAssign(string op)(in 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 *= a.x; x %= M; }
    else static assert(false);
    return this;
  }
  ModInt opOpAssign(string op)(in long a) { return mixin("this " ~ op ~ "= ModInt(a)"); }
  ModInt opBinary(string op, T)(in T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op)(in long a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  string toString() const { return x.to!string; }
}

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

int N, M;
int[] C;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      M = readInt();
      C = new int[M];
      foreach (i; 0 .. M) {
        C[i] = readInt();
      }

      auto dp = new Mint[][](N + 1, N + 1);
      foreach (i; 0 .. N + 1) {
        dp[i][i] = Mint(1);
      }
      foreach (w; 1 .. N + 1) {
        foreach (i; 0 .. N - w + 1) {
          const j = i + w;
          int km = i;
          foreach (k; i .. j) {
            if (C[km] > C[k]) {
              km = k;
            }
          }
          Mint sumL, sumR;
          foreach (k; i .. km + 1) {
            sumL += dp[i][k] * dp[k][km];
          }
          foreach (k; km + 1 .. j + 1) {
            sumR += dp[km + 1][k] * dp[k][j];
          }
          debug {
            writeln(i, " ", j, ": ", km, " ", sumL, " ", sumR);
          }
          dp[i][j] = sumL * sumR;
        }
      }
      writeln(dp[0][N]);
    }
  } catch (EOFException e) {
  }
}


A false witness that speaketh lies!You are given a sequence containing n integers. There is a variable res that is equal to 0 initially. The following process repeats k times.Choose an index from 1 to n uniformly at random. Name it x. Add to res the multiply of all ai's such that 1 ≤ i ≤ n, but i ≠ x. Then, subtract ax by 1.You have to find expected value of res at the end of the process. It can be proved that the expected value of res can be represented as an irreducible fraction . You have to find .

The first line contains two integers n and k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 109) — the number of elements and parameter k that is specified in the statement. The second line contains n space separated integers a1, a2, ..., an (0 ≤ ai ≤ 109).

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

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

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

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

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

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

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

      const invN = Mint(N).inv;

      // \prod_i (A[i] - T)
      auto fs = [Mint(1)];
      foreach (i; 0 .. N) {
        auto gs = new Mint[i + 1 + 1];
        foreach (j; 0 .. i + 1) {
          gs[j + 0] += fs[j] * A[i];
          gs[j + 1] -= fs[j];
        }
        fs = gs;
      }

      auto gsSum = new Mint[N];
      foreach (i; 0 .. N) {
        auto gs = fs.dup;
        foreach_reverse (j; 0 .. N) {
          gs[j + 1] *= -1;
          gs[j] -= gs[j + 1] * A[i];
        }
        assert(!gs[0]);
        gs = gs[1 .. N + 1];
        debug {
          writeln("gs = ", gs);
        }
        gsSum[] += gs[];
      }

      debug {
        const M = N + 5;
        auto hs = new Mint[M];
        foreach (k; 0 .. M) {
          Mint coef = 1;
          foreach (s; 0 .. N) {
            hs[k] += coef * gsSum[s];
            coef *= (k - s);
            coef *= invN;
          }
          hs[k] *= invN;
        }
        writeln("hs = ", hs);
        if (K <= M) {
          writeln("hs[0 .. K].sum = ", hs[0 .. cast(int)(K)].sum);
        }
      }

      // \sum_{k=0}^{K-1} k (k - 1) ... (k - (s - 1))
      Mint ans;
      Mint coef = invN;
      foreach (s; 0 .. N) {
        coef *= (K - s);
        ans += coef / (s + 1) * gsSum[s];
        coef *= invN;
      }
      writeln(ans);

      debug {
        Mint brt;
        Mint eProd;
        foreach (p; 0 .. N^^K) {
          auto as = A.dup;
          Mint res;
          foreach (k; 0 .. K) {
            const i = cast(int)(p / N^^k % N);
            Mint prod = 1;
            foreach (j; 0 .. N) {
              if (j != i) {
                prod *= as[j];
              }
            }
            res += prod;
            --as[i];
          }
          brt += res;
          {
            Mint prod = 1;
            foreach (i; 0 .. N - 1) {
              prod *= as[i];
            }
            eProd += prod;
          }
        }
        brt /= N^^K;
        eProd /= N^^K;
        writeln("brt = ", brt);
        writeln("eProd = ", eProd);

        Mint eProd1;
        foreach (f; 0 .. 1 << (N - 1)) {
          const pop = popcnt(f);
          Mint tmp = (-1)^^pop;
          foreach (i; 0 .. N - 1) {
            if (!(f & 1 << i)) {
              tmp *= A[i];
            }
          }
          foreach (j; 0 .. pop) {
            tmp *= (K - j);
          }
          tmp *= Mint(N)^^(-pop);
          eProd1 += tmp;
        }
        writeln("eProd1 = ", eProd1);
      }
    }
  } catch (EOFException e) {
  }
}


Your favorite shop sells $$$n$$$ Kinder Surprise chocolate eggs. You know that exactly $$$s$$$ stickers and exactly $$$t$$$ toys are placed in $$$n$$$ eggs in total.Each Kinder Surprise can be one of three types:  it can contain a single sticker and no toy;  it can contain a single toy and no sticker;  it can contain both a single sticker and a single toy. But you don't know which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other.What is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy?Note that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$T$$$ lines contain three integers $$$n$$$, $$$s$$$ and $$$t$$$ each ($$$1 \le n \le 10^9$$$, $$$1 \le s, t \le n$$$, $$$s + t \ge n$$$) — the number of eggs, stickers and toys. All queries are independent.

Print $$$T$$$ integers (one number per query) — the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and one toy

NoteIn the first query, we have to take at least $$$6$$$ eggs because there are $$$5$$$ eggs with only toy inside and, in the worst case, we'll buy all of them.In the second query, all eggs have both a sticker and a toy inside, that's why it's enough to buy only one egg.In the third query, we have to buy both eggs: one with a sticker and one with a toy.

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

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

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

void main() {
  auto r = new InputReader;
  immutable nt = r.next!int;
  foreach (tid; 0 .. nt) {
    immutable n = r.next!int;
    immutable s = r.next!int;
    immutable t = r.next!int;
    auto y = n - s;
    auto x = n - t;
    auto z = s - x;
    debug stderr.writefln ("x = %d, y = %d, z = %d", x, y, z);
    writeln (max (x, y) + 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 T = RD!int;
	foreach (i; 0..T)
	{
		auto n = RD!int;
		auto s = RD!int;
		auto t = RD!int;
		auto x = min(s, t);
		writeln(n - x + 1);
	}

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


A number $$$a_2$$$ is said to be the arithmetic mean of two numbers $$$a_1$$$ and $$$a_3$$$, if the following condition holds: $$$a_1 + a_3 = 2\cdot a_2$$$. We define an arithmetic mean deviation of three numbers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ as follows: $$$d(a_1, a_2, a_3) = |a_1 + a_3 - 2 \cdot a_2|$$$.Arithmetic means a lot to Jeevan. He has three numbers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ and he wants to minimize the arithmetic mean deviation $$$d(a_1, a_2, a_3)$$$. To do so, he can perform the following operation any number of times (possibly zero):  Choose $$$i, j$$$ from $$$\{1, 2, 3\}$$$ such that $$$i \ne j$$$ and increment $$$a_i$$$ by $$$1$$$ and decrement $$$a_j$$$ by $$$1$$$ Help Jeevan find out the minimum value of $$$d(a_1, a_2, a_3)$$$ that can be obtained after applying the operation any number of times.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 5000)$$$  — the number of test cases. The first and only line of each test case contains three integers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ $$$(1 \le a_1, a_2, a_3 \le 10^{8})$$$.

For each test case, output the minimum value of $$$d(a_1, a_2, a_3)$$$ that can be obtained after applying the operation any number of times.

NoteNote that after applying a few operations, the values of $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ may become negative.In the first test case, $$$4$$$ is already the Arithmetic Mean of $$$3$$$ and $$$5$$$.$$$d(3, 4, 5) = |3 + 5 - 2 \cdot 4| = 0$$$In the second test case, we can apply the following operation:$$$(2, 2, 6)$$$ $$$\xrightarrow[\text{increment $$$a_2$$$}]{\text{decrement $$$a_1$$$}}$$$ $$$(1, 3, 6)$$$$$$d(1, 3, 6) = |1 + 6 - 2 \cdot 3| = 1$$$It can be proven that answer can not be improved any further.In the third test case, we can apply the following operations:$$$(1, 6, 5)$$$ $$$\xrightarrow[\text{increment $$$a_3$$$}]{\text{decrement $$$a_2$$$}}$$$ $$$(1, 5, 6)$$$ $$$\xrightarrow[\text{increment $$$a_1$$$}]{\text{decrement $$$a_2$$$}}$$$ $$$(2, 4, 6)$$$$$$d(2, 4, 6) = |2 + 6 - 2 \cdot 4| = 0$$$

immutable multi = true;

void solve(int tc)
{
	int sum = readInt!int + readInt!int + readInt!int;
	switch (sum % 3)
	{
	case 0: return writeln(0);
	default: return writeln(1);
	}
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
	{
		popChar;
	}
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

// Cheese-Cracker: cheese-cracker.github.io

void solve(){
    long a = scan;
    long b = scan;
    long c = scan;
    long res = (a + c - 2*b) % 3;
    if(res != 0){
        writeln(1);
    }else{
        writeln(0);
    }
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/**************    *****    That's All Folks!    *****    **************/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math;
string[] tk; T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long, tup = Tuple!(long, "x",  long, "y");


You are given two strings $$$a$$$ and $$$b$$$ consisting of lowercase English letters, both of length $$$n$$$. The characters of both strings have indices from $$$1$$$ to $$$n$$$, inclusive. You are allowed to do the following changes:   Choose any index $$$i$$$ ($$$1 \le i \le n$$$) and swap characters $$$a_i$$$ and $$$b_i$$$;  Choose any index $$$i$$$ ($$$1 \le i \le n$$$) and swap characters $$$a_i$$$ and $$$a_{n - i + 1}$$$;  Choose any index $$$i$$$ ($$$1 \le i \le n$$$) and swap characters $$$b_i$$$ and $$$b_{n - i + 1}$$$. Note that if $$$n$$$ is odd, you are formally allowed to swap $$$a_{\lceil\frac{n}{2}\rceil}$$$ with $$$a_{\lceil\frac{n}{2}\rceil}$$$ (and the same with the string $$$b$$$) but this move is useless. Also you can swap two equal characters but this operation is useless as well.You have to make these strings equal by applying any number of changes described above, in any order. But it is obvious that it may be impossible to make two strings equal by these swaps.In one preprocess move you can replace a character in $$$a$$$ with another character. In other words, in a single preprocess move you can choose any index $$$i$$$ ($$$1 \le i \le n$$$), any character $$$c$$$ and set $$$a_i := c$$$.Your task is to find the minimum number of preprocess moves to apply in such a way that after them you can make strings $$$a$$$ and $$$b$$$ equal by applying some number of changes described in the list above.Note that the number of changes you make after the preprocess moves does not matter. Also note that you cannot apply preprocess moves to the string $$$b$$$ or make any preprocess moves after the first change is made.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$a$$$ and $$$b$$$. The second line contains the string $$$a$$$ consisting of exactly $$$n$$$ lowercase English letters. The third line contains the string $$$b$$$ consisting of exactly $$$n$$$ lowercase English letters.

Print a single integer — the minimum number of preprocess moves to apply before changes, so that it is possible to make the string $$$a$$$ equal to string $$$b$$$ with a sequence of changes from the list above.

NoteIn the first example preprocess moves are as follows: $$$a_1 := $$$'b', $$$a_3 := $$$'c', $$$a_4 := $$$'a' and $$$a_5:=$$$'b'. Afterwards, $$$a = $$$"bbcabba". Then we can obtain equal strings by the following sequence of changes: $$$swap(a_2, b_2)$$$ and $$$swap(a_2, a_6)$$$. There is no way to use fewer than $$$4$$$ preprocess moves before a sequence of changes to make string equal, so the answer in this example is $$$4$$$.In the second example no preprocess moves are required. We can use the following sequence of changes to make $$$a$$$ and $$$b$$$ equal: $$$swap(b_1, b_5)$$$, $$$swap(a_2, a_4)$$$.

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;
    readf("%s", &n);
    readln;

    dchar[][] s;
    auto r = () => readln.chomp.to!(dchar[]);
    s ~= r();
    s ~= r();

    auto ans = 0;
    foreach (i; 0 .. n / 2) {
        auto c = [ s[0][i], s[1][i], s[0][n-1-i], s[1][n-1-i] ].sort();

        debug { c.writeln; }

        if (c[0] == c[1] && c[2] == c[3]) continue;

        auto s0arr = [s[0][i], s[0][n-1-i]].sort();
        auto s1arr = [s[1][i], s[1][n-1-i]].sort();

        debug { writeln(i, ": ", setIntersection(s0arr, s1arr)); }

        if (s[1][i] == s[1][n-1-i] || !setIntersection(s0arr, s1arr).empty()) ans += 1;
        else ans += 2;
    }

    if (n % 2 == 1 && s[0][n/2] != s[1][n/2]) ++ans;

    ans.writeln;
}

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;
    readf("%s", &n);
    readln;

    dchar[][] s;
    auto r = () => readln.chomp.to!(dchar[]);
    s ~= r();
    s ~= r();

    auto ans = 0;
    foreach (i; 0 .. n / 2) {
        auto c = [ s[0][i], s[1][i], s[0][n-1-i], s[1][n-1-i] ].sort();

        debug { c.writeln; }

        if (c[0] == c[1] && c[2] == c[3]) continue;

        if (s[0][i] == s[1][i] || s[0][i] == s[1][n-1-i]
            || s[0][n-1-i] == s[1][i] || s[0][n-1-i] == s[1][n-1-i]
            || s[1][i] == s[1][n-1-i]) ans += 1;
        else ans += 2;
    }

    if (n % 2 == 1 && s[0][n/2] != s[1][n/2]) ++ans;

    ans.writeln;
}

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;
    readf("%s", &n);
    readln;

    dchar[][] s;
    auto r = () => readln.chomp.to!(dchar[]);
    s ~= r();
    s ~= r();

    auto ans = 0;
    foreach (i; 0 .. n / 2) {
        auto c = [ s[0][i], s[1][i], s[0][n-1-i], s[1][n-1-i] ].sort();

        debug { c.writeln; }

        if (c[0] == c[1] && c[2] == c[3]) continue;

        ans += min(2, cast(int)(c[0] != c[1]) + cast(int)(c[1] != c[2]) + cast(int)(c[2] != c[3]));
    }

    if (n % 2 == 1 && s[0][n/2] != s[1][n/2]) ++ans;

    ans.writeln;
}

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;
    readf("%s", &n);
    readln;

    dchar[][] s;
    auto r = () => readln.chomp.to!(dchar[]);
    s ~= r();
    s ~= r();

    auto ans = 0;
    foreach (i; 0 .. n / 2) {
        auto c = [ s[0][i], s[1][i], s[0][n-1-i], s[1][n-1-i] ].sort();

        debug { c.writeln; }

        if (c[0] == c[1] && c[2] == c[3]) continue;

        if (s[0][i] == s[1][i] || s[0][i] == s[1][n-1-i]
            || s[0][n-1-i] == s[1][i] || s[0][n-1-i] == s[1][n-1-i]) ans += 1;
        else ans += 2;
    }

    if (n % 2 == 1 && s[0][n/2] != s[1][n/2]) ++ans;

    ans.writeln;
}


Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks:  Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.  Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman. After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?

The first line contains a single integer n (1 ≤ n ≤ 3·105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the initial group that is given to Toastman.

Print a single integer — the largest possible score.

NoteConsider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions.

module main;

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

void solve(int[] a)
{
    sort(a);
    long ans = 0, sum = 0;
    for (int i = a.length - 1; i >= 0; -- i)
    {
        sum += a[i];
        ans += sum;
    }
    ans -= a[$ - 1];
    ans += sum;
    writefln("%d", ans);
}

int main(string[] args)
{
    int n;
    while (scanf("%d", &n) == 1)
    {
        auto a = new int[n];
        foreach (i, ref v; a)
        {
            scanf("%d", &v);
        }
        solve(a);
    }
    return 0;
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (ref x; a)
		{
			readf (" %d", &x);
		}
		sort !("a < b", SwapStrategy.stable) (a);
		long res;
		foreach (i, c; a)
		{
			res += cast (long) (i + 2) * c;
		}
		res -= a[$ - 1];
		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, 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;
long[] A;

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

		long ans;
		auto q = BinaryHeap!(Array!long)();
		foreach (a; A) {
			ans += a;
			q.insert(a);
		}
		for (; ; ) {
			const a = q.front; q.removeFront;
			if (q.empty) {
				break;
			}
			const b = q.front; q.removeFront;
			ans += a + b;
			q.insert(a + b);
		}
		writeln(ans);
	}
	} catch (EOFException) {}
}

import std.algorithm;
import std.stdio;

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

    auto a = new long[n];
    foreach(i; 0..n) readf(" %s", a[i]);

    a.sort();

    long result = 0;
    foreach(i; 0..n) {
        result += a[i];
    }
    foreach(i; 0..n-1) {
        result += a[i] * (i+1);
    }
    result += a[n-1] * (n-1);
    writeln(result);
}

import std.stdio;
import std.math;
import std.array;
import std.algorithm;

unittest{
  assert(solve([3,1,5]) == 26, "Teste 1");
  assert(solve([10]) == 10, "Teste 1");
}

ulong solve(ulong[] l){
  sort!("a > b")(l);

  auto sum = l.length*l[0];
  foreach(i,x; l[1..$]){
    sum += (l.length-i)*x;
  }

  debug(1) writeln(l[1..$]);
  debug(1) writeln(sum);
  return sum;
}

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

  ulong[] l = new ulong[n];
  for(ulong i = 0; i < n; i++){
    readf("%s ",l.ptr+i);
  }
  writeln(solve(l));
}

import std.algorithm;
import std.stdio;

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

    auto a = new int[n];
    foreach(i; 0..n) readf(" %s", a[i]);

    a.sort();

    long result = 0;
    foreach(i; 0..n) {
        result += a[i];
    }
    foreach(i; 0..n-1) {
        result += a[i] * (i+1);
    }
    result += a[n-1] * (n-1);
    writeln(result);
}


You are given a string $$$s$$$ of even length $$$n$$$. String $$$s$$$ is binary, in other words, consists only of 0's and 1's.String $$$s$$$ has exactly $$$\frac{n}{2}$$$ zeroes and $$$\frac{n}{2}$$$ ones ($$$n$$$ is even).In one operation you can reverse any substring of $$$s$$$. A substring of a string is a contiguous subsequence of that string.What is the minimum number of operations you need to make string $$$s$$$ alternating? A string is alternating if $$$s_i \neq s_{i + 1}$$$ for all $$$i$$$. There are two types of alternating strings in general: 01010101... or 10101010...

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$; $$$n$$$ is even) — the length of string $$$s$$$. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ ($$$s_i \in$$$ {0, 1}). String $$$s$$$ has exactly $$$\frac{n}{2}$$$ zeroes and $$$\frac{n}{2}$$$ ones. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$10^5$$$.

For each test case, print the minimum number of operations to make $$$s$$$ alternating.

NoteIn the first test case, string 10 is already alternating.In the second test case, we can, for example, reverse the last two elements of $$$s$$$ and get: 0110 $$$\rightarrow$$$ 0101.In the third test case, we can, for example, make the following two operations:   11101000 $$$\rightarrow$$$ 10101100;  10101100 $$$\rightarrow$$$ 10101010.

// Vicfred
// https://codeforces.com/contest/1437/problem/B
// string manipulation, greedy
import std.algorithm;
import std.stdio;

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

    long n;
    string s;
    while(t--) {
        readf("%s\n%s\n", &n, &s);
        long ans = n - s.count("10") - s.count("01");
        (ans/2).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);
		auto s = readln.strip;
		int cur = 1;
		foreach (i; 1..n)
		{
			cur += (s[i - 1] == s[i]);
		}
		writeln (cur / 2);
	}
}


Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions:  The coordinates of each point in the set are integers.  For any two points from the set, the distance between them is a non-integer. Consider all points (x, y) which satisfy the inequations: 0 ≤ x ≤ n; 0 ≤ y ≤ m; x + y > 0. Choose their subset of maximum size such that it is also a beautiful set of points.

The single line contains two space-separated integers n and m (1 ≤ n, m ≤ 100).

In the first line print a single integer — the size k of the found beautiful set. In each of the next k lines print a pair of space-separated integers — the x- and y- coordinates, respectively, of a point from the set. If there are several optimal solutions, you may print any of them.

NoteConsider the first sample. The distance between points (0, 1) and (1, 2) equals , between (0, 1) and (2, 0) — , between (1, 2) and (2, 0) — . Thus, these points form a beautiful set. You cannot form a beautiful set with more than three points out of the given points. Note that this is not the only solution.

module sigod.codeforces.p268C;

import std.algorithm : min;
import std.stdio;

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

	solve(n, m);
}

void solve(int n, int m) {
	int min = min(n, m);

	stdout.writeln(min + 1);

	foreach (i; 0 .. min + 1) {
		stdout.writeln(i, " ", min - i);
	}
}

module p268C;

import std.algorithm : min;
import std.array : split;
import std.conv : to;
import std.stdio;
import std.string : strip;

void main() {
	read();

	int n = get!int(0);
	int m = get!int(1);

	solve(n, m);
}

void solve(int n, int m) {
	int min = min(n, m);

	stdout.writeln(min + 1);

	foreach (i; 0 .. min + 1) {
		stdout.writeln(i, " ", min - i);
	}
}

private {
	string[] temp;

	void read() {
		temp = split(strip(stdin.readln()));
	}

	T get(T)(int p) {
		return to!(T)(temp[p]);
	}
}

import std.array : split;
import std.conv : to;
import std.math : abs, sqrt, pow, trunc;
import std.stdio;
import std.string : strip;

private {
	string[] temp;
	int N, M;
}

void main() {
	read();

	N = get!int(0);
	M = get!int(1);

	int[][] max;

	foreach (x; 0 .. N + 1) {
		foreach (y; 0 .. M + 1) {
			if (x + y == 0) continue;

			auto current = p(x, y);

			version (unittest) {
				stdout.writeln("current: ", current);
			}

			if (current.length > max.length) {
				max = current.dup;
			}
		}
	}

	stdout.writeln(max.length);
	foreach (point; max) {
		stdout.writeln(point[0], " ", point[1]);
	}
}

int[][] p(int start_x, int start_y) {
	int x = start_x,
		y = start_y + 1;

	int[][] result = [[start_x, start_y]];

	while (x <= N) {
		if (x != start_x) y = 0;

		while (y <= N) {
			if (isValid(result, x, y)) {
				result ~= [x, y];
			}

			++y;
		}

		++x;
	}

	if (result.length == 1) {
		result.length = 0;
	}

	return result;
}

bool isValid(int[][] array, int x, int y) {
	foreach (point; array) {
		if (!isValidLength(point[0], point[1], x, y))
			return false;
	}

	return true;
}

bool isValidLength(int x1, int y1, int x2, int y2) {
	auto length = sqrt(cast(float) (pow(x2 - x1, 2) + pow(y2 - y1, 2)));

	version (unittest) {
		stdout.writeln("isValidLength: [", x1, ", ", y1, "], [", x2, ", ", y2, "] = ", length);
	}

	return abs(length - trunc(length)) > 0.000000001;
}

void read() {
	temp = split(strip(stdin.readln()));
}

T get(T)(int p) {
	return to!(T)(temp[p]);
}

import std.array : split;
import std.conv : to;
import std.math : abs, sqrt, pow, trunc;
import std.stdio;
import std.string : strip;

private {
	string[] temp;
	int N, M;
}

void main() {
	read();

	N = get!int(0);
	M = get!int(1);

	int[][] max;

	foreach (x; 0 .. N + 1) {
		foreach (y; 0 .. M + 1) {
			if (x + y == 0) continue;

			auto current = p(x, y);

			version (unittest) {
				stdout.writeln("current: ", current);
			}

			if (current.length > max.length) {
				max = current.dup;
			}
		}
	}

	stdout.writeln(max.length);
	foreach (point; max) {
		stdout.writeln(point[0], " ", point[1]);
	}
}

int[][] p(int start_x, int start_y) {
	int x = start_x,
		y = start_y + 1;

	int[][] result = [[start_x, start_y]];

	while (x <= N) {
		if (x != start_x) y = 0;

		while (y <= N) {
			if (isValid(result, x, y)) {
				result ~= [x, y];
			}

			++y;
		}

		++x;
	}

	return result;
}

bool isValid(int[][] array, int x, int y) {
	foreach (point; array) {
		if (!isValidLength(point[0], point[1], x, y))
			return false;
	}

	return true;
}

bool isValidLength(int x1, int y1, int x2, int y2) {
	auto length = sqrt(cast(float) (pow(x2 - x1, 2) + pow(y2 - y1, 2)));

	version (unittest) {
		stdout.writeln("isValidLength: [", x1, ", ", y1, "], [", x2, ", ", y2, "] = ", length);
	}

	return abs(length - trunc(length)) > 0.000000001;
}

void read() {
	temp = split(strip(stdin.readln()));
}

T get(T)(int p) {
	return to!(T)(temp[p]);
}


Monocarp is the coach of the Berland State University programming teams. He decided to compose a problemset for a training session for his teams.Monocarp has $$$n$$$ problems that none of his students have seen yet. The $$$i$$$-th problem has a topic $$$a_i$$$ (an integer from $$$1$$$ to $$$n$$$) and a difficulty $$$b_i$$$ (an integer from $$$1$$$ to $$$n$$$). All problems are different, that is, there are no two tasks that have the same topic and difficulty at the same time.Monocarp decided to select exactly $$$3$$$ problems from $$$n$$$ problems for the problemset. The problems should satisfy at least one of two conditions (possibly, both):  the topics of all three selected problems are different;  the difficulties of all three selected problems are different. Your task is to determine the number of ways to select three problems for the problemset.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 50000$$$) — the number of testcases. The first line of each testcase contains an integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of problems that Monocarp have. In the $$$i$$$-th of the following $$$n$$$ lines, there are two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — the topic and the difficulty of the $$$i$$$-th problem. It is guaranteed that there are no two problems that have the same topic and difficulty at the same time. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

Print the number of ways to select three training problems that meet either of the requirements described in the statement.

NoteIn the first example, you can take the following sets of three problems:  problems $$$1$$$, $$$2$$$, $$$4$$$;  problems $$$1$$$, $$$3$$$, $$$4$$$;  problems $$$2$$$, $$$3$$$, $$$4$$$. Thus, the number of ways is equal to three.

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

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

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

void solve() {
    int N = read!int;
    auto A = new int[N];
    auto B = new int[N];
    foreach (i; 0 .. N) {
        readf("%d %d\n", &A[i], &B[i]);
    }
    long[int] MA, MB; {
        foreach (a; A) {
            MA[a] = MA.get(a, 0) + 1;
        }
        foreach (b; B) {
            MB[b] = MB.get(b, 0) + 1;
        }
    }
    long[Tuple!(int,int)] MAB; {
        foreach (i; 0 .. N) {
            auto k = tuple(A[i], B[i]);
            MAB[k] = MAB.get(k, 0) + 1;
        }
    }

    long dup = 0;
    for (int i = 0; i < N; i++) {
        dup += (MA[A[i]] - 1) * (MB[B[i]] - 1);
    }
    long ans = cast(long)(N) * (N - 1) * (N - 2) / 6 - dup;
    writeln(ans);
}


You have a sequence $$$a_1, a_2, \ldots, a_n$$$ of length $$$n$$$, consisting of integers between $$$1$$$ and $$$m$$$. You also have a string $$$s$$$, consisting of $$$m$$$ characters B.You are going to perform the following $$$n$$$ operations.   At the $$$i$$$-th ($$$1 \le i \le n$$$) operation, you replace either the $$$a_i$$$-th or the $$$(m + 1 - a_i)$$$-th character of $$$s$$$ with A. You can replace the character at any position multiple times through the operations. Find the lexicographically smallest string you can get after these operations.A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ of the same length if and only if in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.

The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2000$$$). The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 50$$$) — the length of the sequence $$$a$$$ and the length of the string $$$s$$$ respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the sequence $$$a$$$.

For each test case, print a string of length $$$m$$$ — the lexicographically smallest string you can get. Each character of the string should be either capital English letter A or capital English letter B.

NoteIn the first test case, the sequence $$$a = [1, 1, 3, 1]$$$. One of the possible solutions is the following.   At the $$$1$$$-st operation, you can replace the $$$1$$$-st character of $$$s$$$ with A. After it, $$$s$$$ becomes ABBBB.  At the $$$2$$$-nd operation, you can replace the $$$5$$$-th character of $$$s$$$ with A (since $$$m+1-a_2=5$$$). After it, $$$s$$$ becomes ABBBA.  At the $$$3$$$-rd operation, you can replace the $$$3$$$-rd character of $$$s$$$ with A. After it, $$$s$$$ becomes ABABA.  At the $$$4$$$-th operation, you can replace the $$$1$$$-st character of $$$s$$$ with A. After it, $$$s$$$ remains equal to ABABA.  The resulting string is ABABA. It is impossible to produce a lexicographically smaller string.In the second test case, you are going to perform only one operation. You can replace either the $$$2$$$-nd character or $$$4$$$-th character of $$$s$$$ with A. You can get strings BABBB and BBBAB after the operation. The string BABBB is the lexicographically smallest among these strings.In the third test case, the only string you can get is A.In the fourth test case, you can replace the $$$1$$$-st and $$$2$$$-nd characters of $$$s$$$ with A to get AABB.In the fifth test case, you can replace the $$$1$$$-st and $$$3$$$-rd characters of $$$s$$$ with A to get ABABBBB.

// cheese-cracker [2022-07-18]

void solve(){
    int n = scan!int;
    int m = scan!int;
    auto arr = scanArray!int;
    dchar[] s;
    for(int i = 0; i < m; ++i) s ~= 'B';
    for(int i = 0; i < n; ++i){
        int minn = min(arr[i], m + 1 - arr[i]) - 1;
        int maxx = max(arr[i], m + 1 - arr[i]) - 1;
        if(s[minn] == 'A'){
            s[maxx] = 'A';
        }else{
            s[minn] = 'A';
        }
    }
    writeln(s);
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm;
import std.container, std.math, std.numeric, std.functional;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }


This problem is a version of problem D from the same contest with some additional constraints and tasks.There are $$$n$$$ candies in a candy box. The type of the $$$i$$$-th candy is $$$a_i$$$ ($$$1 \le a_i \le n$$$). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $$$1$$$ and two candies of type $$$2$$$ is bad).It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.You really like some of the candies and don't want to include them into the gift, but you want to eat them yourself instead. For each candy, a number $$$f_i$$$ is given, which is equal to $$$0$$$ if you really want to keep $$$i$$$-th candy for yourself, or $$$1$$$ if you don't mind including it into your gift. It is possible that two candies of the same type have different values of $$$f_i$$$.You want your gift to be as large as possible, but you don't want to include too many of the candies you want to eat into the gift. So, you want to calculate the maximum possible number of candies that can be included into a gift, and among all ways to choose maximum number of candies, you want to maximize the number of candies having $$$f_i = 1$$$ in your gift.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of candies. Then $$$n$$$ lines follow, each containing two integers $$$a_i$$$ and $$$f_i$$$ ($$$1 \le a_i \le n$$$, $$$0 \le f_i \le 1$$$), where $$$a_i$$$ is the type of the $$$i$$$-th candy, and $$$f_i$$$ denotes whether you want to keep the $$$i$$$-th candy for yourself ($$$0$$$ if you want to keep it, $$$1$$$ if you don't mind giving it away). It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.

For each query print two integers:   the maximum number of candies in a gift you can compose, according to the constraints in the statement;  the maximum number of candies having $$$f_i = 1$$$ in a gift you can compose that contains the maximum possible number of candies.

NoteIn the first query, you can include two candies of type $$$4$$$ and one candy of type $$$5$$$. All of them have $$$f_i = 1$$$ and you don't mind giving them away as part of the gift.

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

  int q;
  rd(q);

  struct P {
    int f, c;
  }

  while (q--) {
    int n;
    rd(n);
    auto freq = new int[](n), cnt1s = new int[](n);
    foreach (i; 0 .. n) {
      int a, t;
      rd(a, t);
      freq[a - 1] += 1;
      if (t == 1) {
        cnt1s[a - 1] += 1;
      }
    }
    auto list = new int[][](n + 1);
    foreach (i; 0 .. n) {
      if (freq[i] > 0) {
        list[freq[i]] ~= cnt1s[i];
      }
    }
    int[] b;
    foreach (i; 0 .. n) {
      if (freq[i] > 0) {
        b ~= freq[i];
      }
    }
    b.sort!"a > b";
    int last = b[0] + 1;
    long ans = 0, sum1s = 0;
    auto rbt = new RedBlackTree!(int, "a>b", true);
    foreach (el; b) {
      auto cur = min(last - 1, el);
      ans += cur;
      foreach (cnt; list[cur]) {
        rbt.insert(cnt);
      }
      auto mx1 = rbt.front;
      sum1s += min(mx1, cur);
      rbt.removeKey(mx1);
      last = cur;
      if (last == 0) {
        break;
      }
    }
    writeln(ans, " ", sum1s);
  }

}

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

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

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

void main(string[] args)
{
  auto q = next!int;
  foreach(qi; q.iota)
    {
      auto n = next!int;
      auto badCnt = new int[](n);
      auto goodCnt = new int[](n);
      auto cnt = new int[](n);
      foreach(i; n.iota)
	{
	  auto ai = next!int - 1;
	  auto fi = next!int;
	  if (fi)
	    goodCnt[ai]++;
	  else
	    badCnt[ai]++;
	  cnt[ai]++;
	}
      auto orderedTypes = iota(n).array.sort!((i, j) => cnt[i] > cnt[j]);
      int[] addSeq;
      auto prev = int.max;
      foreach(type; orderedTypes)
	{
	  prev = min(prev - 1, cnt[type]);
	  if (prev <= 0) break;
	  addSeq ~= prev;
	}
      debug writeln("addSeq = ", addSeq);
      auto avTypes = redBlackTree!((a, b) => a > b, true, Tuple!(int, int))();
      int noBadChosen = 0;
      foreach(add; addSeq)
	{
	  while(!orderedTypes.empty &&
		cnt[orderedTypes.front] >= add)
	    {
	      avTypes.insert(tuple(goodCnt[orderedTypes.front], badCnt[orderedTypes.front]));
	      orderedTypes = orderedTypes[1 .. $];
	    }
	  debug writeln("Trying to add ", add,
			" with avTypes = ", avTypes[]);
	  auto best = avTypes.front;
	  avTypes.removeFront;
	  add -= min(add, best[0]);
	  noBadChosen += min(add, best[1]);
	  add -= min(add, best[1]);
	  assert(add == 0);
	}
      auto res = addSeq.sum;
      writeln(res, " ", res - noBadChosen);
    }
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}

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.range;
import std.numeric;
import std.traits;
import std.variant;
import std.concurrency;

void main(string[] args)
{
  auto q = next!int;
  foreach(qi; q.iota)
    {
      auto n = next!int;
      auto badCnt = new int[](n);
      auto goodCnt = new int[](n);
      auto cnt = new int[](n);
      foreach(i; n.iota)
	{
	  auto ai = next!int - 1;
	  auto fi = next!int;
	  if (fi)
	    goodCnt[ai]++;
	  else
	    badCnt[ai]++;
	  cnt[ai]++;
	}
      auto orderedTypes = iota(n).array.sort!((i, j) => cnt[i] > cnt[j]);
      int[] addSeq;
      auto prev = int.max;
      foreach(type; orderedTypes)
	{
	  prev = min(prev - 1, cnt[type]);
	  if (prev <= 0) break;
	  addSeq ~= prev;
	}
      debug writeln("addSeq = ", addSeq);
      auto avTypes = redBlackTree!((a, b) => a > b, true, Tuple!(int, int))();
      int noBadChosen = 0;
      foreach(add; addSeq)
	{
	  while(!orderedTypes.empty &&
		cnt[orderedTypes.front] >= add)
	    {
	      avTypes.insert(tuple(goodCnt[orderedTypes.front], badCnt[orderedTypes.front]));
	      orderedTypes = orderedTypes[1 .. $];
	    }
	  debug writeln("Trying to add ", add,
			" with avTypes = ", avTypes[]);
	  auto best = avTypes.front;
	  avTypes.removeFront;
	  add -= min(add, best[0]);
	  noBadChosen += max(add, best[1]);
	  add -= min(add, best[1]);
	  assert(add == 0);
	}
      auto res = addSeq.sum;
      writeln(res, " ", res - noBadChosen);
    }
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}


You are given two integers $$$a$$$ and $$$m$$$. Calculate the number of integers $$$x$$$ such that $$$0 \le x < m$$$ and $$$\gcd(a, m) = \gcd(a + x, m)$$$.Note: $$$\gcd(a, b)$$$ is the greatest common divisor of $$$a$$$ and $$$b$$$.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. Each line contains two integers $$$a$$$ and $$$m$$$ ($$$1 \le a < m \le 10^{10}$$$).

Print $$$T$$$ integers — one per test case. For each test case print the number of appropriate $$$x$$$-s.

NoteIn the first test case appropriate $$$x$$$-s are $$$[0, 1, 3, 4, 6, 7]$$$.In the second test case the only appropriate $$$x$$$ is $$$0$$$.

//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;
import std.typecons;
import std.numeric;

final class PrimeTable {
  private:
  BitArray a;
  size_t n;
  public:
  pure nothrow @nogc
  bool isPrime (size_t i) const {
    return (i & 1) ? !a[i>>>1] : (i == 2);
  }
  pure
  int[] primes () const {
    int[] p;
    if (n > 2) {
      p ~= 2;
      p ~= (~a).bitsSet.map! (i => (2 * i + 1).to!int).array;
    }
    return p;
  }
  pure
  this (size_t _n) {
    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;
        }
      }
    }
  }
}

alias Factorization = Tuple!(ulong, "p", uint, "c")[];

pure
Factorization factorizationTrialDivision (ulong x, in int[] primes) in {
  assert (primes.takeExactly (2).equal ([2, 3]));
} body {
  Factorization f;
  foreach (p; chain (primes, iota (primes.back + 2, int.max, 2))) {
    if (p.to!ulong * p > x) {
      break;
    }
    uint c;
    while (!(x % p)) {
      x /= p;
      ++c;
    }
    if (c) {
      f ~= tuple!("p", "c")(p.to!ulong, c);
    }
  }
  if (x > 1) {
    f ~= tuple!("p", "c")(x, 1U);
  }
  return f;
}

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

long test (const ulong a, const ulong m, in int[] p) {
  long g = gcd (a, m);
  long m1 = m / g;
  auto f = factorizationTrialDivision (m1, p);
  immutable l = f.length.to!int;
  long cnt (const long x) {
    immutable t = x / g;
    long res;
    void go (int k, int sign, long x) {
      if (x > t) return;
      if (k < 0) {
        res += sign * (t / x);
      } else {
        go (k - 1, sign, x);
        go (k - 1, -sign, x * f[k].p);
      }
    }
    go (l - 1, 1, 1L);
    return res;
  }
  return cnt (a + m - 1) - cnt (a - 1);
}

int[] primes () {
  auto pt = new PrimeTable (110_000);
  return pt.primes ();
}

void main() {
  auto p = primes ();

  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    immutable a = r.next!ulong;
    immutable m = r.next!ulong;
    writeln (test (a, m, p));
  }
}


Madoka's father just reached $$$1$$$ million subscribers on Mathub! So the website decided to send him a personalized award — The Mathhub's Bit Button! The Bit Button is a rectangular table with $$$n$$$ rows and $$$m$$$ columns with $$$0$$$ or $$$1$$$ in each cell. After exploring the table Madoka found out that: A subrectangle $$$A$$$ is contained in a subrectangle $$$B$$$ if there's no cell contained in $$$A$$$ but not contained in $$$B$$$. Two subrectangles intersect if there is a cell contained in both of them. A subrectangle is called black if there's no cell with value $$$0$$$ inside it. A subrectangle is called nice if it's black and it's not contained in another black subrectangle. The table is called elegant if there are no two nice intersecting subrectangles.For example, in the first illustration the red subrectangle is nice, but in the second one it's not, because it's contained in the purple subrectangle.  Help Madoka to determine whether the table is elegant.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two positive integers $$$n, m$$$ ($$$1 \le n, m \le 100$$$). The next $$$n$$$ lines contain strings of length $$$m$$$ consisting of zeros and ones — the description of the table. It is guaranteed that the sum of the values of $$$n$$$ and the sum of the values of $$$m$$$ for all test cases do not exceed $$$777$$$.

For each test case print "YES" if its table is elegant or print "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).

NoteIn the second test case the table is not elegant, because the red and the purple subrectangles are nice and intersect.   In the fourth test case the table is not elegant, because the red and the purple subrectangles are nice and intersect.

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)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto a = new int [] [n];
		foreach (ref c; a)
		{
			c = readln.strip.map !(q{int (a) - '0'}).array;
		}

		bool ok = true;
		foreach (row; 1..n)
		{
			foreach (col; 1..m)
			{
				if (a[row - 1][col - 1] + a[row - 1][col] +
				    a[row][col - 1] + a[row][col] == 3)
				{
					ok = false;
				}
			}
		}
		writeln (ok ? "YES" : "NO");
	}
}


Roma found a new character in the game "World of Darkraft - 2". In this game the character fights monsters, finds the more and more advanced stuff that lets him fight stronger monsters.The character can equip himself with k distinct types of items. Power of each item depends on its level (positive integer number). Initially the character has one 1-level item of each of the k types.After the victory over the monster the character finds exactly one new randomly generated item. The generation process looks as follows. Firstly the type of the item is defined; each of the k types has the same probability. Then the level of the new item is defined. Let's assume that the level of player's item of the chosen type is equal to t at the moment. Level of the new item will be chosen uniformly among integers from segment [1; t + 1].From the new item and the current player's item of the same type Roma chooses the best one (i.e. the one with greater level) and equips it (if both of them has the same level Roma choses any). The remaining item is sold for coins. Roma sells an item of level x of any type for x coins.Help Roma determine the expected number of earned coins after the victory over n monsters.

The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 100).

Print a real number — expected number of earned coins after victory over n monsters. The answer is considered correct if its relative or absolute error doesn't exceed 10 - 9.

import std.stdio, std.getopt, std.random, std.range, std.string, std.conv;
import std.algorithm, std.container;

const ML = 700;
double[][] dp;
bool[][] used;
int k;
double solve(int l, int n) {
    if (n < 0) return 0;
    if (l >= ML) return 0;
    if (used[l][n]) return dp[l][n];
    used[l][n] = true;
    double res = 0;
    double hp = 1.0/(l+1);
    res += hp*(l + solve(l+1, n-1));
    res += (1-hp)*((l+1.0)/2 + solve(l, n-1));
    res /= k;
    res += (1-1.0/k)*solve(l, n-1);
    return (dp[l][n] = res);
}

int main() {
    int n;
    readf("%d %d\n", &n, &k);
    auto dp = new double[ML+1];
    dp[] = 0;
    foreach (i; 1..n+1) {
        foreach (j; 1..ML) {
            double res = 0;
            double hp = 1.0/(j+1);
            res += hp*(j + dp[j+1]);
            res += (1-hp)*((j+1.0)/2 + dp[j]);
            res /= k;
            res += (1-1.0/k)*dp[j];
            dp[j] = res;
        }
    }
    writef("%.20f\n", dp[1]*k);
	return 0;
}

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

immutable LIM = 1000;

int N, K;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		K = readInt;

		real[] pa = new real[LIM];
		real[] pb = new real[LIM];
		real[] pc = new real[LIM];
		foreach (j; 1 .. LIM - 1) {
			pa[j] = 1.0 - 1.0 / K / (j + 1);
			pb[j] = 1.0 / K - 1.0 / K / (j + 1);
			pc[j] = 1.0 / K / (j + 1);
		}

		real[] dp = new real[LIM];
		dp[] = 0.0;
		foreach (i; 0 .. N) {
			foreach (j; 1 .. LIM - 1) {
				// dp[j] = (1.0 - 1.0 / K) * dp[j] + (1.0 / K - 1.0 / K / (j + 1)) * ((j + 1) / 2.0 + dp[j]) + (1.0 / K / (j + 1)) * (j + dp[j + 1]);
				dp[j] = pa[j] * dp[j] + pb[j] * ((j + 1) / 2.0) + pc[j] * (j + dp[j + 1]);
			}
		}
debug{
writeln(dp);
}
		const ans = dp[1] * K;
		writefln("%.10f", ans);
	}
	} catch (EOFException) {}
}


You are given a rectangular grid of lattice points from (0, 0) to (n, m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.A polyline defined by points p1, p2, p3, p4 consists of the line segments p1 p2, p2 p3, p3 p4, and its length is the sum of the lengths of the individual line segments.

The only line of the input contains two integers n and m (0 ≤ n, m ≤ 1000). It is guaranteed that grid contains at least 4 different points.

Print 4 lines with two integers per line separated by space — coordinates of points p1, p2, p3, p4 in order which represent the longest possible polyline. Judge program compares your answer and jury's answer with 10 - 6 precision.

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;

alias Point = Tuple !(int, "x", int, "y");

real len (Point [] p)
{
	real res = 0.0;
	foreach (i; 1..p.length)
	{
		res += hypot (p[i - 1].y - p[i].y, p[i - 1].x - p[i].x);
	}
	return res;
}

void main ()
{
	int n;
	int m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		Point [] a;
		foreach (i; 0..n + 1)
		{
			foreach (j; 0..m + 1)
			{
				if ((abs (0 - i) <= 2 || abs (n - i) <= 2) &&
				    (abs (0 - j) <= 2 || abs (m - j) <= 2))
				{
					a ~= Point (i, j);
				}
			}
		}

		real res = 0.0;
		Point [] ans;
		foreach (b; a)
		{
			foreach (c; a)
			{
				if (c == b)
				{
					continue;
				}
				foreach (d; a)
				{
					if (d == b || d == c)
					{
						continue;
					}
					foreach (e; a)
					{
						if (e == b || e == c || e == d)
						{
							continue;
						}
						Point [] cur = [b, c, d, e];
						real temp = len (cur);
						if (res < temp)
						{
							res = temp;
							ans = cur;
						}
					}
				}
			}
		}

		foreach (f; ans)
		{
			writeln (f.x, ' ', f.y);
		}
	}
}


There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.

The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.

In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.

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

struct Point
{
	int x;
	int y;
	this(int _x, int _y)
	{
		this.x = _x;
		this.y = _y;
	}
};

auto search(int len, int bound)
{
	Point[] ret;
	foreach (int i; 1 .. bound)
	{
		foreach (int j; i .. bound)
		{
			double d = i * i + j * j;
			double s = sqrt(d);
			if (s == len)
			{
				ret ~= Point(i, j);
				break;
			}
			else if (s > len)
			{
				break;
			}
		}
	}
	if (ret.length == 0)
	{
		ret ~= Point(1 << 30, 1 << 30);
	}
	return ret;
}

int cross(ref Point p0, ref Point p1)
{
	return (p0.x * p1.x + p0.y * p1.y);
}

void change(ref Point p)
{
	p.x ^= p.y;
	p.y ^= p.x;
	p.x ^= p.y;
}

void output(ref Point pa, ref Point pb)
{
	printf("YES\n");
	printf("0 0\n");
	printf("%d %d\n", pa.x, pa.y);
	printf("%d %d\n", pb.x, pb.y);
}

bool check(Point[] arr)
{
	if (arr.length == 0 || arr[0].x == 1 << 30)
	{
		return false;
	}
	return true;
}

void print(Point[] arr)
{
	printf("%d\n", arr);
	foreach (ref Point p; arr)
	{
		printf("%d %d\n", p.x, p.y);
	}
}

bool judge(ref Point p0, Point[] arr)
{
	foreach (ref Point p1; arr)
	{
		//printf("try (%d %d) (%d %d)\n", p0.x, p0.y, p1.x, p1.y);
		if (p0.x * p1.x == p0.y * p1.y)
		{
			if (-p0.x != p1.x && p0.y != p1.y)
			{
				p0.x *= -1;
				output(p0, p1);
				return true;
			}
			if (-p0.y != p1.y && p0.x != p1.x)
			{
				p0.y *= -1;
				output(p0, p1);
				return true;
			}
		}
	}
	return false;
}

void solve(int a, int b)
{
	auto bound = a > b ? a : b;
	auto pa = search(a, bound);
	if (check(pa) == false)
	{
		printf("NO\n");
		return;
	}
	auto pb = search(b, bound);
	if (check(pb) == false)
	{
		printf("NO\n");
		return;
	}
	//print(pa);
	//print(pb);
	foreach (ref Point p0; pa)
	{
		if (judge(p0, pb) == true)
		{
			return;
		}
		change(p0);
		if (judge(p0, pb) == true)
		{
			return;
		}
	}
	printf("NO\n");
}
/*
void test()
{
	int[] cnt = new int[1001];
	foreach (int i; 1 .. 1001)
	{
		foreach (int j; i .. 1001)
		{
			double d = i * i + j * j;
			double s = sqrt(d);
			if (s > 1000)
			{
				break;
			}
			int t = to!int(s);
			if (t == s)
			{
				++ cnt[t];
			}
		}
	}
	foreach (int i; 1 .. 1001)
	{
		if (cnt[i] > 1)
		{
			printf("%d %d\n", i, cnt[i]);
		}
	}
}
*/
void main(string[] args)
{
	//test();
	int a, b;
	while (scanf("%d%d", &a, &b) == 2)
	{
		solve(a, b);
	}
}

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 a, b;
main_loop:
	while (readf (" %s %s", &a, &b) > 0)
	{
		foreach (p; 1..a)
		{
			int q = a * a - p * p;
			if (q <= 0)
			{
				continue;
			}
			q = to !(int) (sqrt (to !(double) (q)));
			if (p * p + q * q != a * a)
			{
				continue;
			}
			int u = p * b;
			int v = q * b;
			if (u % a != 0 || v % a != 0 || p * a == v)
			{
				continue;
			}
			u /= a;
			v /= a;
			writeln ("YES");
			writeln (0, ' ', 0);
			writeln (p, ' ', q);
			writeln (v, ' ', -u);
			continue main_loop;
		}
		writeln ("NO");
	}
}

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

struct Point
{
    int x;
    int y;
    this(int _x, int _y)
    {
        this.x = _x;
        this.y = _y;
    }
};

auto search(int len, int bound)
{
    Point[] ret;
    foreach (int i; 1 .. bound)
    {
        foreach (int j; i .. bound)
        {
            double d = i * i + j * j;
            double s = sqrt(d);
            if (s == len)
            {
                ret ~= Point(i, j);
                break;
            }
            else if (s > len)
            {
                break;
            }
        }
    }
    if (ret.length == 0)
    {
        ret ~= Point(1 << 30, 1 << 30);
    }
    return ret;
}

int cross(ref Point p0, ref Point p1)
{
    return (p0.x * p1.x + p0.y * p1.y);
}

void change(ref Point p)
{
    p.x ^= p.y;
    p.y ^= p.x;
    p.x ^= p.y;
}

void output(ref Point pa, ref Point pb)
{
    printf("YES\n");
    printf("0 0\n");
    printf("%d %d\n", pa.x, pa.y);
    printf("%d %d\n", pb.x, pb.y);
}

bool check(Point[] arr)
{
    if (arr.length == 0 || arr[0].x == 1 << 30)
    {
        return false;
    }
    return true;
}

void solve(int a, int b)
{
    auto bound = a > b ? a : b;
    auto pa = search(a, bound);
    if (check(pa) == false)
    {
        printf("NO\n");
        return;
    }
    auto pb = search(b, bound);
    if (check(pb) == false)
    {
        printf("NO\n");
        return;
    }
    foreach (ref Point p0; pa)
    {
        p0.x = -p0.x;
        foreach (ref Point p1; pb)
        {
            if (cross(p0, p1) == 0)
            {
                output(p0, p1);
                return;
            }
        }
        change(p0);
        foreach (ref Point p1; pb)
        {
            if (cross(p0, p1) == 0)
            {
                output(p0, p1);
                return;
            }
        }
    }
    printf("NO\n");
}

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

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

struct Point
{
	int x;
	int y;
	this(int _x, int _y)
	{
		this.x = _x;
		this.y = _y;
	}
};

auto search(int len, int bound)
{
	Point[] ret;
	foreach (int i; 1 .. bound)
	{
		foreach (int j; i .. bound)
		{
			double d = i * i + j * j;
			double s = sqrt(d);
			if (s == len)
			{
				ret ~= Point(i, j);
				break;
			}
			else if (s > len)
			{
				break;
			}
		}
	}
	if (ret.length == 0)
	{
		ret ~= Point(1 << 30, 1 << 30);
	}
	return ret;
}

int cross(ref Point p0, ref Point p1)
{
	return (p0.x * p1.x + p0.y * p1.y);
}

void change(ref Point p)
{
	p.x ^= p.y;
	p.y ^= p.x;
	p.x ^= p.y;
}

void output(ref Point pa, ref Point pb)
{
	printf("YES\n");
	printf("0 0\n");
	printf("%d %d\n", pa.x, pa.y);
	printf("%d %d\n", pb.x, pb.y);
}

bool check(Point[] arr)
{
	if (arr.length == 0 || arr[0].x == 1 << 30)
	{
		return false;
	}
	return true;
}

void print(Point[] arr)
{
	printf("%d\n", arr);
	foreach (ref Point p; arr)
	{
		printf("%d %d\n", p.x, p.y);
	}
}

void solve(int a, int b)
{
	auto bound = a > b ? a : b;
	auto pa = search(a, bound);
	if (check(pa) == false)
	{
		printf("NO\n");
		return;
	}
	auto pb = search(b, bound);
	if (check(pb) == false)
	{
		printf("NO\n");
		return;
	}
	//print(pa);
	//print(pb);
	foreach (ref Point p0; pa)
	{
		p0.x = -p0.x;
		foreach (ref Point p1; pb)
		{
			if (p0.x != p1.x && p0.y != p1.y && cross(p0, p1) == 0)
			{
				output(p0, p1);
				return;
			}
		}
		change(p0);
		foreach (ref Point p1; pb)
		{
			if (p0.x != p1.x && p0.y != p1.y && cross(p0, p1) == 0)
			{
				output(p0, p1);
				return;
			}
		}
	}
	printf("NO\n");
}
/*
void test()
{
	int[] cnt = new int[1001];
	foreach (int i; 1 .. 1001)
	{
		foreach (int j; i .. 1001)
		{
			double d = i * i + j * j;
			double s = sqrt(d);
			if (s > 1000)
			{
				break;
			}
			int t = to!int(s);
			if (t == s)
			{
				++ cnt[t];
			}
		}
	}
	foreach (int i; 1 .. 1001)
	{
		if (cnt[i] > 1)
		{
			printf("%d %d\n", i, cnt[i]);
		}
	}
}
*/
void main(string[] args)
{
	//test();
	int a, b;
	while (scanf("%d%d", &a, &b) == 2)
	{
		solve(a, b);
	}
}

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

struct Point
{
    int x;
    int y;
    this(int _x, int _y)
    {
        this.x = _x;
        this.y = _y;
    }
};

auto search(int len, int bound)
{
    foreach (int i; 1 .. bound)
    {
        foreach (int j; i .. bound)
        {
            double d = i * i + j * j;
            double s = sqrt(d);
            if (s == len)
            {
                return Point(i, j);
            }
            else if (s > len)
            {
                break;
            }
        }
    }
    return Point(1 << 30, 1 << 30);
}

int cross(ref Point p0, ref Point p1)
{
    return (p0.x * p1.x + p0.y * p1.y);
}

void change(ref Point p)
{
    p.x ^= p.y;
    p.y ^= p.x;
    p.x ^= p.y;
}

void output(ref Point pa, ref Point pb)
{
    printf("YES\n");
    printf("0 0\n");
    printf("%d %d\n", pa.x, pa.y);
    printf("%d %d\n", pb.x, pb.y);
}

void solve(int a, int b)
{
    auto bound = a > b ? a : b;
    auto pa = search(a, bound);
    if (pa.x == 1 << 30)
    {
        printf("NO\n");
        return;
    }
    auto pb = search(b, bound);
    if (pb.x == 1 << 30)
    {
        printf("NO\n");
        return;
    }
    pb.x = -pb.x;
    if (cross(pa, pb) == 0)
    {
        output(pa, pb);
        return;
    }
    change(pb);
    if (cross(pa, pb) == 0)
    {
        output(pa, pb);
        return;
    }
    printf("NO\n");
}

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

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 a, b;
main_loop:
	while (readf (" %s %s", &a, &b) > 0)
	{
		foreach (p; 1..a)
		{
			int q = a * a - p * p;
			if (q <= 0)
			{
				continue;
			}
			q = to !(int) (sqrt (to !(double) (q)));
			if (p * p + q * q != a * a)
			{
				continue;
			}
			int u = p * b;
			int v = q * b;
			if (u % a != 0 || v % a != 0)
			{
				continue;
			}
			u /= a;
			v /= a;
			writeln ("YES");
			writeln (0, ' ', 0);
			writeln (p, ' ', q);
			writeln (v, ' ', -u);
			continue main_loop;
		}
		writeln ("NO");
	}
}