A sequence $$$(b_1, b_2, \ldots, b_k)$$$ is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair $$$(i, j)$$$ with $$$1 \le i<j \le k$$$, we have $$$|a_i-a_j|\geq MAX$$$, where $$$MAX$$$ is the largest element of the sequence. In particular, any sequence of length at most $$$1$$$ is strange.For example, the sequences $$$(-2021, -1, -1, -1)$$$ and $$$(-1, 0, 1)$$$ are strange, but $$$(3, 0, 1)$$$ is not, because $$$|0 - 1| < 3$$$.Sifid has an array $$$a$$$ of $$$n$$$ integers. Sifid likes everything big, so among all the strange subsequences of $$$a$$$, he wants to find the length of the longest one. Can you help him?A sequence $$$c$$$ is a subsequence of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements.

The first line contains an integer $$$t$$$ $$$(1\le t\le 10^4)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1\le n\le 10^5)$$$ — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(-10^9\le a_i \le 10^9)$$$ — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case output a single integer — the length of the longest strange subsequence of $$$a$$$.

NoteIn the first test case, one of the longest strange subsequences is $$$(a_1, a_2, a_3, a_4)$$$In the second test case, one of the longest strange subsequences is $$$(a_1, a_3, a_4, a_5, a_7)$$$.In the third test case, one of the longest strange subsequences is $$$(a_1, a_3, a_4, a_5)$$$.In the fourth test case, one of the longest strange subsequences is $$$(a_2)$$$.In the fifth test case, one of the longest strange subsequences is $$$(a_1, a_2, a_4)$$$.

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

void main() {
    foreach(t; 0 .. to!int(readln.chomp)) {
        int n = to!int(readln.chomp);
        auto nums = readln.split.map!(to!int).array.sort;
        int mn = int.max, ans = 1;
        foreach(i; 1 .. n) {
            mn = min(mn, nums[i] - nums[i-1]);
            if(mn < nums[i]) break;
            ans++;
        }
        writeln(ans);
    }
}

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.numeric;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln().chomp.to!int;
        auto arr = readln().chomp.splitter(" ").map!(to!int).array.sort;

        int diff = int.max;
        int res= 1;

        for(int i = 1; i < arr.length;i++)
        {
            diff = min(diff, arr[i] - arr[i-1]);
            if(diff < arr[i]) break;
            res++;
        }

        writeln(res);
    }
}

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.numeric;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln().chomp.to!int;
        auto arr = readln().chomp.splitter(" ").map!(to!int).array.sort.array;

        int diff = int.max;
        int res= 1;

        for(int i = 1; i < arr.length;i++)
        {
            diff = min(diff, arr[i] - arr[i-1]);
            if(diff < arr[i]) break;
            res++;
        }

        writeln(res);
    }
}

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

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

while(t--) {
    int n = readln.chomp.to!int;
    int[] a = readln.split.map!(to!int).array;
    int minima = int.max;
    int ans = 1;
    a.sort;
    for(int i = 1; i < n; ++i) {
        minima = min(minima, a[i] - a[i - 1]);
        if(a[i] <= 0) {
            ans += 1;
            continue;
        } else {
            if(a[i] <= minima) {
                ans += 1;
            }
            break;
        }
    }
    ans.writeln;
}
}

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)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

//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 a = RDA;

		long[] b, c;
		foreach (i; 0..n)
		{
			if (a[i] > 0)
				b ~= a[i];
			else
				c ~= a[i];
		}

		long rmv, x;
		if (!b.empty)
		{
			rmv = b.length - 1;
			x = b.minElement;
		}
		c.sort;
		long y = long.max;
		foreach (i; 0..cast(int)c.length-1)
		{
			y.chmin(c[i+1] - c[i]);
		}
		if (y < x)
			++rmv;
		ans[ti] = n - rmv;
	}

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

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

void main() {
    foreach(t; 0 .. to!int(readln.chomp)) {
        int n = to!int(readln.chomp);
        auto nums = readln.split.map!(to!int).array;
        auto cnt = new int[3];
        foreach(e; nums) {
            if(e < 0) {
                cnt[0]++;
            } else if(!e) {
                cnt[1]++;
            } else {
                cnt[2] = true;
            }
        }
        writeln(cnt[0] + (cnt[1] > 1 ? cnt[1] : cnt[1]+cnt[2]));
    }
}


The new academic year has started, and Berland's university has $$$n$$$ first-year students. They are divided into $$$k$$$ academic groups, however, some of the groups might be empty. Among the students, there are $$$m$$$ pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.Alice is the curator of the first years, she wants to host an entertaining game to make everyone know each other. To do that, she will select two different academic groups and then divide the students of those groups into two teams. The game requires that there are no acquaintance pairs inside each of the teams.Alice wonders how many pairs of groups she can select, such that it'll be possible to play a game after that. All students of the two selected groups must take part in the game.Please note, that the teams Alice will form for the game don't need to coincide with groups the students learn in. Moreover, teams may have different sizes (or even be empty).

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 500\,000$$$; $$$0 \le m \le 500\,000$$$; $$$2 \le k \le 500\,000$$$) — the number of students, the number of pairs of acquaintances and the number of groups respectively. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ equals to the group number of the $$$i$$$-th student. Next $$$m$$$ lines follow. The $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting that students $$$a_i$$$ and $$$b_i$$$ are acquaintances. It's guaranteed, that $$$a_i \neq b_i$$$, and that no (unordered) pair is mentioned more than once.

Print a single integer — the number of ways to choose two different groups such that it's possible to select two teams to play the game.

NoteThe acquaintances graph for the first example is shown in the picture below (next to each student there is their group number written).In that test we can select the following groups:  Select the first and the second groups. For instance, one team can be formed from students $$$1$$$ and $$$4$$$, while other team can be formed from students $$$2$$$ and $$$3$$$.  Select the second and the third group. For instance, one team can be formed $$$3$$$ and $$$6$$$, while other team can be formed from students $$$4$$$ and $$$5$$$.  We can't select the first and the third group, because there is no way to form the teams for the game. In the second example, we can select any group pair. Please note, that even though the third group has no students, we still can select it (with some other group) for the game.

// c
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 KV = Tuple!(int, "key", int, "val");
KV[] history;

int root(int[] uf, int u) {
  // return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
  if (uf[u] < 0) {
    return u;
  } else {
    const r = uf.root(uf[u]);
    history ~= KV(u, uf[u]);
    return uf[u] = r;
  }
}
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);
  history ~= KV(u, uf[u]);
  uf[u] += uf[v];
  history ~= KV(v, uf[v]);
  uf[v] = u;
  return true;
}

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      const K = readInt();
      auto C = new int[N];
      foreach (u; 0 .. N) {
        C[u] = readInt() - 1;
      }
      auto A = new int[M];
      auto B = new int[M];
      foreach (i; 0 .. M) {
        A[i] = readInt() - 1;
        B[i] = readInt() - 1;
      }

      auto uss = new int[][K];
      foreach (u; 0 .. N) {
        uss[C[u]] ~= u;
      }

      auto uf = new int[N * 2];
      uf[] = -1;

      alias Entry = Tuple!(int, "ca", int, "cb", int, "i");
      Entry[] es;
      foreach (i; 0 .. M) {
        if (C[A[i]] > C[B[i]]) {
          swap(A[i], B[i]);
        }
        if (C[A[i]] == C[B[i]]) {
          uf.connect(A[i] * 2 + 0, B[i] * 2 + 1);
          uf.connect(A[i] * 2 + 1, B[i] * 2 + 0);
        } else {
          es ~= Entry(C[A[i]], C[B[i]], i);
        }
      }
      es.sort;
      const esLen = cast(int)(es.length);

      auto good = new bool[K];
      good[] = true;
      foreach (k; 0 .. K) {
        foreach (u; uss[k]) {
          good[k] = good[k] && (uf.root(u * 2 + 0) != uf.root(u * 2 + 1));
        }
      }
      debug {
        writeln("good = ", good);
      }
      const numGood = cast(long)(good.count(true));
      long ans = numGood * (numGood - 1) / 2;

      for (int g = 0, h; g < esLen; g = h) {
        for (h = g; h < esLen && (es[g].ca == es[h].ca && es[g].cb == es[h].cb); ++h) {}
        if (good[es[g].ca] && good[es[g].cb]) {
          debug {
            writeln(es[g .. h]);
          }
          history = [];
          foreach (ref e; es[g .. h]) {
            const i = e.i;
            uf.connect(A[i] * 2 + 0, B[i] * 2 + 1);
            uf.connect(A[i] * 2 + 1, B[i] * 2 + 0);
          }
          bool ok = true;
          foreach (ref e; es[g .. h]) {
            const i = e.i;
            ok = ok && (uf.root(A[i] * 2 + 0) != uf.root(A[i] * 2 + 1));
            ok = ok && (uf.root(B[i] * 2 + 0) != uf.root(B[i] * 2 + 1));
          }
          if (!ok) {
            --ans;
          }
          foreach_reverse (ref kv; history) {
            uf[kv.key] = kv.val;
          }
        }
      }

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

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

