Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns — from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (xk, yk).The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like.  Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!

The first line of the input contains fix integers n, m, x, y, z, p (1 ≤ n, m ≤ 109; 0 ≤ x, y, z ≤ 109; 1 ≤ p ≤ 105). Each of the following p lines contains two integers xk, yk (1 ≤ xk ≤ n; 1 ≤ yk ≤ m) — the initial coordinates of the k-th candy. Two candies can lie on the same cell.

For each of the p candies, print on a single line its space-separated new coordinates.

NoteJust for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix:QWER      REWQ ASDF  ->  FDSAZXCV      VCXZ

import std.stdio;
import std.conv;

int n, m, x, y, z, p, t;

struct coord {
    int x, y;
}

void transform(ref coord c) {
    int n_t = n, m_t = m;
    for (int i = 0; i < x; i++) {
        t = c.x; c.x = c.y; c.y = n_t-t+1;
        n_t ^= m_t; m_t ^= n_t; n_t ^= m_t;
    }
    if (y)
        c.y = m_t-c.y+1;

    for (int i = 0; i < z; i++) {
        t = c.y; c.y = c.x; c.x = m_t-t+1;
        n_t ^= m_t; m_t ^= n_t; n_t ^= m_t;
    }
}

void main() {
    string str = "";
    scanf("%d %d %d %d %d %d", &n, &m, &x, &y, &z, &p); coord c; x %= 4; y %=2; z %= 4;
    while (p--) {
        scanf("%d %d", &c.x, &c.y); transform(c); str ~= to!string(c.x) ~ ' ' ~ to!string(c.y) ~ '\n';
    }
    write(str);
}

import std.stdio;

int n, m, x, y, z, p, t;

struct coord {
    int x, y;
}

void transform(ref coord c) {
    int n_t = n, m_t = m;
    for (int i = 0; i < x; i++) {
        t = c.x; c.x = c.y; c.y = n_t-t+1;
        n_t ^= m_t; m_t ^= n_t; n_t ^= m_t;
    }
    if (y)
        c.y = m_t-c.y+1;

    for (int i = 0; i < z; i++) {
        t = c.y; c.y = c.x; c.x = m_t-t+1;
        n_t ^= m_t; m_t ^= n_t; n_t ^= m_t;
    }
}

void main() {
    scanf("%d %d %d %d %d %d", &n, &m, &x, &y, &z, &p); coord c; x %= 4; y %=2; z %= 4;
    while (p--) {
        scanf("%d %d", &c.x, &c.y); transform(c); writeln(c.x, ' ', c.y);
    }
}

import std.stdio;

int n, m, x, y, z, p, t;

struct coord {
    int x, y;
}

void transform(ref coord c) {
    int n_t = n, m_t = m;
    for (int i = 0; i < x; i++) {
        t = c.x; c.x = c.y; c.y = n_t-t+1;
        n_t ^= m_t; m_t ^= n_t; n_t ^= m_t;
    }
    if (y)
        c.y = m_t-c.y+1;

    for (int i = 0; i < z; i++) {
        t = c.y; c.y = c.x; c.x = n_t-t+1;
        n_t ^= m_t; m_t ^= n_t; n_t ^= m_t;
    }
}

void main() {
    scanf("%d %d %d %d %d %d", &n, &m, &x, &y, &z, &p); coord c; x %= 4; y %=2; z %= 4;
    while (p--) {
        scanf("%d %d", &c.x, &c.y); transform(c); writeln(c.x, ' ', c.y);
    }
}


Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare. Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places.You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.

The first line contain integer t (1 ≤ t ≤ 20), where t is the number of races. After that all races are described one by one. Every race description start with an integer n (1 ≤ n ≤ 50) on a line of itself, where n is the number of clasified drivers in the given race. After that n lines follow with the classification for the race, each containing the name of a driver. The names of drivers are given in order from the first to the last place. The name of the driver consists of lowercase and uppercase English letters and has length at most 50 characters. Comparing of names should be case-sensetive.

Your output should contain exactly two line. On the first line is the name of the champion according to the original rule, and on the second line the name of the champion according to the alternative rule.

3
3
Hamilton
Vettel
Webber
2
Webber
Vettel
2
Hamilton
Vettel

2
7
Prost
Surtees
Nakajima
Schumacher
Button
DeLaRosa
Buemi
8
Alonso
Prost
NinoFarina
JimClark
DeLaRosa
Nakajima
Patrese
Surtees

NoteIt is not guaranteed that the same drivers participate in all races. For the championship consider every driver that has participated in at least one race. The total number of drivers during the whole season is not more then 50.


Bob is playing a game of Spaceship Solitaire. The goal of this game is to build a spaceship. In order to do this, he first needs to accumulate enough resources for the construction. There are $$$n$$$ types of resources, numbered $$$1$$$ through $$$n$$$. Bob needs at least $$$a_i$$$ pieces of the $$$i$$$-th resource to build the spaceship. The number $$$a_i$$$ is called the goal for resource $$$i$$$.Each resource takes $$$1$$$ turn to produce and in each turn only one resource can be produced. However, there are certain milestones that speed up production. Every milestone is a triple $$$(s_j, t_j, u_j)$$$, meaning that as soon as Bob has $$$t_j$$$ units of the resource $$$s_j$$$, he receives one unit of the resource $$$u_j$$$ for free, without him needing to spend a turn. It is possible that getting this free resource allows Bob to claim reward for another milestone. This way, he can obtain a large number of resources in a single turn.The game is constructed in such a way that there are never two milestones that have the same $$$s_j$$$ and $$$t_j$$$, that is, the award for reaching $$$t_j$$$ units of resource $$$s_j$$$ is at most one additional resource.A bonus is never awarded for $$$0$$$ of any resource, neither for reaching the goal $$$a_i$$$ nor for going past the goal — formally, for every milestone $$$0 < t_j < a_{s_j}$$$.A bonus for reaching certain amount of a resource can be the resource itself, that is, $$$s_j = u_j$$$.Initially there are no milestones. You are to process $$$q$$$ updates, each of which adds, removes or modifies a milestone. After every update, output the minimum number of turns needed to finish the game, that is, to accumulate at least $$$a_i$$$ of $$$i$$$-th resource for each $$$i \in [1, n]$$$.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of types of resources. The second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$), the $$$i$$$-th of which is the goal for the $$$i$$$-th resource. The third line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$) — the number of updates to the game milestones. Then $$$q$$$ lines follow, the $$$j$$$-th of which contains three space separated integers $$$s_j$$$, $$$t_j$$$, $$$u_j$$$ ($$$1 \leq s_j \leq n$$$, $$$1 \leq t_j < a_{s_j}$$$, $$$0 \leq u_j \leq n$$$). For each triple, perform the following actions:    First, if there is already a milestone for obtaining $$$t_j$$$ units of resource $$$s_j$$$, it is removed.  If $$$u_j = 0$$$, no new milestone is added.  If $$$u_j \neq 0$$$, add the following milestone: "For reaching $$$t_j$$$ units of resource $$$s_j$$$, gain one free piece of $$$u_j$$$."  Output the minimum number of turns needed to win the game.

Output $$$q$$$ lines, each consisting of a single integer, the $$$i$$$-th represents the answer after the $$$i$$$-th update.

NoteAfter the first update, the optimal strategy is as follows. First produce $$$2$$$ once, which gives a free resource $$$1$$$. Then, produce $$$2$$$ twice and $$$1$$$ once, for a total of four turns.After the second update, the optimal strategy is to produce $$$2$$$ three times — the first two times a single unit of resource $$$1$$$ is also granted.After the third update, the game is won as follows.   First produce $$$2$$$ once. This gives a free unit of $$$1$$$. This gives additional bonus of resource $$$1$$$. After the first turn, the number of resources is thus $$$[2, 1]$$$.  Next, produce resource $$$2$$$ again, which gives another unit of $$$1$$$.  After this, produce one more unit of $$$2$$$. The final count of resources is $$$[3, 3]$$$, and three turns are needed to reach this situation. Notice that we have more of resource $$$1$$$ than its goal, which is of no use.

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto q = readln.strip.to !(int);
		alias Pair = Tuple !(int, q{num}, int, q{kind});
		int [Pair] b;
		long total = sum (a, 0L);
		auto surplus = new int [n];

		void sub (const ref Pair cur)
		{
			if (cur !in b)
			{
				return;
			}
			auto kind = b[cur];
			b.remove (cur);
			surplus[kind] -= 1;
			if (surplus[kind] < a[kind])
			{
				total += 1;
			}
		}

		void add (const ref Pair cur, int kind)
		{
			if (kind < 0)
			{
				return;
			}
			if (surplus[kind] < a[kind])
			{
				total -= 1;
			}
			b[cur] = kind;
			surplus[kind] += 1;
		}

		foreach (r; 0..q)
		{
			int s;
			int t;
			int u;
			readf !(" %s %s %s") (s, t, u);
			t -= 1;
			u -= 1;
			auto cur = Pair (s, t);
			sub (cur);
			add (cur, u);
			writeln (total);
		}
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }
      const Q = readInt();
      auto S = new int[Q];
      auto T = new int[Q];
      auto U = new int[Q];
      foreach (q; 0 .. Q) {
        S[q] = readInt() - 1;
        T[q] = readInt();
        U[q] = readInt() - 1;
      }

      auto us = new int[int][N];
      long now = A.sum;
      auto cs = new long[N];
      void add(int s, int t, int u) {
        if (cs[u] < A[u]) {
          --now;
        }
        ++cs[u];
        us[s][t] = u;
      }
      void remove(int s, int t) {
        const u = us[s][t];
        --cs[u];
        if (cs[u] < A[u]) {
          ++now;
        }
        us[s][t] = -1;
      }

      foreach (q; 0 .. Q) {
        if (T[q] in us[S[q]] && us[S[q]][T[q]] != -1) {
          remove(S[q], T[q]);
        }
        if (U[q] != -1) {
          add(S[q], T[q], U[q]);
        }
        writeln(now);
      }
    }
  } catch (EOFException e) {
  }
}


There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai.The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is.The airport manager asked you to count for each of n walruses in the queue his displeasure.

The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109). Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one.

Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus.

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

int minPow(int x) {
    int res = 1;
    while (res < x)
        res <<= 1;
    return res;
}

int[] unique(int[] a) {
    int[] res = [a[0]];
    foreach (i; 1 .. a.length) {
        if (a[i] != a[i - 1])
            res ~= a[i];
    }
    return res;
}

struct SegmentTree {
    int[] tree, left, right;

    this(int n) {
        int size = minPow(2 * n);
        tree = new int[size];
        left = new int[size];
        right = new int[size];
        precalc(1, 0, n - 1);
    }

    void precalc(int v, int l, int r) {
        left[v] = l;
        right[v] = r;
        tree[v] = int.max;
        if (l == r)
            return;

        int m = (l + r) / 2;
        precalc(2 * v, l, m);
        precalc(2 * v + 1, m + 1, r);
    }

    int get(int v, int l, int r) {
        if (l <= left[v] && right[v] <= r) {
            return tree[v];
        }

        if (l > right[v] || r < left[v])
            return int.max;

        return min(get(2 * v, l, r), get(2 * v + 1, l, r));
    }

    void update(int v, int pos, int val) {
        if (pos == left[v] && left[v] == right[v]) {
            if (tree[v] == int.max)
                tree[v] = val;
            return;
        }

        if (pos < left[v] || pos > right[v])
            return;

        update(2 * v, pos, val);
        update(2 * v + 1, pos, val);
        tree[v] = min(tree[2 * v], tree[2 * v + 1]);
    }
};

void main() {
    debug stdin = File("input.txt", "r");

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

    int[] a = new int[n];
    foreach (ref x; a) {
        readf(" %s", &x);
    }

    bool cmp(int x, int y) {
        return x > y;
    }

    int[] b = a.dup;
    sort!(cmp)(b);
    b = unique(b);
    auto r = assumeSorted!(cmp)(b);

    reverse(a);

    int[] ans = new int[n];
    auto tree = SegmentTree(cast(int) b.length);
    foreach (int i, x; a) {
        int pos = cast(int) r.lowerBound(x).length;
        int minPos = tree.get(1, pos + 1, cast (int)(b.length) - 1);
        if (minPos != int.max) {
            ans[n - i - 1] = i - minPos - 1;
        } else {
            ans[n - i - 1] = -1;
        }
        tree.update(1, pos, i);
    }

    foreach (x; ans) {
        write(x, " ");
    }
    writeln();
}

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