void main ()
{
	int n, m, k;
	while (readf !(" %s %s %s") (n, m, k) > 0)
	{
		readln;
		auto g = readln.splitter.map !(to !(int)).array;
		g[] -= 1;
		alias Edge = Tuple !(int, q{u}, int, q{v});
		Edge [] [Edge] edgesByPair;
		foreach (j; 0..m)
		{
			Edge e;
			readf !(" %s %s") (e.u, e.v);
			e.u -= 1;
			e.v -= 1;

			auto pair = Edge (g[e.u], g[e.v]);
			if (pair.u > pair.v)
			{
				swap (pair.u, pair.v);
			}
			edgesByPair[pair] ~= e;
		}

		alias Parent = Tuple !(int, q{v}, int, q{xor});
		auto p = new Parent [n];
		auto rank = new int [n];
		foreach (u; 0..n)
		{
			p[u] = Parent (u, 0);
			rank[u] = 1;
		}

		auto root (int v)
		{
			auto res = Parent (v, 0);
			while (res.v != p[res.v].v)
			{
				res.xor ^= p[res.v].xor;
				res.v = p[res.v].v;
			}
			return res;
		}

		alias Record = Tuple !(int, q{u}, int, q{v}, int, q{xor},
		    int, q{w}, int, q{rank});
		Record [] history;

		auto unite (const ref Edge e, bool doRecord = false)
		{
			auto pu = root (e.u);
			auto pv = root (e.v);
			auto u = pu.v;
			auto v = pv.v;
			auto xor = pu.xor ^ pv.xor;
			debug {writefln !("unite: %s %s %s") (u, v, xor);}
			if (u == v)
			{
				return (xor == 1);
			}
			xor ^= 1;
			if (rank[u] > rank[v])
			{
				swap (u, v);
			}
			if (doRecord)
			{
				history ~= Record (u, p[u].v, p[u].xor,
				    v, rank[v]);
			}
			if (rank[u] == rank[v])
			{
				rank[v] += 1;
			}
			p[u] = Parent (v, xor);
			debug {writefln !("p[%s] = %s %s") (u, v, xor);}
			return true;
		}

		auto badGroup = new bool [k];

		foreach (i; 0..k)
		{
			auto pair = Edge (i, i);
			if (pair in edgesByPair)
			{
				foreach (e; edgesByPair[pair])
				{
					if (!unite (e))
					{
						badGroup[i] = true;
					}
				}
			}
		}

		auto totalBad = sum (badGroup, 0);
		debug {writeln ("totalBad = ", totalBad);}
		long res = k - totalBad;
		res = (res * (res - 1L)) / 2;

		foreach (pair, edges; edgesByPair)
		{
			if (pair.u == pair.v)
			{
				continue;
			}
			if (badGroup[pair.u] || badGroup[pair.v])
			{
				continue;
			}

			bool badPair = false;
			foreach (e; edges)
			{
				if (!unite (e, true))
				{
					badPair = true;
				}
			}
			if (badPair)
			{
				res -= 1;
			}
			foreach_reverse (r; history)
			{
				rank[r.w] = r.rank;
				p[r.u] = Parent (r.v, r.xor);
				debug {writefln !("p[%s] reverted to %s %s")
				    (r.u, r.v, r.xor);}
			}
			history = null;
		}

		writeln (res);
	}
}

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

void main ()
{
	int n, m, k;
	while (readf !(" %s %s %s") (n, m, k) > 0)
	{
		readln;
		auto g = readln.splitter.map !(to !(int)).array;
		g[] -= 1;
		alias Edge = Tuple !(int, q{u}, int, q{v});
		Edge [] [Edge] edgesByPair;
		foreach (j; 0..m)
		{
			Edge e;
			readf !(" %s %s") (e.u, e.v);
			e.u -= 1;
			e.v -= 1;

			auto pair = Edge (g[e.u], g[e.v]);
			if (pair.u > pair.v)
			{
				swap (pair.u, pair.v);
			}
			edgesByPair[pair] ~= e;
		}

		alias Parent = Tuple !(int, q{v}, int, q{xor});
		auto p = new Parent [n];
		auto rank = new int [n];
		foreach (u; 0..n)
		{
			p[u] = Parent (u, 0);
			rank[u] = 1;
		}

		auto root (int v)
		{
			auto res = Parent (v, 0);
			while (res.v != p[res.v].v)
			{
				res.xor ^= p[res.v].xor;
				res.v = p[res.v].v;
			}
			return res;
		}

		alias Record = Tuple !(int, q{u}, int, q{v}, int, q{xor},
		    int, q{w}, int, q{rank});
		Record [] history;

		auto unite (const ref Edge e, bool doRecord = false)
		{
			auto pu = root (e.u);
			auto pv = root (e.v);
			auto u = pu.v;
			auto v = pv.v;
			auto xor = pu.xor ^ pv.xor;
			debug {writefln !("unite: %s %s %s") (u, v, xor);}
			if (u == v)
			{
				return (xor == 1);
			}
			xor ^= 1;
			if (rank[u] > rank[v])
			{
				swap (u, v);
			}
			if (doRecord)
			{
				history ~= Record (u, p[u].v, p[u].xor,
				    v, rank[v]);
			}
			if (rank[u] == rank[v])
			{
				rank[v] += 1;
			}
			p[u] = Parent (v, xor);
			debug {writefln !("p[%s] = %s %s") (u, v, xor);}
			return true;
		}

		auto badGroup = new bool [k];

		foreach (i; 0..k)
		{
			auto pair = Edge (i, i);
			if (pair in edgesByPair)
			{
				foreach (e; edgesByPair[pair])
				{
					if (!unite (e))
					{
						badGroup[i] = true;
					}
				}
			}
		}

		auto totalBad = sum (badGroup, 0);
		debug {writeln ("totalBad = ", totalBad);}
		long res = k - totalBad;
		res = (res * (res - 1L)) / 2;

		foreach (pair, edges; edgesByPair)
		{
			if (pair.u == pair.v)
			{
				continue;
			}

			bool badPair = false;
			foreach (e; edges)
			{
				if (!unite (e, true))
				{
					badPair = true;
				}
			}
			if (badPair)
			{
				res -= 1;
			}
			foreach_reverse (r; history)
			{
				rank[r.w] = r.rank;
				p[r.u] = Parent (r.v, r.xor);
				debug {writefln !("p[%s] reverted to %s %s")
				    (r.u, r.v, r.xor);}
			}
			history = null;
		}

		writeln (res);
	}
}


You are given an array $$$a$$$ of length $$$n$$$, which initially is a permutation of numbers from $$$1$$$ to $$$n$$$. In one operation, you can choose an index $$$i$$$ ($$$1 \leq i < n$$$) such that $$$a_i < a_{i + 1}$$$, and remove either $$$a_i$$$ or $$$a_{i + 1}$$$ from the array (after the removal, the remaining parts are concatenated). For example, if you have the array $$$[1, 3, 2]$$$, you can choose $$$i = 1$$$ (since $$$a_1 = 1 < a_2 = 3$$$), then either remove $$$a_1$$$ which gives the new array $$$[3, 2]$$$, or remove $$$a_2$$$ which gives the new array $$$[1, 2]$$$.Is it possible to make the length of this array equal to $$$1$$$ with these operations?

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq n$$$, $$$a_i$$$ are pairwise distinct) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, output on a single line the word "YES" if it is possible to reduce the array to a single element using the aforementioned operation, or "NO" if it is impossible to do so.

NoteFor the first two test cases and the fourth test case, we can operate as follow (the bolded elements are the pair chosen for that operation):$$$[\text{1}, \textbf{2}, \textbf{3}] \rightarrow [\textbf{1}, \textbf{2}] \rightarrow [\text{1}]$$$$$$[\text{3}, \textbf{1}, \textbf{2}, \text{4}] \rightarrow [\text{3}, \textbf{1}, \textbf{4}] \rightarrow [\textbf{3}, \textbf{4}] \rightarrow [\text{4}]$$$$$$[\textbf{2}, \textbf{4}, \text{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\textbf{4}, \textbf{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\text{4}, \text{1}, \textbf{3}, \textbf{5}] \rightarrow [\text{4}, \textbf{1}, \textbf{5}] \rightarrow [\textbf{4}, \textbf{5}] \rightarrow [\text{4}]$$$

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = a.front < a.back;
	}

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

import std.algorithm;
import std.conv;
import std.math;
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 a = readln.splitter.map !(to !(long)).array;
		writeln (a.front < a.back ? "YES" : "NO");
	}
}

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 numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        auto A = new int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt();
        }

        writeln((A[0] < A[N - 1]) ? "YES" : "NO");
      }
    }
  } catch (EOFException e) {
  }
}


You a captain of a ship. Initially you are standing in a point $$$(x_1, y_1)$$$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $$$(x_2, y_2)$$$. You know the weather forecast — the string $$$s$$$ of length $$$n$$$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $$$s_1$$$, the second day — $$$s_2$$$, the $$$n$$$-th day — $$$s_n$$$ and $$$(n+1)$$$-th day — $$$s_1$$$ again and so on. Ship coordinates change the following way:  if wind blows the direction U, then the ship moves from $$$(x, y)$$$ to $$$(x, y + 1)$$$;  if wind blows the direction D, then the ship moves from $$$(x, y)$$$ to $$$(x, y - 1)$$$;  if wind blows the direction L, then the ship moves from $$$(x, y)$$$ to $$$(x - 1, y)$$$;  if wind blows the direction R, then the ship moves from $$$(x, y)$$$ to $$$(x + 1, y)$$$. The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $$$(x, y)$$$ it will move to the point $$$(x - 1, y + 1)$$$, and if it goes the direction U, then it will move to the point $$$(x, y + 2)$$$.You task is to determine the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$.