int minPow(int x) {
    int res = 1;
    while (res < x)
        res <<= 1;
    return res;
}

int[] unique(int[] a) {
    int[] res = [a[0]];
    foreach (i; 1 .. a.length) {
        if (a[i] != a[i - 1])
            res ~= a[i];
    }
    return res;
}

struct SegmentTree {
    int[] tree, left, right;

    this(int n) {
        int size = minPow(2 * n);
        tree = new int[size];
        left = new int[size];
        right = new int[size];
        precalc(1, 0, n - 1);
    }

    void precalc(int v, int l, int r) {
        left[v] = l;
        right[v] = r;
        tree[v] = int.max;
        if (l == r)
            return;

        int m = (l + r) / 2;
        precalc(2 * v, l, m);
        precalc(2 * v + 1, m + 1, r);
    }

    int get(int v, int l, int r) {
        if (l <= left[v] && right[v] <= r) {
            return tree[v];
        }

        if (l > right[v] || r < left[v])
            return int.max;

        return min(get(2 * v, l, r), get(2 * v + 1, l, r));
    }

    void update(int v, int pos, int val) {
        if (pos == left[v] && left[v] == right[v]) {
            tree[v] = val;
            return;
        }

        if (pos < left[v] || pos > right[v])
            return;

        update(2 * v, pos, val);
        update(2 * v + 1, pos, val);
        tree[v] = min(tree[2 * v], tree[2 * v + 1]);
    }
};

void main() {
    debug stdin = File("input.txt", "r");

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

    int[] a = new int[n];
    foreach (ref x; a) {
        readf(" %s", &x);
    }

    bool cmp(int x, int y) {
        return x > y;
    }

    int[] b = a.dup;
    sort!(cmp)(b);
    b = unique(b);
    auto r = assumeSorted!(cmp)(b);

    reverse(a);

    int[] ans = new int[n];
    auto tree = SegmentTree(cast(int) b.length);
    foreach (int i, x; a) {
        int pos = cast(int) r.lowerBound(x).length;
        int minPos = tree.get(1, pos + 1, cast (int)(b.length) - 1);
        if (minPos != int.max) {
            ans[n - i - 1] = i - minPos - 1;
        } else {
            ans[n - i - 1] = -1;
        }
        tree.update(1, pos, i);
    }

    foreach (x; ans) {
        write(x, " ");
    }
    writeln();
}


This is an interactive problem.Alice and Bob are playing a game. There is $$$n\times n$$$ grid, initially empty. We refer to the cell in row $$$i$$$ and column $$$j$$$ by $$$(i, j)$$$ for $$$1\le i, j\le n$$$. There is an infinite supply of tokens that come in $$$3$$$ colors labelled $$$1$$$, $$$2$$$, and $$$3$$$.The game proceeds with turns as follows. Each turn begins with Alice naming one of the three colors, let's call it $$$a$$$. Then, Bob chooses a color $$$b\ne a$$$, chooses an empty cell, and places a token of color $$$b$$$ on that cell.We say that there is a conflict if there exist two adjacent cells containing tokens of the same color. Two cells are considered adjacent if they share a common edge.If at any moment there is a conflict, Alice wins. Otherwise, if $$$n^2$$$ turns are completed (so that the grid becomes full) without any conflicts, Bob wins.We have a proof that Bob has a winning strategy. Play the game as Bob and win.The interactor is adaptive. That is, Alice's color choices can depend on Bob's previous moves.

NoteThe final grid from the sample is pictured below. Bob wins because there are no two adjacent cells with tokens of the same color. $$$$$$\begin{matrix}2&3\\3&1\end{matrix}$$$$$$The sample is only given to demonstrate the input and output format. It is not guaranteed to represent an optimal strategy for Bob or the real behavior of the interactor.

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	long x1, y1, x2 = 1, y2;
	foreach (i; 0..n*n)
	{
		auto num = RD;
		if (num != 1)
		{
			if (x1 < n && y1 < n)
			{
				writeln(1, " ", x1+1, " ", y1+1);
				stdout.flush;
				if (x1+2 < n)
					x1 += 2;
				else
				{
					++y1;
					x1 = 1 - x1 % 2;
				}
			}
			else
			{
				auto z = num == 2 ? 3 : 2;
				writeln(z, " ", x2+1, " ", y2+1);
				stdout.flush;
				if (x2+2 < n)
					x2 += 2;
				else
				{
					++y2;
					x2 = 1 - x2 % 2;
				}
			}
		}
		else
		{
			if (x2 < n && y2 < n)
			{
				writeln(2, " ", x2+1, " ", y2+1);
				stdout.flush;
				if (x2+2 < n)
					x2 += 2;
				else
				{
					++y2;
					x2 = 1 - x2 % 2;
				}
			}
			else
			{
				writeln(3, " ", x1+1, " ", y1+1);
				stdout.flush;
				if (x1+2 < n)
					x1 += 2;
				else
				{
					++y1;
					x1 = 1 - x1 % 2;
				}
			}
		}
	}

	debug readln;
}

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

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

void main() {
  const N = readInt();

  Pt[] ps, qs;
  foreach (x; 1 .. N + 1) foreach (y; 1 .. N + 1) {
    if ((x + y) % 2 == 0) {
      ps ~= Pt(x, y);
    } else {
      qs ~= Pt(x, y);
    }
  }
  const psLen = cast(int)(ps.length);
  const qsLen = cast(int)(qs.length);
  int posP, posQ;

  foreach (_; 0 .. N^^2) {
    const A = readInt();
    int b;
    Pt p;
    if (A != 1 && posP < psLen) {
      b = 1;
      p = ps[posP++];
    } else if (A != 2 && posQ < qsLen) {
      b = 2;
      p = qs[posQ++];
    } else if (A != 3 && posP < psLen) {
      b = 3;
      p = ps[posP++];
    } else if (A != 3 && posQ < qsLen) {
      b = 3;
      p = qs[posQ++];
    } else {
      assert(false);
    }
    writefln("%s %s %s", b, p.x, p.y);
    stdout.flush;
  }
}

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

int main(string[] args)
{
    auto n = to!int(readln.strip);
    Tuple!(int, int)[] f, s;
    foreach (i; 1 .. n + 1) foreach (j; 1 .. n + 1)
    {
        if ((i + j) & 1) s ~= tuple(i, j);
        else f ~= tuple(i, j);
    }
    int c0, c1, fidx, sidx;
    foreach (i; 0 .. n * n)
    {
        auto r = to!int(readln.strip);
        int c, x, y;
        if (fidx == f.length)
        {
            foreach (j; 1 .. 4) if (j != c0 && j != r)
            {
                c = j;
                break;
            }
            x = s[sidx][0], y = s[sidx][1];
            ++ sidx;
        }
        else if (sidx == s.length)
        {
            foreach (j; 1 .. 4) if (j != c1 && j != r)
            {
                c = j;
                break;
            }
            x = f[fidx][0], y = f[fidx][1];
            ++ fidx;
        }
        else
        {
            if (r != c0)
            {
                if (c0 == 0) c0 = (r == 1 ? 2 : 1);
                c = c0;
                x = f[fidx][0], y = f[fidx][1];
                ++ fidx;
            }
            else
            {
                if (c1 == 0)
                {
                    foreach (j; 1 .. 4) if (j != c0 && j != r)
                    {
                        c1 = j;
                        break;
                    }
                }
                c = c1;
                x = s[sidx][0], y = s[sidx][1];
                ++ sidx;
            }
        }
        writeln(c, " ", x, " ", y);
        stdout.flush;
    }
    return 0;
}

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

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

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

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

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

void main() {
  const N = readInt();

  Pt[] ps, qs;
  foreach (x; 1 .. N + 1) foreach (y; 1 .. N + 1) {
    if ((x + y) % 2 == 0) {
      ps ~= Pt(x, y);
    } else {
      qs ~= Pt(x, y);
    }
  }
  const psLen = cast(int)(ps.length);
  const qsLen = cast(int)(ps.length);
  int posP, posQ;

  foreach (_; 0 .. N^^2) {
    const A = readInt();
    int b;
    Pt p;
    if (A != 1 && posP < psLen) {
      b = 1;
      p = ps[posP++];
    } else if (A != 2 && posQ < qsLen) {
      b = 2;
      p = qs[posQ++];
    } else if (A != 3 && posP < psLen) {
      b = 3;
      p = ps[posP++];
    } else if (A != 3 && posQ < qsLen) {
      b = 3;
      p = qs[posQ++];
    } else {
      assert(false);
    }
    writefln("%s %s %s", b, p.x, p.y);
    stdout.flush;
  }
}


You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:  Write parity(a) to the end of a. For example, .  Remove the first character of a. For example, . You cannot perform this operation if a is empty. You can use as many operations as you want. The problem is, is it possible to turn a into b?The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.

The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.

Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.

NoteIn the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110

module sigod.codeforces.p298C;

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

void main()
{
	string a = stdin.readln().strip();
	string b = stdin.readln().strip();

	size_t a_count = a.count('1');
	if (a_count % 2 == 1) ++a_count;

	size_t b_count = b.count('1');

	stdout.writeln(a_count >= b_count ? "YES" : "NO");
}

import std.stdio, std.string;

int main() {
	string s1, s2;
	s1 = chomp(readln());
	s2 = chomp(readln());
	if ((count(s1, '1')+1)/2*2 >= count(s2, '1')) {
		writeln("YES");
	} else {
		writeln("NO");
	}
    return 0;
}

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

void main ()
{
	string s, t;
	while ((s = readln ()) != null)
	{
		t = readln ();
		auto x = s.count ('1');
		x += x & 1;
		auto y = t.count ('1');
		writefln ("%s", x >= y ? "YES" : "NO");
	}
}

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

string A, B;

void main(string[] args) {
	try {
	for (; ; ) {
		A = readToken;
		B = readToken;

		int a = A.count('1');
		int b = B.count('1');
		if (a % 2 != 0) {
			++a;
		}
		writeln((a >= b) ? "YES" : "NO");
	}
	} catch (EOFException) {}
}


Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find:  In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.

Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.

NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.

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

immutable int mod = cast(int)1e9 + 7;
alias pair = Tuple!(int, "x", int, "y");

int N, K;
pair[] A;

int mul(int x, int y) {
	int ans = 1;
	for (int i = 0; (1 << i) <= y; ++i) {
		if (y & (1 << i)) ans = cast(int)(cast(long)1 * ans * x % mod);
		x = cast(int)(cast(long)x * x % mod);
	}
	return ans;
}

void main() {
	readf("%d %d\n", &N, &K);
	A ~= pair(cast(int)1e9 + 5, 0);
	foreach(i; 0..N) {
		int x, y; readf("%d %d\n", &x, &y);
		A ~= [pair(x, 1), pair(y + 1, -1)];
	}
	sort!`a.x < b.x`(A);
	int cnt = 0, ways = 0;
	int ans = 0;
	for (int i = 0; i + 1 < A.length; ++i) {
		int st = i;
		while (i + 1 < A.length && A[i].x == A[st].x) {
			if (A[i].y == 1) {
				++cnt;
				if (cnt == K) ways = 1;
				else ways = cast(int)(cast(long)cnt * ways % mod * mul(cnt - K, mod - 2) % mod);
			} else if (A[i].y == -1) {
				--cnt;
				if (cnt < K) ways = 0;
				else ways = cast(int)(cast(long)ways * mul(cnt + 1, mod - 2) % mod * (cnt - K + 1) % mod);
			}
			++i;
		} --i;
		//writeln(A[st].x, ' ', cnt, ' ', ways * (A[i + 1].x - A[i].x));
		ans = (ans + cast(long)ways * (A[i + 1].x - A[i].x) % mod) % mod;
	}
	writeln(ans);
}

import std.stdio, std.conv;
import std.algorithm, std.range, std.random;
import std.string, std.array, std.container, std.bigint;
import std.exception;