The first line contains two integers $$$x_1, y_1$$$ ($$$0 \le x_1, y_1 \le 10^9$$$) — the initial coordinates of the ship. The second line contains two integers $$$x_2, y_2$$$ ($$$0 \le x_2, y_2 \le 10^9$$$) — the coordinates of the destination point. It is guaranteed that the initial coordinates and destination point coordinates are different. The third line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string $$$s$$$. The fourth line contains the string $$$s$$$ itself, consisting only of letters U, D, L and R.

The only line should contain the minimal number of days required for the ship to reach the point $$$(x_2, y_2)$$$. If it's impossible then print "-1".

NoteIn the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $$$(0, 0)$$$ $$$\rightarrow$$$ $$$(1, 1)$$$ $$$\rightarrow$$$ $$$(2, 2)$$$ $$$\rightarrow$$$ $$$(3, 3)$$$ $$$\rightarrow$$$ $$$(4, 4)$$$ $$$\rightarrow$$$ $$$(4, 6)$$$.In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 3)$$$ $$$\rightarrow$$$ $$$(0, 1)$$$ $$$\rightarrow$$$ $$$(0, 0)$$$.In the third example the ship can never reach the point $$$(0, 1)$$$.

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

immutable int INF = 10L ^^ 9 + 23;
immutable int N = 10 ^^ 5;
immutable int MXDST = 2 * 10 ^^ 9;

void main()
{
    int x1, y1, x2, y2;
    readf("%s %s", &x1, &y1);
    readln;
    readf("%s %s", &x2, &y2);
    readln;

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

    auto s = readln.chomp.to!(char[]);

    void swtch(ref int i1, ref int i2, char c1, char c2) {
        swap(i1, i2);
        foreach (ref e; s) {
            if (e == c1) e = c2;
            else if (e == c2) e = c1;
        }
    }

    if (x1 > x2) swtch(x1, x2, 'L', 'R');
    if (y1 > y2) swtch(y1, y2, 'U', 'D');

    int[4] cnt;
    cnt[] = 0;
    foreach (e; s) {
        if (e == 'U') cnt[0] += 1;
        if (e == 'R') cnt[1] += 1;
        if (e == 'D') cnt[2] += 1;
        if (e == 'L') cnt[3] += 1;
    }

    long bins() {
        bool isOk(long steps) {
            long[4] curcnt;
            long whole = steps / n;
            int rst = steps % n;

            curcnt[] = cnt[] * whole;
            curcnt[0] += s[0 .. rst].count!(x => x == 'U');
            curcnt[1] += s[0 .. rst].count!(x => x == 'R');
            curcnt[2] += s[0 .. rst].count!(x => x == 'D');
            curcnt[3] += s[0 .. rst].count!(x => x == 'L');

            long curx = x1 + curcnt[1] - curcnt[3];
            long cury = y1 + curcnt[0] - curcnt[2];

            return abs(curx - x2) + abs(cury - y2) <= steps;
        }

        long le = 1, r = N.to!long * MXDST + 1;
        while (le < r) {
            long m = (le + r) / 2;
            if (isOk(m)) r = m;
            else le = m+1;
        }

        return le <= N.to!long * MXDST ? le : -1;
    }

    bins().writeln;
}

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

immutable int INF = 10L ^^ 9 + 23;
immutable int N = 10 ^^ 5;
immutable int MXDST = 2 * 10 ^^ 9;

void main()
{
    int x1, y1, x2, y2;
    readf("%s %s", &x1, &y1);
    readln;
    readf("%s %s", &x2, &y2);
    readln;

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

    auto s = readln.chomp.to!(char[]);

    void swtch(ref int i1, ref int i2, char c1, char c2) {
        if (i1 > i2) {
            swap(i1, i2);
            foreach (ref e; s) {
                if (e == c1) e = c2;
                else if (e == c2) e = c1;
            }
        }
    }

    swtch(x1, x2, 'L', 'R');
    swtch(y1, y2, 'U', 'D');

    int[4] cnt;
    cnt[] = 0;
    foreach (e; s) {
        if (e == 'U') cnt[0] += 1;
        if (e == 'R') cnt[1] += 1;
        if (e == 'D') cnt[2] += 1;
        if (e == 'L') cnt[3] += 1;
    }

    long bins() {
        bool isOk(long steps) {
            long[4] curcnt;
            long whole = steps / n;
            int rst = steps % n;

            curcnt[] = cnt[] * whole;
            curcnt[0] += s[0 .. rst].count!(x => x == 'U');
            curcnt[1] += s[0 .. rst].count!(x => x == 'R');
            curcnt[2] += s[0 .. rst].count!(x => x == 'D');
            curcnt[3] += s[0 .. rst].count!(x => x == 'L');

            long curx = x1 + curcnt[1] - curcnt[3];
            long cury = y1 + curcnt[0] - curcnt[2];

            return abs(curx - x2) + abs(cury - y2) <= steps;
        }

        long le = 1, r = N.to!long * MXDST + 1;
        while (le < r) {
            long m = (le + r) / 2;
            if (isOk(m)) r = m;
            else le = m+1;
        }

        return le <= N * MXDST ? le : -1;
    }

    bins().writeln;
}

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

immutable int INF = 10L ^^ 9 + 23;
immutable int N = 10 ^^ 5;
immutable int MXDST = 2 * 10 ^^ 9;

void main()
{
    int x1, y1, x2, y2;
    readf("%s %s", &x1, &y1);
    readln;
    readf("%s %s", &x2, &y2);
    readln;

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

    auto s = readln.chomp.to!(char[]);

    void swtch(ref int i1, ref int i2, char c1, char c2) {
        if (i1 > i2) {
            swap(i1, i2);
            foreach (ref e; s) {
                if (e == c1) e = c2;
                else if (e == c2) e = c1;
            }
        }
    }

    swtch(x1, x2, 'L', 'R');
    swtch(y1, y2, 'U', 'D');

    int[4] cnt;
    cnt[] = 0;
    foreach (e; s) {
        if (e == 'U') cnt[0] += 1;
        if (e == 'R') cnt[1] += 1;
        if (e == 'D') cnt[2] += 1;
        if (e == 'L') cnt[3] += 1;
    }

    long bins() {
        bool isOk(long steps) {
            long[4] curcnt;
            long whole = steps / n;
            int rst = steps % n;

            curcnt[] = cnt[] * whole;
            curcnt[0] += s[0 .. rst].count!(x => x == 'U');
            curcnt[1] += s[0 .. rst].count!(x => x == 'R');
            curcnt[2] += s[0 .. rst].count!(x => x == 'D');
            curcnt[3] += s[0 .. rst].count!(x => x == 'L');

            long curx = x1 + curcnt[1] - curcnt[3];
            long cury = y1 + curcnt[0] - curcnt[2];

            return abs(curx - x2) + abs(cury - y2) <= steps;
        }

        long le = 1, r = N * MXDST + 1;
        while (le < r) {
            long m = (le + r) / 2;
            if (isOk(m)) r = m;
            else le = m+1;
        }

        return le <= N * MXDST ? le : -1;
    }

    bins().writeln;
}


You are given a program you want to execute as a set of tasks organized in a dependency graph. The dependency graph is a directed acyclic graph: each task can depend on results of one or several other tasks, and there are no directed circular dependencies between tasks. A task can only be executed if all tasks it depends on have already completed.Some of the tasks in the graph can only be executed on a coprocessor, and the rest can only be executed on the main processor. In one coprocessor call you can send it a set of tasks which can only be executed on it. For each task of the set, all tasks on which it depends must be either already completed or be included in the set. The main processor starts the program execution and gets the results of tasks executed on the coprocessor automatically.Find the minimal number of coprocessor calls which are necessary to execute the given program.

The first line contains two space-separated integers N (1 ≤ N ≤ 105) — the total number of tasks given, and M (0 ≤ M ≤ 105) — the total number of dependencies between tasks. The next line contains N space-separated integers . If Ei = 0, task i can only be executed on the main processor, otherwise it can only be executed on the coprocessor. The next M lines describe the dependencies between tasks. Each line contains two space-separated integers T1 and T2 and means that task T1 depends on task T2 (T1 ≠ T2). Tasks are indexed from 0 to N - 1. All M pairs (T1, T2) are distinct. It is guaranteed that there are no circular dependencies between tasks.

Output one line containing an integer — the minimal number of coprocessor calls necessary to execute the program.

NoteIn the first test, tasks 1 and 3 can only be executed on the coprocessor. The dependency graph is linear, so the tasks must be executed in order 3 -> 2 -> 1 -> 0. You have to call coprocessor twice: first you call it for task 3, then you execute task 2 on the main processor, then you call it for for task 1, and finally you execute task 0 on the main processor.In the second test, tasks 0, 1 and 2 can only be executed on the coprocessor. Tasks 1 and 2 have no dependencies, and task 0 depends on tasks 1 and 2, so all three tasks 0, 1 and 2 can be sent in one coprocessor call. After that task 3 is executed on the main processor.

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    enum spec = ' ' ~ replicate("%s ", vars.length);
    return readf(spec, getAddrTuple(vars).expand) == vars.length;
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Task {
    bool coproc;
    int deps;
    Task*[ ] next;

    void perform(ref Array!(Task*) q, bool traverseCoproc) {
        assert(!deps);
        assert(coproc == traverseCoproc);
        foreach (t; next) {
            assert(t.deps >= 1);
            if (!--t.deps) {
                if (t.coproc == traverseCoproc)
                    t.perform(q, traverseCoproc);
                else
                    q ~= t;
            }
        }
    }
}

Task[100_001] _tasks;

void main() {
    int n, m;
    Array!(Task*)[2] q;
    while (read(n, m)) {
        auto tasks = _tasks[0 .. n + 1];
        version (LocalProject)
            tasks[ ] = Task.init;
        q[0].clear();
        char c;
        foreach (ref t; tasks[0 .. n]) {
            read(c);
            t.coproc = c == '1';
        }
        while (m--) {
            int a, b;
            read(a, b);
            tasks[a].deps++;
            tasks[b].next ~= &tasks[a];
        }
        foreach (ref t; tasks[0 .. n])
            if (!t.deps) {
                t.deps = 1;
                tasks[n].next ~= &t;
            }

        q[0] ~= &tasks[n];
        int result = 0;
        do {
            q[1].clear();
            foreach (t; q[0])
                t.perform(q[1], false);
            q[0].clear();
            result += !q[1].empty;
            foreach (t; q[1])
                t.perform(q[0], true);
        } while (!q[0].empty);
        writeln(result);
    }

    stdout.flush();
    _Exit(0);
}

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

void main() {
    int n,m;
    scan(n,m);
    auto e = readln.split.to!(int[]);
    auto adj = new int[][](n, 0);
    foreach (i ; 0 .. m) {
        int t1,t2;
        scan(t1,t2);
        adj[t1] ~= t2;
    }

    auto memo = new int[](n);
    memo[] = -1;

    int dfs(int i) {
        if (memo[i] > -1) return memo[i];
        if (adj[i].empty) {
            memo[i] = e[i] == 1;
            return memo[i];
        }
        memo[i] = 0;
        if (e[i] == 1) {
            foreach (j ; adj[i]) {
                memo[i] = max(memo[i], dfs(j) + (e[j] == 0));
            }
        }
        else {
            foreach (j ; adj[i]) {
                memo[i] = max(memo[i], dfs(j));
            }
        }

        return memo[i];
    }

    int ans;

    foreach (i ; 0 .. n) {
        ans = max(ans, dfs(i));
    }

    debug {
        writeln(memo);
    }

    writeln(ans);
}

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

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

import std.stdio;
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;

void main(string[] args)
{
  inputFile = stdin;
  auto n = next!int;
  auto m = next!int;
  auto noDependencies = new int[](n);
  auto dependencies = new int[][](n);
  auto dependants = new int[][](n);
  auto type = next!int(n);
  enum main = 0;
  enum copr = 1;
  foreach(dep; 0 .. m)
    {
      auto t1 = next!int;
      auto t2 = next!int;
      noDependencies[t1]++;
      dependencies[t1] ~= t2;
      dependants[t2] ~= t1;
    }
  DList!int[2] todo;
  todo[0] = DList!int();
  todo[1] = DList!int();
  foreach(i; 0 .. n)
    {
      if (noDependencies[i] == 0)
	{
	  todo[type[i]].insertBack(i);
	}
    }
  int coprSets = 0;
  while(true)
    {
      if (todo[0].empty && todo[1].empty)
	{
	  return coprSets.writeln;
	}
      foreach(typeToDo; 0 .. 2)
	{
	  if (typeToDo == copr && !todo[typeToDo].empty)
	    {
	      coprSets++;
	    }
	  while(!todo[typeToDo].empty)
	    {
	      auto ntask = todo[typeToDo].front;
	      todo[typeToDo].removeFront;
	      foreach(dependant; dependants[ntask])
		{
		  noDependencies[dependant]--;
		  if (noDependencies[dependant] == 0)
		    {
		      todo[type[dependant]].insertBack(dependant);
		    }
		}
	    }
	}
    }
}
ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  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.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
File inputFile;
DList!string _words;
void _wordsFill()
{
  while (_words.empty) _words.insertBack(inputFile.readln.split);
}
string popWord()
{
  _wordsFill;
  auto word = _words.front;
  _words.removeFront;
  return word;
}
string peekWord()
{
  _wordsFill;
  return _words.front;
}
T next(T)()
{
  return to!T(popWord);
}
T peek(T)()
{
  return to!T(peekWord);
}
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 core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    enum spec = ' ' ~ replicate("%s ", vars.length);
    return readf(spec, getAddrTuple(vars).expand) == vars.length;
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

enum TraverseMode: ubyte {
    proc,
    coproc,
}

struct Task {
    bool coproc;
    int deps;
    Task*[ ] next;

    bool perform(ref Array!(Task*) q, TraverseMode mode) {
        assert(coproc == (mode == TraverseMode.coproc));
        bool result = false;
        foreach (t; next) {
            assert(t.deps >= 1);
            if (!--t.deps) {
                if (t.coproc == (mode == TraverseMode.coproc))
                    result |= t.perform(q, mode);
                else if (mode == TraverseMode.proc)
                    result |= t.perform(q, TraverseMode.coproc);
                else {
                    q ~= t;
                    result = true;
                }
            }
        }
        return result;
    }
}

int n;
Task[100_001] _tasks;

void main() {
    int m;
    Array!(Task*)[2] q;
    while (read(n, m)) {
        auto tasks = _tasks[0 .. n + 1];
        version (LocalProject)
            tasks[ ] = Task.init;
        q[0].clear();
        char c;
        foreach (ref t; tasks[0 .. n]) {
            read(c);
            t.coproc = c == '1';
        }
        while (m--) {
            int a, b;
            read(a, b);
            tasks[a].deps++;
            tasks[b].next ~= &tasks[a];
        }
        foreach (ref t; tasks[0 .. n])
            if (!t.deps) {
                t.deps = 1;
                tasks[n].next ~= &t;
            }

        q[0] ~= &tasks[n];
        int result = 0;
        for (bool cur = 0; !q[cur].empty; cur = !cur) {
            q[!cur].clear();
            bool called = false;
            foreach (t; q[cur])
                called |= t.perform(q[!cur], TraverseMode.proc);
            result += called;
        }
        writeln(result);
    }

    stdout.flush();
    _Exit(0);
}


During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same.  When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A:  You can transmit the whole level A. Then you need to transmit n·m bytes via the network.  You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit dA, B·w bytes, where dA, B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate dA, B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other. Your task is to find a way to transfer all the k levels and minimize the traffic.