int main() {
    immutable MN = 200200;
    Mint[] fact = new Mint[](MN), iFac = new Mint[](MN);
    fact[0] = Mint(1);
    foreach (i; 1..MN) {
        fact[i] = fact[i-1] * Mint(i);
    }
    foreach (i; 0..MN) {
        iFac[i] = Mint.inv(fact[i]);
    }
    Mint C(int n, int k) {
        return fact[n]*iFac[k]*iFac[n-k];
    }
    int n, k;
    readf("%d %d\n", &n, &k);
    alias P = int[2];
    int[2][] ev;
    foreach (i; 0..n) {
        int l, r;
        readf("%d %d\n", &l, &r);
        ev ~= [l, 0];
        ev ~= [r+1, 1];
    }
    ev.sort;
    int co = 0;
    Mint ans = 0;
    foreach (i, e; ev) {
        if (e[1] == 0) co++;
        else co--;

        if (i < ev.length-1 && ev[i+1][0] != ev[i][0]) {
            Mint di = Mint(ev[i+1][0]-ev[i][0]);
            if (k <= co) {
                ans += di * C(co, k);
            }
        }
    }
    writeln(ans);
	return 0;
}

T pow(T)(T x, ulong n) {
    T r = 1;
    while (n) {
        if (n & 1) r *= x;
        x *= x;
        n >>= 1;
    }
    return r;
}

struct ModInt(uint MD) {
    import std.conv : to;
    uint v;
    this(long v) {this.v = (v%MD+MD)%MD;}
    auto normS(uint x) {return (x<MD)?x:x-MD;};
    auto opBinary(string op:"+")(ModInt r) {return ModInt(normS(v+r.v));};
    auto opBinary(string op:"-")(ModInt r) {return this+ModInt(MD-r.v);};
    auto opBinary(string op:"*")(ModInt r) {return ModInt(cast(ulong)v*r.v%MD);};
    auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}
    static ModInt inv(Mint x) { return pow(x, MD-2); }
    string toString() {return v.to!string;}
}
//alias Mint = ModInt!(10^^9+7);
alias ModInt!(10^^9+7) Mint;
string readToken() {
    import std.stdio : readln;
    import std.string : split;
    static size_t pos;
    static string[] tokens;
    while (!(pos < tokens.length)) {
        pos = 0;
        tokens = readln.split;
    }
    return tokens[pos++];
}
T read(T)() {
    import std.conv : to;
    return readToken.to!T;
}


There are $$$n$$$ pillars aligned in a row and numbered from $$$1$$$ to $$$n$$$.Initially each pillar contains exactly one disk. The $$$i$$$-th pillar contains a disk having radius $$$a_i$$$.You can move these disks from one pillar to another. You can take a disk from pillar $$$i$$$ and place it on top of pillar $$$j$$$ if all these conditions are met:  there is no other pillar between pillars $$$i$$$ and $$$j$$$. Formally, it means that $$$|i - j| = 1$$$;  pillar $$$i$$$ contains exactly one disk;  either pillar $$$j$$$ contains no disks, or the topmost disk on pillar $$$j$$$ has radius strictly greater than the radius of the disk you move. When you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar.You may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all $$$n$$$ disks on the same pillar simultaneously?

The first line contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of pillars. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_i$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the radius of the disk initially placed on the $$$i$$$-th pillar. All numbers $$$a_i$$$ are distinct.

Print YES if it is possible to place all the disks on the same pillar simultaneously, and NO otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).

NoteIn the first case it is possible to place all disks on pillar $$$3$$$ using the following sequence of actions:  take the disk with radius $$$3$$$ from pillar $$$2$$$ and place it on top of pillar $$$3$$$;  take the disk with radius $$$1$$$ from pillar $$$1$$$ and place it on top of pillar $$$2$$$;  take the disk with radius $$$2$$$ from pillar $$$4$$$ and place it on top of pillar $$$3$$$;  take the disk with radius $$$1$$$ from pillar $$$2$$$ and place it on top of pillar $$$3$$$.

import std.algorithm.searching : maxIndex;
import std.algorithm.sorting : isSorted;
import std.stdio;

void main()
{
  char c;
  int n;
  readf!"%d\n"(n);
  auto a = new int[n];
  foreach (i; 0..n) readf!"%d%c"(a[i], c);

  auto i = maxIndex(a);
  if (isSorted(a[0..i]) && isSorted!"a > b"(a[i+1..$])) {
    writeln("YES");
  } else {
    writeln("NO");
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	int n = read.to!int;
	int[] as;
	foreach(i; 0 .. n) as ~= read.to!int;

	int f = 0;
	int last = -10;
	foreach(a; as){
		if(last < a){
			if(f == 1){
				"NO".writeln;
				return;
			}
		}
		if(last > a){
			if(f == 0) f = 1;
		}
		last = a;
	}

	"YES".writeln;
	return;

}

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;
	long pos = MIN_POS!"a > b"(a);
	int l = cast(int)pos-1, r = cast(int)pos+1;
	long top = n;
	bool ans = true;
	while (top != 1)
	{
		if (l >= 0)
		{
			if (a[l] == top-1)
			{
				--l;
				--top;
				continue;
			}
		}
		if (r < n)
		{
			if (a[r] == top-1)
			{
				++r;
				--top;
				continue;
			}
		}
		ans = false;
		break;
	}

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

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA;
	long pos = MIN_POS!"a > b"(a);
	int l = cast(int)pos-1, r = cast(int)pos+1;
	long top = n;
	bool ans = true;
	while (top != 1)
	{
		if (l >= 0)
		{
			if (a[l] == top-1)
			{
				--l;
				--top;
				continue;
			}
		}
		if (r < n)
		{
			if (a[r] == top-1)
			{
				--r;
				--top;
				continue;
			}
		}
		ans = false;
		break;
	}

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


A median of an array of integers of length $$$n$$$ is the number standing on the $$$\lceil {\frac{n}{2}} \rceil$$$ (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with $$$1$$$. For example, a median of the array $$$[2, 6, 4, 1, 3, 5]$$$ is equal to $$$3$$$. There exist some other definitions of the median, but in this problem, we will use the described one.Given two integers $$$n$$$ and $$$k$$$ and non-decreasing array of $$$nk$$$ integers. Divide all numbers into $$$k$$$ arrays of size $$$n$$$, such that each number belongs to exactly one array.You want the sum of medians of all $$$k$$$ arrays to be the maximum possible. Find this maximum possible sum.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of test cases. The first line of the description of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 1000$$$). The second line of the description of each test case contains $$$nk$$$ integers $$$a_1, a_2, \ldots, a_{nk}$$$ ($$$0 \leq a_i \leq 10^9$$$) — given array. It is guaranteed that the array is non-decreasing: $$$a_1 \leq a_2 \leq \ldots \leq a_{nk}$$$. It is guaranteed that the sum of $$$nk$$$ for all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer — the maximum possible sum of medians of all $$$k$$$ arrays.

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

string FMT_F = "%.10f";

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

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

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

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

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

		a.sort();
		debug writeln(a);
		auto p = (n-1) / 2;
		auto x = p * k;
		foreach (i; 0..k)
		{
			auto j = i*(n-p)+x;
			ans[ti] += a[j];
			debug writeln("i:", i, " ", a[j]);
		}
	}

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


Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.