The first line contains four integers n, m, k, w (1 ≤ n, m ≤ 10; 1 ≤ k, w ≤ 1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("."). Please note that the case of the letters matters.

In the first line print the required minimum number of transferred bytes. Then print k pairs of integers x1, y1, x2, y2, ..., xk, yk, describing the way to transfer levels. Pair xi, yi means that level xi needs to be transferred by way yi. If yi equals 0, that means that the level must be transferred using the first way, otherwise yi must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels yi and xi to transfer level xi. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input. If there are multiple optimal solutions, you can print any of them.

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;

immutable int NA = -1;

void main ()
{
	int n, m, k, w;
	while (readf (" %s %s %s %s ", &n, &m, &k, &w) > 0)
	{
		auto a = new string [] [k];
		foreach (u; 0..k)
		{
			foreach (i; 0..n)
			{
				a[u] ~= readln ().strip ();
			}
		}

		auto d = new int [] [] (k, k);
		foreach (u; 0..k)
		{
			d[u][u] = 0;
			foreach (v; 0..u)
			{
				int cur = 0;
				foreach (i; 0..n)
				{
					foreach (j; 0..m)
					{
						cur += (a[u][i][j] !=
						    a[v][i][j]);
					}
				}
				d[u][v] = cur * w;
				d[v][u] = cur * w;
			}
		}

		long res = n * m;
		auto b = new bool [k];
		alias pair = Tuple !(int, "x", int, "y");
		auto e = new pair [k];
		pair [] ans;
		int r = 0;
		b[r] = true;
		foreach (t; 0..k)
		{
			e[t] = pair (int.max, NA);
		}
		e[r] = pair (0, NA);
		ans ~= pair (r, NA);
		foreach (t; 1..k)
		{
			auto z = pair (int.max, NA);
			foreach (v; 0..k)
			{
				if (!b[v])
				{
					if (e[v].x > d[r][v])
					{
						e[v] = pair (d[r][v], r);
					}
					if (z.x > e[v].x)
					{
						z = pair (e[v].x, v);
					}
				}
			}
			assert (z.x < int.max);
			r = z.y;
			if (z.x >= n * m)
			{
				e[r] = pair (n * m, NA);
			}
			b[r] = true;
			res += e[r].x;
			ans ~= pair (r, e[r].y);
		}

		writeln (res);
		foreach (p; ans)
		{
			writeln (p.x + 1, ' ', p.y + 1);
		}
	}
}

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

// build graph
// add a path to each other with the difference price
// add a path to a node zero representing default costs
// find the MST
// print the mst starting with 0.

long cdiff(char[] a, char[] b){
  long sum = 0;
  foreach(i,c;a){
    if(b[i] != c){
      sum++;
    }
  }
  return sum;
}

class Graph{
  char[][] original_nodes;
  long[][] edges;
  size_t vertex;

  void build_with(char[][] nodes, int n, int m, int k, int w){
    this.vertex = 1 + nodes.count;
    this.original_nodes ~= [[' ']];
    this.original_nodes ~= nodes;
    this.edges = new long[][](this.vertex,this.vertex);

    for(size_t i = 0; i < this.original_nodes.length; i++){
      for(size_t j = i; j < this.original_nodes.length; j++){
        if(i == j){
          this.edges[i][i] = -1;
        } else {
          if(i == 0){
            this.edges[0][j] = n*m;
            this.edges[j][0] = n*m;
          } else {
            auto diff = cdiff(original_nodes[i],original_nodes[j]);
            this.edges[i][j] = diff*w;
            this.edges[j][i] = diff*w;
          }
        }
      }
    }
  }
}

class UnionFind{
  size_t[] set;
  size_t[] sz;
  this(size_t n){
    set = new size_t[n];
    sz = new size_t[n];
    for(size_t i = 0; i < n; i++){
      set[i] = i;
      sz[i] = 1;
    }
  }

  bool connected(size_t a,size_t b){
    return root(a) == root(b);
  }

  void connect(size_t a, size_t b){
    size_t ra = root(a);
    size_t rb = root(b);
    if(sz[rb] > sz[ra]){
      set[ra] = set[rb];
      sz[rb] += sz[ra];
    } else {
      set[rb] = set[ra];
      sz[ra] += sz[rb];
    }
  }

  size_t root(size_t a){
    size_t ra = set[a];
    while(ra != set[ra]){
      set[ra] = set[set[ra]];
      ra = set[ra];
    }
    return ra;
  }
}

class PQueue{
  Edge[] ctn;
  size_t size;
  this(Graph g){
    ctn ~= Edge.init;
    for(size_t i = 0; i < g.vertex; i++){
      for(size_t j = 0; j < g.vertex; j++){
        long ev = g.edges[i][j];
        if(ev != -1){
          Edge e = Edge(i,j,ev);
          ctn ~= e;
        }
      }
    }
    this.size = ctn.length;
    build_heap();
  }

  Edge delMin(){
    Edge ret = ctn[1];
    swap(ctn[1],ctn[size-1]);
    this.size--;

    fix_heap(1);

    return ret;
  }

  bool empty(){
    return this.size == 1;
  }

  void fix_heap(size_t i){
    size_t l = 2*i;
    size_t r = 2*i+1;
    size_t smalest = i;
    if(l < this.size && ctn[l].e < ctn[i].e){
      smalest = l;
    } else {
      smalest = i;
    }

    if(r < this.size && ctn[r].e < ctn[smalest].e){
      smalest = r;
    }

    if(smalest != i){
      swap(ctn[i],ctn[smalest]);
      fix_heap(smalest);
    }
  }

  void build_heap(){
    for(size_t i = this.size/2; i > 0; i--){
      fix_heap(i);
    }
  }
}

struct Edge{
  size_t v;
  size_t w;
  long e;
}

class Mst{
  Graph graph;
  Edge[] mst;
  this(Graph g){
    this.graph = g;
    build_mst(g);
  }

  void build_mst(Graph g){
    PQueue pq = new PQueue(g);
    UnionFind uf = new UnionFind(g.vertex);
    while(!pq.empty() && mst.length < g.vertex - 1){
      Edge e = pq.delMin();
      //writeln(pq.ctn);
      if(!uf.connected(e.v,e.w)){
         uf.connect(e.v,e.w);
         mst ~= e;
      }
    }
  }

  void print_with_cost(){
    auto lmst = this.mst.dup;
    auto lvls = lmst.length;
    int[] lvl = new int[lvls+1];
    Edge[] other;

    int sum = 0;
    for(int i = 0; i < lvls; i++){
      sum += lmst[i].e;
    }

    writeln(sum);

    auto ptc = lmst.length;
    //writeln(lmst);
    while(ptc > 0){
      foreach(e;lmst){
        if(e.v == 0 && lvl[e.w] == 0){
          writefln("%s %s",e.w,e.v);
          lvl[e.w]++;
          break;
        } else if(e.w == 0 && lvl[e.v] == 0){
          writefln("%s %s",e.v,e.w);
          lvl[e.v]++;
          break;
        } else if(lvl[e.v] == 0 && lvl[e.w] == 1 && e.v != 0) {
          writefln("%s %s",e.v,e.w);
          lvl[e.v]++;
          break;
        } else if(lvl[e.w] == 0 && lvl[e.v] == 1  && e.w != 0){
          writefln("%s %s",e.w,e.v);
          lvl[e.w]++;
          break;
        }
      }
      ptc--;
    }
    //writeln(lvl);

//     writeln(sum);
//     for(int i = 0; i < lvls; i++){
//       Edge e = lmst[i];
//       if(e.v == 0 || e.w == 0){
//         if(e.v == 0){
//           writefln("%s %s",e.w,e.v);
//           full ~= e.w;
//         } else {
//           writefln("%s %s",e.v,e.w);
//           full ~= e.v;
//         }
//       } else {
//         other += e;
//       }
//     }
//     writeln(lmst);
//     foreach(o;other){
//       if(lvl[e.v] == 1){
//
//       } else {
//
//       }
//     }
  }
}

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

  char[][] d = new char[][](k,m*n);
  for(int i = 0; i < k; i++){
    for(int j = 0; j < m*n; j++){
      char c = '\n';
      while(c == '\n'){
        readf("%c",&c);
      }
      d[i][j] = c;
    }
  }
  Graph g = new Graph();
  g.build_with(d,n,m,k,w);

  Mst mst = new Mst(g);

  mst.print_with_cost();
}

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;

immutable int NA = -1;

void main ()
{
	int n, m, k, w;
	while (readf (" %s %s %s %s ", &n, &m, &k, &w) > 0)
	{
		auto a = new string [] [k];
		foreach (u; 0..k)
		{
			foreach (i; 0..n)
			{
				a[u] ~= readln ().strip ();
			}
		}

		auto d = new int [] [] (k, k);
		foreach (u; 0..k)
		{
			d[u][u] = 0;
			foreach (v; 0..u)
			{
				int cur = 0;
				foreach (i; 0..n)
				{
					foreach (j; 0..m)
					{
						cur += (a[u][i][j] !=
						    a[v][i][j]);
					}
				}
				d[u][v] = cur * w;
				d[v][u] = cur * w;
			}
		}

		long res = n * m;
		auto b = new bool [k];
		alias pair = Tuple !(int, "x", int, "y");
		auto e = new pair [k];
		pair [] ans;
		int r = 0;
		b[r] = true;
		foreach (t; 0..k)
		{
			e[t] = pair (int.max, NA);
		}
		e[r] = pair (0, NA);
		ans ~= pair (r, NA);
		foreach (t; 1..k)
		{
			auto z = pair (int.max, NA);
			foreach (v; 0..k)
			{
				if (!b[v])
				{
					if (e[v].x > d[r][v])
					{
						e[v] = pair (d[r][v], r);
					}
					if (z.x > e[v].x)
					{
						z = pair (e[v].x, v);
					}
				}
			}
			assert (z.x < int.max);
			if (z.x >= n * m)
			{
				e[z.y].y = NA;
			}
			r = z.y;
			b[r] = true;
			res += e[r].x;
			ans ~= pair (r, e[r].y);
		}

		writeln (res);
		foreach (p; ans)
		{
			writeln (p.x + 1, ' ', p.y + 1);
		}
	}
}

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

// build graph
// add a path to each other with the difference price
// add a path to a node zero representing default costs
// find the MST
// print the mst starting with 0.

long cdiff(char[] a, char[] b){
  long sum = 0;
  foreach(i,c;a){
    if(b[i] != c){
      sum++;
    }
  }
  return sum;
}

class Graph{
  char[][] original_nodes;
  long[][] edges;
  size_t vertex;

  void build_with(char[][] nodes, int n, int m, int k, int w){
    this.vertex = 1 + nodes.count;
    this.original_nodes ~= [[' ']];
    this.original_nodes ~= nodes;
    this.edges = new long[][](this.vertex,this.vertex);

    for(size_t i = 0; i < this.original_nodes.length; i++){
      for(size_t j = i; j < this.original_nodes.length; j++){
        if(i == j){
          this.edges[i][i] = -1;
        } else {
          if(i == 0){
            this.edges[0][j] = n*m;
            this.edges[j][0] = -1;
          } else {
            auto diff = cdiff(original_nodes[i],original_nodes[j]);
            this.edges[i][j] = diff*w;
            this.edges[j][i] = -1;
          }
        }
      }
    }
  }
}

class UnionFind{
  size_t[] set;
  size_t[] sz;
  this(size_t n){
    set = new size_t[n];
    sz = new size_t[n];
    for(size_t i = 0; i < n; i++){
      set[i] = i;
      sz[i] = 1;
    }
  }

  bool connected(size_t a,size_t b){
    return root(a) == root(b);
  }

  void connect(size_t a, size_t b){
    size_t ra = root(a);
    size_t rb = root(b);
    if(sz[rb] > sz[ra]){
      set[ra] = set[rb];
      sz[rb] += sz[ra];
    } else {
      set[rb] = set[ra];
      sz[ra] += sz[rb];
    }
  }

  size_t root(size_t a){
    size_t ra = set[a];
    while(ra != set[ra]){
      set[ra] = set[set[ra]];
      ra = set[ra];
    }
    return ra;
  }
}

class PQueue{
  Edge[] ctn;
  size_t size;
  this(Graph g){
    ctn ~= Edge.init;
    for(size_t i = 0; i < g.vertex; i++){
      for(size_t j = 0; j < g.vertex; j++){
        long ev = g.edges[i][j];
        if(ev != -1){
          Edge e = Edge(i,j,ev);
          ctn ~= e;
        }
      }
    }
    this.size = ctn.length;
    build_heap();
  }

  Edge delMin(){
    Edge ret = ctn[1];
    swap(ctn[1],ctn[size-1]);
    this.size--;

    fix_heap(1);

    return ret;
  }

  bool empty(){
    return this.size == 1;
  }