The first line of the input contains one integer, n (1 ≤ n ≤ 100 000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 109, inclusive.

Print the maximum possible even sum that can be obtained if we use some of the given integers.

NoteIn the first sample, we can simply take all three integers for a total sum of 6.In the second sample Wet Shark should take any four out of five integers 999 999 999.

import std.stdio;
import std.conv;
import std.string;
import std.array: Appender;

void main()
{
	auto n = split(strip(readln))[0];
	auto s = split(strip(readln));
	long[] a = new long[to!int(n,10)];
	long sum;
	long min = long.max;
	foreach(i, el; s)
	{
		a[i] = to!long(el,10);
		sum += a[i];
		if (a[i] % 2 != 0 && min > a[i])
		{
			min = a[i];
		}
	}
	if (sum % 2 != 0)
		sum -= min;
	writeln(sum);
}

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

void main() {
    int n = readln.chomp.to!int;
    ulong[] s = readln.chomp.split.map!(to!ulong).array;

    ulong ans = s.sum;
    if (ans & 1) {
        ans -= s.filter!"a & 1".array.minPos[0];
    }

    ans.writeln;
}

import std.stdio,std.array,std.algorithm;
void main()
{
	stdin.readln;
	auto v=stdin.readln.split.map!"to!ulong(a)";
	auto s=v.sum;
	writeln(s%2?s-v.filter!"a%2".reduce!"a<b?a:b":s);
}

import std.stdio,std.algorithm;
long n,no,ne,mino,so,se,temp;
void main()
{
	scanf(" %d",&n);
	mino=long.max;
	for(int i=0;i<n;++i)
	{
		scanf(" %d",&temp);
		if(temp%2)
		{
			mino=min(mino,temp);
			so+=temp;
			++no;
		}else{
			se+=temp;
			++ne;
		}
	}
	writeln(se+so-(no%2?mino:0));
}

import std.stdio,std.algorithm;
long n,t,s,m=long.max;
void main()
{
	scanf(" %d",&n);
	foreach(i;0..n)
	{
		scanf(" %d",&t);
		s+=t;
		if(t%2) m=min(m,t);
	}
	writeln(s%2?s-m:s);
}


Given the integer $$$n$$$ — the number of available blocks. You must use all blocks to build a pedestal. The pedestal consists of $$$3$$$ platforms for $$$2$$$-nd, $$$1$$$-st and $$$3$$$-rd places respectively. The platform for the $$$1$$$-st place must be strictly higher than for the $$$2$$$-nd place, and the platform for the $$$2$$$-nd place must be strictly higher than for the $$$3$$$-rd place. Also, the height of each platform must be greater than zero (that is, each platform must contain at least one block).    Example pedestal of $$$n=11$$$ blocks: second place height equals $$$4$$$ blocks, first place height equals $$$5$$$ blocks, third place height equals $$$2$$$ blocks.Among all possible pedestals of $$$n$$$ blocks, deduce one such that the platform height for the $$$1$$$-st place minimum as possible. If there are several of them, output any of them.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case contains a single integer $$$n$$$ ($$$6 \le n \le 10^5$$$) — the total number of blocks for the pedestal. All $$$n$$$ blocks must be used. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^6$$$.

For each test case, output $$$3$$$ numbers $$$h_2, h_1, h_3$$$ — the platform heights for $$$2$$$-nd, $$$1$$$-st and $$$3$$$-rd places on a pedestal consisting of $$$n$$$ blocks ($$$h_1+h_2+h_3=n$$$, $$$0 < h_3 < h_2 < h_1$$$).  Among all possible pedestals, output the one for which the value of $$$h_1$$$ minimal. If there are several of them, output any of them.

NoteIn the first test case we can not get the height of the platform for the first place less than $$$5$$$, because if the height of the platform for the first place is not more than $$$4$$$, then we can use at most $$$4 + 3 + 2 = 9$$$ blocks. And we should use $$$11 = 4 + 5 + 2$$$ blocks. Therefore, the answer 4 5 2 fits. In the second set, the only suitable answer is: 2 3 1.

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!long;

      long d3 = (N - 6) / 3;
      long[] ans = [2 + d3, 3 + d3, 1 + d3];
      if (N % 3 >= 1) ans[1]++;
      if (N % 3 >= 2) ans[0]++;

      return ans.toAnswerString;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

// ----------------------------------------------

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

// -----------------------------------------------

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!long;

      auto ans = (N / 3).repeat(3).array;
      ans[1]++;
      ans[2]--;
      ans[1] += N % 3;

      return ans.toAnswerString;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

// ----------------------------------------------

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

// -----------------------------------------------


You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.The following definition of a regular bracket sequence is well-known, so you can be familiar with it.Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.Determine the least number of replaces to make the string s RBS.

The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.

If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s.

import std.range;
import std.stdio;
import std.string;

immutable int NA = -1;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		int n = s.length;
		auto t = '*'.repeat (n).array;
		t.reserve (n * 2);
		int res = 0;
		foreach (char c; s)
		{
			if (c == '<')
			{
				t ~= '>';
			}
			else if (c == '{')
			{
				t ~= '}';
			}
			else if (c == '[')
			{
				t ~= ']';
			}
			else if (c == '(')
			{
				t ~= ')';
			}
			else if (t.back == '*')
			{
				res = NA;
				break;
			}
			else
			{
				res += (c != t.back);
				t.popBack ();
				t.assumeSafeAppend ();
			}
		}
		if (t.length != n || res == NA)
		{
			writeln ("Impossible");
		}
		else
		{
			writeln (res);
		}
	}
}

module main;

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

int main() {

    auto s = readln().strip();

    char[] stack;
    string open = "({[<";
    string close = ")}]>";

    int result;

    bool flag = true;
    foreach (int i; 0..s.length)
        if (canFind(open, s[i])) {
            stack.assumeSafeAppend();
            stack ~= s[i];
        } else {
            if (stack.length == 0 || canFind(stack.back.to! (string), close)) {
                flag = false;
                break;
            }

            if (s[i] == ')' && stack.back != '(' || s[i] == '}' && stack.back != '{' || s[i] == ']' &&
                stack.back != '[' || s[i] == '>' && stack.back != '<')
                    result++;

            stack.popBack();
        }

    writeln((flag && stack.length == 0) ? result.to! (string) : "Impossible");

	return 0;
}

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

immutable int NA = -1;

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		int n = s.length;
		auto t = '*'.repeat (n).array;
		t.reserve (n * 2);
		int res = 0;
		foreach (char c; s)
		{
			if (c == '<')
			{
				t ~= '>';
			}
			else if (c == '{')
			{
				t ~= '}';
			}
			else if (c == '[')
			{
				t ~= ']';
			}
			else if (c == '(')
			{
				t ~= ')';
			}
			else if (t.back == '*')
			{
				res = NA;
				break;
			}
			else
			{
				res += (c != t.back);
				t.popBack ();
				t.assumeSafeAppend ();
			}
		}
		writeln (equal (t, '*'.repeat (n)) ? res : NA);
	}
}


A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.

The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). All the numbers in the lines are separated by single spaces.

On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.

NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.

import std.algorithm;
import std.stdio;

void main ()
{
    int n, k;
    while (readf (" %s %s", &n, &k) > 0)
    {
        if (k == 1)
        {
            k = 0;
        }
        auto a = new long [n];
        foreach (i; 0..n)
        {
            readf (" %s", &a[i]);
        }
        sort (a);
        int j;
        int res = n;
        foreach (i; 0..n)
        {
            while (j < n && a[i] * k > a[j])
            {
                j++;
            }
            if (j < n && a[i] * k == a[j])
            {
                a[j] = -1;
                res--;
                j++;
            }
        }
        writefln ("%s", res);
    }
}

import std.algorithm;
import std.container;
import std.stdio;

void main ()
{
    int n, k;
    while (readf (" %s %s", &n, &k) > 0)
    {
        if (k == 1)
        {
            k = 0;
        }

        auto c = redBlackTree !(long);
        foreach (i; 0..n)
        {
            int a;
            readf (" %s", &a);
            c.insert (a);
        }

        int res;
        foreach (e; c)
        {
            c.removeKey (e * k);
            res++;
        }
        writefln ("%s", res);
    }
}

import std.algorithm;
import std.stdio;

void main ()
{
    int n, k;
    while (readf (" %s %s", &n, &k) > 0)
    {
        auto a = new long [n];
        foreach (i; 0..n)
        {
            readf (" %s", &a[i]);
        }
        sort (a);
        int j;
        int res = n;
        foreach (i; 0..n)
        {
            while (j < n && a[i] * k > a[j])
            {
                j++;
            }
            if (j < n && a[i] * k == a[j])
            {
                a[i] = -1;
                res--;
                j++;
            }
        }
        writefln ("%s", res);
    }
}

import std.algorithm;
import std.stdio;

void main ()
{
    int n, k;
    while (readf (" %s %s", &n, &k) > 0)
    {
        auto a = new long [n];
        foreach (i; 0..n)
        {
            readf (" %s", &a[i]);
        }
        sort (a);
        int j;
        int res = n;
        foreach (i; 0..n)
        {
            while (j < n && a[i] * k > a[j])
            {
                j++;
            }
            if (j < n && a[i] * k == a[j])
            {
                a[j] = -1;
                res--;
                j++;
            }
        }
        writefln ("%s", res);
    }
}


The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it.However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima's task to figure out whether the document has malfunctioned. Specifically, he is given a string of length $$$n$$$ whose characters are all either T or M, and he wants to figure out if it is possible to partition it into some number of disjoint subsequences, all of which are equal to TMT. That is, each character of the string should belong to exactly one of the subsequences.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) characters.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$)  — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$3 \le n < 10^5$$$), the number of characters in the string entered in the document. It is guaranteed that $$$n$$$ is divisible by $$$3$$$. The second line of each test case contains a string of length $$$n$$$ consisting of only the characters T and M. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single line containing YES if the described partition exists, and a single line containing NO otherwise.

5
3
TMT
3
MTT
6
TMTMTT
6
TMTTTT
6
TTMMTT

NoteIn the first test case, the string itself is already a sequence equal to TMT.In the third test case, we may partition the string into the subsequences TMTMTT. Both the bolded and the non-bolded subsequences are equal to TMT.

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

bool ok (string s)
{
	if (s.count ('M') * 2 != s.count ('T'))
	{
		return false;
	}

	int balance = 0;
	foreach (ref c; s)
	{
		balance += (c == 'T') ? +1 : -1;
		if (balance < 0)
		{
			return false;
		}
	}

	return true;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip;
		writeln ((ok (s) && ok (s.retro.text)) ? "YES" : "NO");
	}
}