  void fix_heap(size_t i){
    size_t l = 2*i;
    size_t r = 2*i+1;
    size_t smalest = i;
    if(l < this.size && ctn[l].e < ctn[i].e){
      smalest = l;
    } else {
      smalest = i;
    }

    if(r < this.size && ctn[r].e < ctn[smalest].e){
      smalest = r;
    }

    if(smalest != i){
      swap(ctn[i],ctn[smalest]);
      fix_heap(smalest);
    }
  }

  void build_heap(){
    for(size_t i = this.size/2; i > 0; i--){
      fix_heap(i);
    }
  }
}

struct Edge{
  size_t v;
  size_t w;
  long e;
}

class Mst{
  Graph graph;
  Edge[] mst;
  this(Graph g){
    this.graph = g;
    build_mst(g);
  }

  void build_mst(Graph g){
    PQueue pq = new PQueue(g);
    UnionFind uf = new UnionFind(g.vertex);
    while(!pq.empty() && mst.length < g.vertex - 1){
      Edge e = pq.delMin();
      //writeln(pq.ctn);
      if(!uf.connected(e.v,e.w)){
         uf.connect(e.v,e.w);
         mst ~= e;
      }
    }
  }

  void print_with_cost(){
    sort!((a,b){
      size_t ax = min(a.v,a.w);
      size_t bx = min(b.v,b.w);
      return ax < bx;
    })(this.mst);
    long sum = 0;
    foreach(e;this.mst){
      sum += e.e;
    }
    size_t[] lvl = new size_t[this.mst.length+1];

    writeln(sum);
    foreach(e;this.mst){
      auto v = min(e.v,e.w);
      auto w = max(e.v,e.w);
      if(v == 0){
        lvl[w]++;
        writefln("%s %s",w,v);
      } else {
        if(lvl[v] == 0){
          lvl[v]++;
          writefln("%s %s",v,w);
        } else {
          lvl[w]++;
          writefln("%s %s",w,v);
        }
      }
    }
  }
}

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

  char[][] d = new char[][](k,m*n);
  for(int i = 0; i < k; i++){
    for(int j = 0; j < m*n; j++){
      char c = '\n';
      while(c == '\n'){
        readf("%c",&c);
      }
      d[i][j] = c;
    }
  }
  Graph g = new Graph();
  g.build_with(d,n,m,k,w);

  Mst mst = new Mst(g);

  mst.print_with_cost();
}

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

// build graph
// add a path to each other with the difference price
// add a path to a node zero representing default costs
// find the MST
// print the mst starting with 0.

long cdiff(char[] a, char[] b){
  long sum = 0;
  foreach(i,c;a){
    if(b[i] != c){
      sum++;
    }
  }
  return sum;
}

class Graph{
  char[][] original_nodes;
  long[][] edges;
  size_t vertex;

  void build_with(char[][] nodes, int n, int m, int k, int w){
    this.vertex = 1 + nodes.count;
    this.original_nodes ~= [[' ']];
    this.original_nodes ~= nodes;
    this.edges = new long[][](this.vertex,this.vertex);

    for(size_t i = 0; i < this.original_nodes.length; i++){
      for(size_t j = i; j < this.original_nodes.length; j++){
        if(i == j){
          this.edges[i][i] = -1;
        } else {
          if(i == 0){
            this.edges[0][j] = n*m;
            this.edges[j][0] = n*m;
          } else {
            auto diff = cdiff(original_nodes[i],original_nodes[j]);
            this.edges[i][j] = diff*w;
            this.edges[j][i] = diff*w;
          }
        }
      }
    }
  }
}

class UnionFind{
  size_t[] set;
  size_t[] sz;
  this(size_t n){
    set = new size_t[n];
    sz = new size_t[n];
    for(size_t i = 0; i < n; i++){
      set[i] = i;
      sz[i] = 1;
    }
  }

  bool connected(size_t a,size_t b){
    return root(a) == root(b);
  }

  void connect(size_t a, size_t b){
    size_t ra = root(a);
    size_t rb = root(b);
    if(sz[rb] > sz[ra]){
      set[ra] = set[rb];
      sz[rb] += sz[ra];
    } else {
      set[rb] = set[ra];
      sz[ra] += sz[rb];
    }
  }

  size_t root(size_t a){
    size_t ra = set[a];
    while(ra != set[ra]){
      set[ra] = set[set[ra]];
      ra = set[ra];
    }
    return ra;
  }
}

class PQueue{
  Edge[] ctn;
  size_t size;
  this(Graph g){
    ctn ~= Edge.init;
    for(size_t i = 0; i < g.vertex; i++){
      for(size_t j = 0; j < g.vertex; j++){
        long ev = g.edges[i][j];
        if(ev != -1){
          Edge e = Edge(i,j,ev);
          ctn ~= e;
        }
      }
    }
    this.size = ctn.length;
    build_heap();
  }

  Edge delMin(){
    Edge ret = ctn[1];
    swap(ctn[1],ctn[size-1]);
    this.size--;

    fix_heap(1);

    return ret;
  }

  bool empty(){
    return this.size == 1;
  }

  void fix_heap(size_t i){
    size_t l = 2*i;
    size_t r = 2*i+1;
    size_t smalest = i;
    if(l < this.size && ctn[l].e < ctn[i].e){
      smalest = l;
    } else {
      smalest = i;
    }

    if(r < this.size && ctn[r].e < ctn[smalest].e){
      smalest = r;
    }

    if(smalest != i){
      swap(ctn[i],ctn[smalest]);
      fix_heap(smalest);
    }
  }

  void build_heap(){
    for(size_t i = this.size/2; i > 0; i--){
      fix_heap(i);
    }
  }
}

struct Edge{
  size_t v;
  size_t w;
  long e;
}

class Mst{
  Graph graph;
  Edge[] mst;
  this(Graph g){
    this.graph = g;
    build_mst(g);
  }

  void build_mst(Graph g){
    PQueue pq = new PQueue(g);
    UnionFind uf = new UnionFind(g.vertex);
    while(!pq.empty() && mst.length < g.vertex - 1){
      Edge e = pq.delMin();
      //writeln(pq.ctn);
      if(!uf.connected(e.v,e.w)){
         uf.connect(e.v,e.w);
         mst ~= e;
      }
    }
  }

  void print_with_cost(){
    //writeln(this.graph.edges);
    //writeln(this.graph.original_nodes);
    //writefln("%s",this.mst.length);
    long[2][] pt;
    long sum;

    foreach(e;this.mst){
      if(e.v == 0 || e.w == 0){
        size_t v;
        if(e.v == 0){
          v = e.w;
        } else {
          v = e.v;
        }
        pt ~= [v,0];
        sum += e.e;
      } else {
        pt ~= [e.v,e.w];
        sum += e.e;
      }
    }
    writeln(sum);
    foreach(p;pt){
      writefln("%s %s",p[0],p[1]);
    }
  }
}

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

  char[][] d = new char[][](k,m*n);
  for(int i = 0; i < k; i++){
    for(int j = 0; j < m*n; j++){
      char c = '\n';
      while(c == '\n'){
        readf("%c",&c);
      }
      d[i][j] = c;
    }
  }
  Graph g = new Graph();
  g.build_with(d,n,m,k,w);

  Mst mst = new Mst(g);

  mst.print_with_cost();
}

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

// build graph
// add a path to each other with the difference price
// add a path to a node zero representing default costs
// find the MST
// print the mst starting with 0.

long cdiff(char[] a, char[] b){
  long sum = 0;
  foreach(i,c;a){
    if(b[i] != c){
      sum++;
    }
  }
  return sum;
}

class Graph{
  char[][] original_nodes;
  long[][] edges;
  size_t vertex;

  void build_with(char[][] nodes, int n, int m, int k, int w){
    this.vertex = 1 + nodes.count;
    this.original_nodes ~= [[' ']];
    this.original_nodes ~= nodes;
    this.edges = new long[][](this.vertex,this.vertex);

    for(size_t i = 0; i < this.original_nodes.length; i++){
      for(size_t j = i; j < this.original_nodes.length; j++){
        if(i == j){
          this.edges[i][i] = -1;
        } else {
          if(i == 0){
            this.edges[0][j] = n*m;
            this.edges[j][0] = n*m;
          } else {
            auto diff = cdiff(original_nodes[i],original_nodes[j]);
            this.edges[i][j] = diff*w;
            this.edges[j][i] = diff*w;
          }
        }
      }
    }
  }
}

class UnionFind{
  size_t[] set;
  size_t[] sz;
  this(size_t n){
    set = new size_t[n];
    sz = new size_t[n];
    for(size_t i = 0; i < n; i++){
      set[i] = i;
      sz[i] = 1;
    }
  }

  bool connected(size_t a,size_t b){
    return root(a) == root(b);
  }

  void connect(size_t a, size_t b){
    size_t ra = root(a);
    size_t rb = root(b);
    if(sz[rb] > sz[ra]){
      set[ra] = set[rb];
      sz[rb] += sz[ra];
    } else {
      set[rb] = set[ra];
      sz[ra] += sz[rb];
    }
  }

  size_t root(size_t a){
    size_t ra = set[a];
    while(ra != set[ra]){
      set[ra] = set[set[ra]];
      ra = set[ra];
    }
    return ra;
  }
}

class PQueue{
  Edge[] ctn;
  size_t size;
  this(Graph g){
    ctn ~= Edge.init;
    for(size_t i = 0; i < g.vertex; i++){
      for(size_t j = 0; j < g.vertex; j++){
        long ev = g.edges[i][j];
        if(ev != -1){
          Edge e = Edge(i,j,ev);
          ctn ~= e;
        }
      }
    }
    this.size = ctn.length;
    build_heap();
  }