There are $$$n$$$ cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from $$$1$$$ to $$$n$$$.Two fairs are currently taking place in Berland — they are held in two different cities $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le n$$$; $$$a \ne b$$$).Find the number of pairs of cities $$$x$$$ and $$$y$$$ ($$$x \ne a, x \ne b, y \ne a, y \ne b$$$) such that if you go from $$$x$$$ to $$$y$$$ you will have to go through both fairs (the order of visits doesn't matter). Formally, you need to find the number of pairs of cities $$$x,y$$$ such that any path from $$$x$$$ to $$$y$$$ goes through $$$a$$$ and $$$b$$$ (in any order).Print the required number of pairs. The order of two cities in a pair does not matter, that is, the pairs $$$(x,y)$$$ and $$$(y,x)$$$ must be taken into account only once.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 4\cdot10^4$$$) — the number of test cases in the input. Next, $$$t$$$ test cases are specified. The first line of each test case contains four integers $$$n$$$, $$$m$$$, $$$a$$$ and $$$b$$$ ($$$4 \le n \le 2\cdot10^5$$$, $$$n - 1 \le m \le 5\cdot10^5$$$, $$$1 \le a,b \le n$$$, $$$a \ne b$$$) — numbers of cities and roads in Berland and numbers of two cities where fairs are held, respectively. The following $$$m$$$ lines contain descriptions of roads between cities. Each of road description contains a pair of integers $$$u_i, v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) — numbers of cities connected by the road. Each road is bi-directional and connects two different cities. It is guaranteed that from any city you can pass to any other by roads. There can be more than one road between a pair of cities. The sum of the values of $$$n$$$ for all sets of input data in the test does not exceed $$$2\cdot10^5$$$. The sum of the values of $$$m$$$ for all sets of input data in the test does not exceed $$$5\cdot10^5$$$.

Print $$$t$$$ integers — the answers to the given test cases in the order they are written in the input.

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

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

    while (t--) {
        int n, m, a, b;
        readf("%s %s %s %s", &n, &m, &a, &b);
        readln;

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

            g[u] ~= v;
            g[v] ~= u;
        }

        auto mark = new bool[][] (2, n+1);
        foreach (i; 0 .. 2) { mark[i][] = false; }

        void dfs(int v, int p, int bad) {
            mark[p][v] = true;
            if (v == bad) { return; }

            foreach (u; g[v]) {
                if (mark[p][u]) { continue; }

                dfs(u, p, bad);
            }
        }

        dfs(a, 0, b);
        dfs(b, 1, a);

        debug { mark.each!writeln; }

        auto ans = mark[0].dropOne.count!(p => !p).to!long
            * mark[1].dropOne.count!(p => !p);

        ans.writeln;
    }
}

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

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const M = readInt();
        const A = readInt() - 1;
        const B = readInt() - 1;
        auto U = new int[M];
        auto V = new int[M];
        foreach (i; 0 .. M) {
          U[i] = readInt() - 1;
          V[i] = readInt() - 1;
        }

        long ans = 1L * (N - 2) * (N - 3) / 2;

        int[] doIt(int s) {
          auto uf = new int[N];
          uf[] = -1;
          foreach (i; 0 .. M) {
            if (U[i] != s && V[i] != s) {
              uf.connect(U[i], V[i]);
            }
          }
          foreach (u; 0 .. N) {
            if (uf[u] < 0) {
              long sz = -uf[u];
              if (u == uf.root(A)) --sz;
              if (u == uf.root(B)) --sz;
              ans -= sz * (sz - 1) / 2;
            }
          }
          return uf;
        }

        auto ufA = doIt(A);
        auto ufB = doIt(B);
        Tuple!(int, int)[] ts;
        foreach (u; 0 .. N) {
          if (u != A && u != B) {
            ts ~= tuple(ufA.root(u), ufB.root(u));
          }
        }
        ts.sort;
        foreach (grp; ts.group) {
          long sz = grp[1];
          ans += sz * (sz - 1) / 2;
        }
        writeln(ans);
      }
    }
  } catch (EOFException 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;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  debug scope(exit) inputFile.close;
  auto nt = next!int;
  foreach(tc; 0 .. nt)
    {
      auto n = next!int;
      auto m = next!int;
      auto a = next!int - 1;
      auto b = next!int - 1;
      auto nei = new int[][](n);
      foreach(e; 0 .. m)
        {
          auto u = next!int - 1;
          auto v = next!int - 1;
          nei[u] ~= v;
          nei[v] ~= u;
        }
      auto visited = new bool[](n);
      visited[] = false;
      auto size = new int[](n);
      size[] = 0;
      int searched = -1;
      int searchedAncestor = -1;
      void dfs(int nd, int bigAncestor, bool isRoot)
      {
        visited[nd] = true;
        size[nd] = 1;
        if (nd == searched)
          {
            searchedAncestor = bigAncestor;
          }
        if (isRoot)
          {
            foreach(ne; nei[nd])
              if (!visited[ne])
                {
                  dfs(ne, ne, false);
                  size[nd] += size[ne];
                }
          }
        else
          {
            foreach(ne; nei[nd])
              if (!visited[ne])
                {
                  dfs(ne, bigAncestor, false);
                  size[nd] += size[ne];
                }
          }
      }

      searched = b;
      dfs(a, -1, true);
      auto winga = size[a] - size[searchedAncestor] - 1;
      visited[] = false;
      size[] = 0;
      searched = a;
      dfs(b, -1, true);
      auto wingb = size[b] - size[searchedAncestor] - 1;
      writeln(cast(long) winga * cast(long) wingb);
    }
}

// INPUT

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

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

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

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

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  debug scope(exit) inputFile.close;
  bool[200_000] visitedPool;
  int[200_000] sizePool;
  auto nt = next!int;
  foreach(tc; 0 .. nt)
    {
      auto n = next!int;
      auto m = next!int;
      auto a = next!int - 1;
      auto b = next!int - 1;
      auto nei = new int[][](n);
      foreach(e; 0 .. m)
        {
          auto u = next!int - 1;
          auto v = next!int - 1;
          nei[u] ~= v;
          nei[v] ~= u;
        }
      auto visited = visitedPool[0 .. n];
      visited[] = false;
      auto size = sizePool[0 .. n];
      size[] = 0;
      int searched = -1;
      int searchedAncestor = -1;
      void dfs(int nd, int bigAncestor, bool isRoot)
      {
        visited[nd] = true;
        size[nd] = 1;
        if (nd == searched)
          {
            searchedAncestor = bigAncestor;
          }
        if (isRoot)
          {
            foreach(ne; nei[nd])
              if (!visited[ne])
                {
                  dfs(ne, ne, false);
                  size[nd] += size[ne];
                }
          }
        else
          {
            foreach(ne; nei[nd])
              if (!visited[ne])
                {
                  dfs(ne, bigAncestor, false);
                  size[nd] += size[ne];
                }
          }
      }

      searched = b;
      dfs(a, -1, true);
      auto winga = size[a] - size[searchedAncestor] - 1;
      visited[] = false;
      size[] = 0;
      searched = a;
      dfs(b, -1, true);
      auto wingb = size[b] - size[searchedAncestor] - 1;
      writeln(cast(long) winga * cast(long) wingb);
    }
}

// INPUT

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

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

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