  Edge delMin(){
    Edge ret = ctn[1];
    swap(ctn[1],ctn[size-1]);
    this.size--;

    fix_heap(1);

    return ret;
  }

  bool empty(){
    return this.size == 1;
  }

  void fix_heap(size_t i){
    size_t l = 2*i;
    size_t r = 2*i+1;
    size_t smalest = i;
    if(l < this.size && ctn[l].e < ctn[i].e){
      smalest = l;
    } else {
      smalest = i;
    }

    if(r < this.size && ctn[r].e < ctn[smalest].e){
      smalest = r;
    }

    if(smalest != i){
      swap(ctn[i],ctn[smalest]);
      fix_heap(smalest);
    }
  }

  void build_heap(){
    for(size_t i = this.size/2; i > 0; i--){
      fix_heap(i);
    }
  }
}

struct Edge{
  size_t v;
  size_t w;
  long e;
}

class Mst{
  Graph graph;
  Edge[] mst;
  this(Graph g){
    this.graph = g;
    build_mst(g);
  }

  void build_mst(Graph g){
    PQueue pq = new PQueue(g);
    UnionFind uf = new UnionFind(g.vertex);
    while(!pq.empty() && mst.length < g.vertex - 1){
      Edge e = pq.delMin();
      //writeln(pq.ctn);
      if(!uf.connected(e.v,e.w)){
         uf.connect(e.v,e.w);
         mst ~= e;
      }
    }
  }

  void print_with_cost(){
    sort!((a,b){
      size_t ax = min(a.v,a.w);
      size_t bx = min(b.v,b.w);
      return ax < bx;
    })(this.mst);
    long sum = 0;
    foreach(e;this.mst){
      sum += e.e;
    }
    size_t[] lvl = new size_t[this.mst.length+1];

    writeln(sum);
    foreach(e;this.mst){
      if(lvl[e.v] == 0){
        lvl[e.v]++;
        writefln("%s %s",e.v,e.w);
      } else {
        lvl[e.w]++;
        writefln("%s %s",e.w,e.v);
      }
      //writeln(lvl);
    }
  }
}

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

  char[][] d = new char[][](k,m*n);
  for(int i = 0; i < k; i++){
    for(int j = 0; j < m*n; j++){
      char c = '\n';
      while(c == '\n'){
        readf("%c",&c);
      }
      d[i][j] = c;
    }
  }
  Graph g = new Graph();
  g.build_with(d,n,m,k,w);

  Mst mst = new Mst(g);

  mst.print_with_cost();
}


A known chef has prepared $$$n$$$ dishes: the $$$i$$$-th dish consists of $$$a_i$$$ grams of fish and $$$b_i$$$ grams of meat. The banquet organizers estimate the balance of $$$n$$$ dishes as follows. The balance is equal to the absolute value of the difference between the total mass of fish and the total mass of meat.Technically, the balance equals to $$$\left|\sum\limits_{i=1}^n a_i - \sum\limits_{i=1}^n b_i\right|$$$. The smaller the balance, the better.In order to improve the balance, a taster was invited. He will eat exactly $$$m$$$ grams of food from each dish. For each dish, the taster determines separately how much fish and how much meat he will eat. The only condition is that he should eat exactly $$$m$$$ grams of each dish in total.Determine how much of what type of food the taster should eat from each dish so that the value of the balance is as minimal as possible. If there are several correct answers, you may choose any of them.

The first line of input data contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of the test cases. Each test case's description is preceded by a blank line. Next comes a line that contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$; $$$0 \leq m \leq 10^6$$$). The next $$$n$$$ lines describe dishes, the $$$i$$$-th of them contains a pair of integers $$$a_i$$$ and $$$b_i$$$ ($$$0 \leq a_i, b_i \le 10^6$$$) — the masses of fish and meat in the $$$i$$$-th dish. It is guaranteed that it is possible to eat $$$m$$$ grams of food from each dish. In other words, $$$m \leq a_i+b_i$$$ for all $$$i$$$ from $$$1$$$ to $$$n$$$ inclusive. The sum of all $$$n$$$ values over all test cases in the test does not exceed $$$2 \cdot 10^5$$$.

For each test case, print on the first line the minimal balance value that can be achieved by eating exactly $$$m$$$ grams of food from each dish. Then print $$$n$$$ lines that describe a way to do this: the $$$i$$$-th line should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \leq x_i \leq a_i$$$; $$$0 \leq y_i \leq b_i$$$; $$$x_i+y_i=m$$$), where $$$x_i$$$ is how many grams of fish taster should eat from the $$$i$$$-th meal and $$$y_i$$$ is how many grams of meat. If there are several ways to achieve a minimal balance, find any of them.

// Author: Ivan Kazmenko (gassa@mail.ru)
module solution;
import std.algorithm;
import std.conv;
import std.math;
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);
		auto a = new int [n];
		auto b = new int [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s") (a[i], b[i]);
		}

		auto x = new long [n];
		auto y = new long [n];
		long sa = 0;
		long sb = 0;
		foreach (i; 0..n)
		{
			x[i] = min (a[i], m);
			y[i] = m - x[i];
			sa += a[i] - x[i];
			sb += b[i] - y[i];
		}

		foreach (i; 0..n)
		{
			auto cur = max (0, sb - sa) >> 1;
			auto yAlt = min (b[i], m);
			auto xAlt = m - yAlt;
			auto delta = min (cur, x[i] - xAlt);
			x[i] -= delta;
			y[i] += delta;
			sa += delta;
			sb -= delta;
		}

		writeln (abs (sa - sb));
		foreach (i; 0..n)
		{
			writeln (x[i], " ", y[i]);
		}
	}
}

// Author: Ivan Kazmenko (gassa@mail.ru)
module solution;
import std.algorithm;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		auto a = new int [n];
		auto b = new int [n];
		auto m = new int [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s %s") (a[i], b[i], m[i]);
		}

		alias Segment = Tuple !(int, q{hi}, int, q{lo}, int, q{id});
		Segment [] [int] s;
		foreach (i; 0..n)
		{
			int total = a[i] + b[i] - m[i];
			int hiA = min (a[i], m[i]);
			int loB = m[i] - hiA;
			int hiB = min (b[i], m[i]);
			int loA = m[i] - hiB;
			s[total] ~= Segment (a[i] - loA, a[i] - hiA, i);
		}

		auto x = new long [n];
		auto y = new long [n];
		int res = 0;
		foreach (total, t; s)
		{
			sort (t);
			writeln (t);
			int cur = int.min;
			foreach (ref seg; t)
			{
				if (cur < seg.lo)
				{
					cur = seg.hi;
					res += 1;
				}
				auto i = seg.id;
				x[seg.id] = a[i] - cur;
				y[seg.id] = m[i] - x[seg.id];
			}
		}

		writeln (res);
		foreach (i; 0..n)
		{
			writeln (x[i], " ", y[i]);
		}
	}
}


A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $$$n$$$ rows and $$$m$$$ columns. The rows of the floor are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and columns of the floor are numbered from $$$1$$$ to $$$m$$$ from left to right. The cell on the intersection of the $$$r$$$-th row and the $$$c$$$-th column is denoted as $$$(r,c)$$$. The initial position of the robot is $$$(r_b, c_b)$$$.In one second, the robot moves by $$$dr$$$ rows and $$$dc$$$ columns, that is, after one second, the robot moves from the cell $$$(r, c)$$$ to $$$(r + dr, c + dc)$$$. Initially $$$dr = 1$$$, $$$dc = 1$$$. If there is a vertical wall (the left or the right walls) in the movement direction, $$$dc$$$ is reflected before the movement, so the new value of $$$dc$$$ is $$$-dc$$$. And if there is a horizontal wall (the upper or lower walls), $$$dr$$$ is reflected before the movement, so the new value of $$$dr$$$ is $$$-dr$$$.Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at $$$(r_d, c_d)$$$. The job of the robot is to clean that dirty cell.  Illustration for the first example. The blue arc is the robot. The red star is the target dirty cell. Each second the robot cleans a row and a column, denoted by yellow stripes. Given the floor size $$$n$$$ and $$$m$$$, the robot's initial position $$$(r_b, c_b)$$$ and the dirty cell's position $$$(r_d, c_d)$$$, find the time for the robot to do its job.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. A test case consists of only one line, containing six integers $$$n$$$, $$$m$$$, $$$r_b$$$, $$$c_b$$$, $$$r_d$$$, and $$$c_d$$$ ($$$1 \le n, m \le 100$$$, $$$1 \le r_b, r_d \le n$$$, $$$1 \le c_b, c_d \le m$$$) — the sizes of the room, the initial position of the robot and the position of the dirt cell.

For each test case, print an integer — the time for the robot to clean the dirty cell. We can show that the robot always cleans the dirty cell eventually.

NoteIn the first example, the floor has the size of $$$10\times 10$$$. The initial position of the robot is $$$(6, 1)$$$ and the position of the dirty cell is $$$(2, 8)$$$. See the illustration of this example in the problem statement.In the second example, the floor is the same, but the initial position of the robot is now $$$(9, 9)$$$, and the position of the dirty cell is $$$(1, 1)$$$. In this example, the robot went straight to the dirty cell and clean it.   In the third example, the floor has the size $$$9 \times 8$$$. The initial position of the robot is $$$(5, 6)$$$, and the position of the dirty cell is $$$(2, 1)$$$.   In the fourth example, the floor has the size $$$6 \times 9$$$. The initial position of the robot is $$$(2, 2)$$$ and the position of the dirty cell is $$$(5, 8)$$$.   In the last example, the robot was already standing in the same column as the dirty cell, so it can clean the cell right away.

import std;

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

    foreach (test_index; 0 .. tests) {
        int n, m, rb, cb, rd, cd;
        readf("%s %s %s %s %s %s\n", n, m, rb, cb, rd, cd);

        int reach_line;
        int reach_column;

        if (rb <= rd)
            reach_line = rd - rb;
        else
            reach_line = n - rb + n - rd;

        if (cb <= cd)
            reach_column = cd - cb;
        else
            reach_column = m - cb + m - cd;

        writeln(min(reach_line, reach_column));
    }
}
// ""

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

void read(S...)(ref S args) {
  auto input = readln.split;
  enforce(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

void main() {
  int T;
  read(T);
  while (T--) {
    int n, m, x, y, X, Y;
    read(n, m, x, y, X, Y);
    int dr = 1, dc = 1;
    int time = 0;
    while (x != X && y != Y) {
      // check dir
      if (x == n) dr = -1;
      if (x == 0) dr = 1;
      if (y == m) dc = -1;
      if (y == 0) dc = 1;

      x += dr;
      y += dc;

      time++;
    }
    writeln(time);
  }
}

void main() { runSolver(); }

void problem() {
  auto QN = scan!long;
  auto Q = scan!long(6 * QN).chunks(6);

  auto solve() {
    foreach(q; Q) {
      auto F = Point(q[0], q[1]);
      auto S = Point(q[2], q[3]);
      auto G = Point(q[4], q[5]);

      writeln(min(
        G.x < S.x ? 2*(F.x - S.x) + (S.x - G.x) : G.x - S.x,
        G.y < S.y ? 2*(F.y - S.y) + (S.y - G.y) : G.y - S.y,
      ));
    }
  }

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

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

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)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

//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 m = RD!int;
		auto rb = RD!int-1;
		auto cb = RD!int-1;
		auto rd = RD!int-1;
		auto cd = RD!int-1;

		int dr = 1, dc = 1;
		while (true)
		{
			if (rb == rd || cb == cd) break;
			if (rb + dr >= n)
				dr = -1;
			if (rb + dr < 0)
				dr = 1;
			if (cb + dc >= m)
				dc = -1;
			if (cb + dc < 0)
				dc = 1;
			rb += dr;
			cb += dc;
			++ans[ti];
		}
	}

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

// 提出解
void solve(){
	foreach(_; 0 .. scan!int){
		int n = scan!int, m = scan!int;
		int rb = scan!int - 1, cb = scan!int - 1;
		int rd = scan!int - 1, cd = scan!int - 1;

		int high = n + m;
		int ans = high;
		if(rd >= rb) ans.mini(rd - rb);
		else ans.mini(n - 1 - rb + n - 1 - rd);
		if(cd >= cb) ans.mini(cd - cb);
		else ans.mini(m - 1 - cb + m - 1 - cd);

		ans.print;
	}
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// 愚直解
void jury(){
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// テストケース
void gen(){
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// テンプレ
import std;
bool DEBUG = 0;
void main(string[] args){
	if(args.canFind("-debug")) DEBUG = 1;
	if(args.canFind("-gen")) gen; else if(args.canFind("-jury")) jury; else solve;
}
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); }
void print(T)(T t){ writeln(t); }
void print(T, A ...)(T t, A a){ stdout.write(t, " "), print(a); }
string unsplit(T)(T xs, string d = " "){ return xs.array.to!(string[]).join(d); }
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)(int n){ return n.iota.map!(i => scan!T()).array; }
T mini(T)(ref T x, T y){ if(x > y) x = y; return x; }
T maxi(T)(ref T x, T y){ if(x < y) x = y; return x; }
T mid(T)(T l, T r, bool delegate(T) f){
	T m = (l + r) / 2; (f(m)? l: r) = m; return f(l)? f(r - 1)? r: mid(l, r, f): l;
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// ライブラリ（基本）

class UnionFind{
	this(int n){ foreach(i; 0 .. n) R ~= i, K ~= [i]; } int[] R; int[][] K;
	void unite(int a, int b){
		int ra = R[a], rb = R[b]; if(ra == rb) return;
		if(K[ra].length < K[rb].length) unite(b, a);
		else foreach(k; K[rb]) R[k] = ra, K[ra] ~= k;
	}
	int find(int a){ return R[a]; }
	int getSize(int a){ return K[R[a]].length.to!int; }
}
class Queue(T){
	private T[] xs; private uint i, j;
	this(T[] xs = []){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j - i; }
	bool isEmpty(){ return j == i; }
	void enq(T x){ while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1; xs[j ++] = x; }
	T deq(){ assert(i < j); return xs[i ++]; }
	T peek(){ assert(i < j); return xs[i]; }
	void flush(){ i = j; }
	alias empty = isEmpty, front = peek, popFront = deq, pop = deq, push = enq, top = peek;
	Queue opOpAssign(string op)(T x) if(op == "~"){ enq(x); return this; }
	T opIndex(uint li){ assert(i + li < j); return xs[i + li]; }
	static Queue!T opCall(T[] xs){ return new Queue!T(xs); }
	T[] array(){ return xs[i .. j]; }
	override string toString(){ return array.to!string; }
}
class Stack(T){
	private T[] xs; private uint j;
	this(T[] xs = []){ this.xs = xs; j = xs.length.to!uint; }
	uint length(){ return j; }
	bool isEmpty(){ return j == 0; }
	void push(T x){ while(j + 1 >= xs.length) xs.length = xs.length * 2 + 1; xs[j ++] = x; }
	T pop(){ assert(j > 0); return xs[-- j]; }
	T peek(){ assert(j > 0); return xs[j - 1]; }
	void clear(){ j = 0; }
	alias empty = isEmpty, front = peek, popFront = pop, top = peek;
	Stack opOpAssign(string op)(T x) if(op == "~"){ push(x); return this; }
	T opIndex(uint li){ assert(j > 0 && j - 1 >= li); return xs[j - 1 - li]; }
	static Stack!T opCall(T[] xs = []){ return new Stack!T(xs); }
	T[] array(){ return xs[0 .. j]; }
	override string toString(){ return array.to!string; }
}

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //
// ライブラリ（追加）

import std;

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

    foreach (test_index; 0 .. tests) {
        int n, m, rb, cb, rd, cd;
        readf("%s %s %s %s %s %s\n", n, m, rb, cb, rd, cd);

        int reach_line;
        int reach_column;

        if (rb <= rd)
            reach_line = rd - rb;
        else
            reach_line = m - rb + m - rd;

        if (cb <= cd)
            reach_column = cd - cb;
        else
            reach_column = n - cb + n - cd;

        writeln(min(reach_line, reach_column));
    }
}
// ""

import std;

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

    foreach (test_index; 0 .. tests) {
        int n, m, rb, cb, rd, cd;
        readf("%s %s %s %s %s %s\n", n, m, rb, cb, rd, cd);

        int reach_line;
        int reach_column;

        if (rb <= rd)
            reach_line = rd - rb;
        else
            reach_line = m - rb + m - rd;

        if (cb <= cd)
            reach_column = cd - cb;
        else
            reach_column = m - cb + m - cd;

        writeln(min(reach_line, reach_column));
    }
}
// ""

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

void read(S...)(ref S args) {
  auto input = readln.split;
  enforce(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

void main() {
  int T;
  read(T);
  while (T--) {
    int n, m, x, y, X, Y;
    read(n, m, x, y, X, Y);
    int dr = 1, dc = 1;
    int time = 0;
    while (x != X && y != Y) {
      // check dir
      if (x == n) dr = -1;
      if (x == 0) dr = 1;
      if (y == m) dc = -1;
      if (y == 0) dc = 1;

      x += dr;
      y += dc;

      time++;

      if (time == 20) break;
    }
    writeln(time);
  }
}


You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.For instance, if we are given an array $$$[10, 20, 30, 40]$$$, we can permute it so that it becomes $$$[20, 40, 10, 30]$$$. Then on the first and the second positions the integers became larger ($$$20>10$$$, $$$40>20$$$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $$$2$$$. Read the note for the first example, there is one more demonstrative test case.Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array.

Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.

NoteIn the first sample, one of the best permutations is $$$[1, 5, 5, 3, 10, 1, 1]$$$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.In the second sample, there is no way to increase any element with a permutation, so the answer is 0.

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

void main() {
  alias Tree = RedBlackTree!(int,"a<b",true);
  immutable n = readln.strip.to!int;
  auto a = readln.strip.splitter.map! (i => i.to!int).array[0..n];
  sort (a);
  auto t = make!Tree (a);
  debug stderr.writeln (t);
  int res;
  foreach (i; a) {
    auto r = t.upperBound (i);
    if (!r.empty) {
      int v = r.front;
      debug stderr.writefln ("%d %d", i, v);
      ++res;
      t.removeKey (v);
    }
  }
  writeln (res);
}

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

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

  struct Pair{
    int val, idx;
  }
  auto data=new Pair[](n);
  foreach(i; 0..n) data[i]=Pair(a[i], i);
  sort!((l, r)=>(l.val==r.val ? l.idx<r.idx : l.val<r.val))(data);
  auto b=a.dup;
  sort(b);
  int cnt=0;
  for(int i=0, j=0; i<n && j<n; i++, j++){
    while(i<n && b[i]<=a[data[j].idx]) i++;
    if(i<n) cnt++;
  }
  writeln(cnt);

}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

/*

7
10 1 1 1 5 5 3

1 2 3 6 4 5 0

*/