You are given a deck of $$$n$$$ cards numbered from $$$1$$$ to $$$n$$$ (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation.   Choose $$$2 \le k \le n$$$ and split the deck in $$$k$$$ nonempty contiguous parts $$$D_1, D_2,\dots, D_k$$$ ($$$D_1$$$ contains the first $$$|D_1|$$$ cards of the deck, $$$D_2$$$ contains the following $$$|D_2|$$$ cards and so on). Then reverse the order of the parts, transforming the deck into $$$D_k, D_{k-1}, \dots, D_2, D_1$$$ (so, the first $$$|D_k|$$$ cards of the new deck are $$$D_k$$$, the following $$$|D_{k-1}|$$$ cards are $$$D_{k-1}$$$ and so on). The internal order of each packet of cards $$$D_i$$$ is unchanged by the operation. You have to obtain a sorted deck (i.e., a deck where the first card is $$$1$$$, the second is $$$2$$$ and so on) performing at most $$$n$$$ operations. It can be proven that it is always possible to sort the deck performing at most $$$n$$$ operations.Examples of operation: The following are three examples of valid operations (on three decks with different sizes).   If the deck is [3 6 2 1 4 5 7] (so $$$3$$$ is the first card and $$$7$$$ is the last card), we may apply the operation with $$$k=4$$$ and $$$D_1=$$$[3 6], $$$D_2=$$$[2 1 4], $$$D_3=$$$[5], $$$D_4=$$$[7]. Doing so, the deck becomes [7 5 2 1 4 3 6].  If the deck is [3 1 2], we may apply the operation with $$$k=3$$$ and $$$D_1=$$$[3], $$$D_2=$$$[1], $$$D_3=$$$[2]. Doing so, the deck becomes [2 1 3].  If the deck is [5 1 2 4 3 6], we may apply the operation with $$$k=2$$$ and $$$D_1=$$$[5 1], $$$D_2=$$$[2 4 3 6]. Doing so, the deck becomes [2 4 3 6 5 1].

The first line of the input contains one integer $$$n$$$ ($$$1\le n\le 52$$$)  — the number of cards in the deck. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$  — the cards in the deck. The first card is $$$c_1$$$, the second is $$$c_2$$$ and so on. It is guaranteed that for all $$$i=1,\dots,n$$$ there is exactly one $$$j\in\{1,\dots,n\}$$$ such that $$$c_j = i$$$.

On the first line, print the number $$$q$$$ of operations you perform (it must hold $$$0\le q\le n$$$). Then, print $$$q$$$ lines, each describing one operation. To describe an operation, print on a single line the number $$$k$$$ of parts you are going to split the deck in, followed by the size of the $$$k$$$ parts: $$$|D_1|, |D_2|, \dots , |D_k|$$$.  It must hold $$$2\le k\le n$$$, and $$$|D_i|\ge 1$$$ for all $$$i=1,\dots,k$$$, and $$$|D_1|+|D_2|+\cdots + |D_k| = n$$$. It can be proven that it is always possible to sort the deck performing at most $$$n$$$ operations. If there are several ways to sort the deck you can output any of them.

NoteExplanation of the first testcase: Initially the deck is [3 1 2 4].   The first operation splits the deck as [(3) (1 2) (4)] and then transforms it into [4 1 2 3].  The second operation splits the deck as [(4) (1 2 3)] and then transforms it into [1 2 3 4].  Explanation of the second testcase: Initially the deck is [6 5 4 3 2 1].   The first (and only) operation splits the deck as [(6) (5) (4) (3) (2) (1)] and then transforms it into [1 2 3 4 5 6].

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto p = readln.splitter.map !(to !(int)).array;
		p[] -= 1;

		void perform (int [] cuts)
		{
			int [] res;
			foreach_reverse (i; 1..cuts.length)
			{
				res ~= p[cuts[i - 1]..cuts[i]];
			}
			p = res;
		}

		int [] [] answer;
		while (!p.isSorted)
		{
			auto q = new int [n];
			foreach (i; 0..n)
			{
				q[p[i]] = i;
			}
			foreach (v; 0..n - 1)
			{
				if (q[v + 1] < q[v] + 1)
				{
					auto pos = q[v + 1];
					while (p[pos + 1] == p[pos] + 1)
					{
						pos += 1;
					}
					auto cuts = only (0, q[v + 1],
					    pos + 1, q[v] + 1, n).uniq.array;
					perform (cuts);
					answer ~= cuts.zip (cuts[1..$])
					    .map !(q{a[1] - a[0]}).array;
					break;
				}
			}
		}
		writeln (answer.length);
		foreach (ref line; answer)
		{
			writefln !("%s %(%s %)") (line.length, line);
		}
	}
}

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

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

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

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

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

      auto cs = C.dup;
      int[][] dss;
      int cnt;
      foreach (i; 0 .. N) {
        if (cs[i] != i) {
          foreach (j; 0 .. N) {
            if (cs[j] == i) {
              int[] ds;
              foreach (k; 0 .. i) {
                ds ~= 1;
              }
              ds ~= (j + 1) - i;
              foreach (k; j + 1 .. N) {
                ds ~= 1;
              }
              if (cnt % 2 != 0) {
                ds.reverse;
              }
              ++cnt;
              if (ds.length > 1) {
                dss ~= ds;
              }
              cs[i .. j + 1].reverse;
              break;
            }
          }
        }
      }
      if (cnt % 2 != 0) {
        int[] ds;
        foreach (i; 0 .. N) {
          ds ~= 1;
        }
        ds.reverse;
        if (ds.length > 1) {
          dss ~= ds;
        }
      }

      writeln(dss.length);
      foreach (ds; dss) {
        write(ds.length);
        foreach (d; ds) {
          write(" ", d);
        }
        writeln;
      }

      debug {
        cs = C.dup;
        foreach (ds; dss) {
          int[][] blocks;
          int i;
          foreach (d; ds) {
            blocks ~= cs[i .. i + d];
            i += d;
          }
          assert(i == N);
          blocks.reverse;
          cs = [];
          foreach (block; blocks) {
            cs ~= block;
          }
        }
        assert(cs == iota(N).array, format("C = %s, cs = %s", C, cs));
      }
    }
  } catch (EOFException e) {
  }
}

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 n = RD!int;
	auto c = RDA(-1);

	int[][] lrp;
	int[][] ans;
	foreach (_; 0..n)
	{
		{
			lrp.length = 0;
			int l;
			foreach (i; 0..n-1)
			{
				if (c[i]+1 == c[i+1]) continue;
				lrp ~= [c[l], c[i], l];
				l = i+1;
			}
			lrp ~= [c[l], c[$-1], l];
		}
		debug writeln(lrp);
		if (lrp.length == 1) break;

		int[int] list;
		foreach (int j, ref e; lrp)
		{
			auto pos = list.get(e[1]+1, -1);
			if (pos != -1)
			{
				debug writeln(e, " ", lrp[pos]);
				auto ee = lrp[pos];
				auto l = ee[0];
				auto r = ee[1];
				auto p = ee[2];
				auto len = e[1] - e[0] + 1;
				debug writeln("len:", len);
				int[] tmp;
				if (p != 0)
					tmp ~= p;
				tmp ~= e[2] - p;
				tmp ~= len;
				if (e[2]+len < n)
					tmp ~= n - (e[2]+len);
				ans ~= cast(int)tmp.length ~ tmp;

				int[] next;
				int cnt = n;
				foreach_reverse (t; tmp)
				{
					next ~= c[cnt-t..cnt];
					cnt -= t;
				}
				c = next;
				break;
			}
			else
			{
				list[e[0]] = j;
			}
		}
	}

	writeln(ans.length);
	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}

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

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

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

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

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

      auto cs = C.dup;
      int[][] dss;
      foreach (i; 0 .. N) {
        if (cs[i] != i) {
          foreach (j; 0 .. N) {
            if (cs[j] == i) {
              int[] ds;
              foreach (k; 0 .. i) {
                ds ~= 1;
              }
              ds ~= (j + 1) - i;
              foreach (k; j + 1 .. N) {
                ds ~= 1;
              }
              if (ds.length > 1) {
                dss ~= ds;
              }
              cs[i .. j + 1].reverse;
              break;
            }
          }
        }
      }
      if (dss.length % 2 != 0) {
        int[] ds;
        foreach (i; 0 .. N) {
          ds ~= 1;
        }
        if (ds.length > 1) {
          dss ~= ds;
        }
      }

      writeln(dss.length);
      foreach (ds; dss) {
        write(ds.length);
        foreach (d; ds) {
          write(" ", d);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto cs = C.dup;
      int[][] dss;
      int cnt;
      foreach (i; 0 .. N) {
        if (cs[i] != i) {
          foreach (j; 0 .. N) {
            if (cs[j] == i) {
              int[] ds;
              foreach (k; 0 .. i) {
                ds ~= 1;
              }
              ds ~= (j + 1) - i;
              foreach (k; j + 1 .. N) {
                ds ~= 1;
              }
              ++cnt;
              if (ds.length > 1) {
                dss ~= ds;
              }
              cs[i .. j + 1].reverse;
              break;
            }
          }
        }
      }
      if (cnt % 2 != 0) {
        int[] ds;
        foreach (i; 0 .. N) {
          ds ~= 1;
        }
        if (ds.length > 1) {
          dss ~= ds;
        }
      }

      writeln(dss.length);
      foreach (ds; dss) {
        write(ds.length);
        foreach (d; ds) {
          write(" ", d);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto cs = C.dup;
      int[][] dss;
      foreach (i; 0 .. N) {
        if (cs[i] != i) {
          foreach (j; 0 .. N) {
            if (cs[j] == i) {
              int[] ds;
              foreach (k; 0 .. i) {
                ds ~= 1;
              }
              ds ~= (j + 1) - i;
              foreach (k; j + 1 .. N) {
                ds ~= 1;
              }
              dss ~= ds;
              cs[i .. j + 1].reverse;
              break;
            }
          }
        }
      }
      if (dss.length % 2 != 0) {
        int[] ds;
        foreach (i; 0 .. N) {
          ds ~= 1;
        }
        dss ~= ds;
      }

      writeln(dss.length);
      foreach (ds; dss) {
        write(ds.length);
        foreach (d; ds) {
          write(" ", d);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}


There is a bookshelf which can fit $$$n$$$ books. The $$$i$$$-th position of bookshelf is $$$a_i = 1$$$ if there is a book on this position and $$$a_i = 0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.In one move, you can choose some contiguous segment $$$[l; r]$$$ consisting of books (i.e. for each $$$i$$$ from $$$l$$$ to $$$r$$$ the condition $$$a_i = 1$$$ holds) and:  Shift it to the right by $$$1$$$: move the book at index $$$i$$$ to $$$i + 1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$r+1 \le n$$$ and there is no book at the position $$$r+1$$$.  Shift it to the left by $$$1$$$: move the book at index $$$i$$$ to $$$i-1$$$ for all $$$l \le i \le r$$$. This move can be done only if $$$l-1 \ge 1$$$ and there is no book at the position $$$l-1$$$. Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).For example, for $$$a = [0, 0, 1, 0, 1]$$$ there is a gap between books ($$$a_4 = 0$$$ when $$$a_3 = 1$$$ and $$$a_5 = 1$$$), for $$$a = [1, 1, 0]$$$ there are no gaps between books and for $$$a = [0, 0,0]$$$ there are also no gaps between books.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of places on a bookshelf. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is $$$1$$$ if there is a book at this position and $$$0$$$ otherwise. It is guaranteed that there is at least one book on the bookshelf.

For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).

NoteIn the first test case of the example, you can shift the segment $$$[3; 3]$$$ to the right and the segment $$$[4; 5]$$$ to the right. After all moves, the books form the contiguous segment $$$[5; 7]$$$. So the answer is $$$2$$$.In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.In the third test case of the example, you can shift the segment $$$[5; 5]$$$ to the left and then the segment $$$[4; 4]$$$ to the left again. After all moves, the books form the contiguous segment $$$[1; 3]$$$. So the answer is $$$2$$$.In the fourth test case of the example, you can shift the segment $$$[1; 1]$$$ to the right, the segment $$$[2; 2]$$$ to the right, the segment $$$[6; 6]$$$ to the left and then the segment $$$[5; 5]$$$ to the left. After all moves, the books form the contiguous segment $$$[3; 4]$$$. So the answer is $$$4$$$.In the fifth test case of the example, you can shift the segment $$$[1; 2]$$$ to the right. After all moves, the books form the contiguous segment $$$[2; 5]$$$. So the answer is $$$1$$$.

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

void play(){
    int n;
    n = rd!int;
    ll[] arr = rdarr;
    int ix = -1, rix = -1;
    foreach(i; 0..n){
        if(arr[i] == 1){ ix = i; break; }
    }
    foreach_reverse(i; 0..n){
        if(arr[i] == 1){ rix = i; break; }
    }
    if(ix == -1){
        writeln(0);
        return;
    }
    int cnt = 0;
    foreach(i; ix..rix+1){
        cnt += (arr[i] == 0);
    }
    writeln(cnt);
}

int main(){
    long t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
void show(A...)(A a) { debug{ a.each!(w => write(w, "| ")); writeln; } }
alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
T max(T = long)(T a, T b){ return (a > b) ? a : b; }
T min(T = long)(T a, T b){ return (a < b) ? a : b; }

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		while (!a.front)
		{
			a.popFront ();
		}
		while (!a.back)
		{
			a.popBack ();
		}
		writeln (a.length - a.sum);
	}
}

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 long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;

		int l, r;
		foreach (i; 0..n)
		{
			if (a[i] == 1)
			{
				l = i;
				break;
			}
		}
		foreach_reverse (i; 0..n)
		{
			if (a[i] == 1)
			{
				r = i;
				break;
			}
		}
		foreach (i; l..r)
		{
			if (a[i] == 0)
				++ans[ti];
		}
	}

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


You are given an array $$$a$$$ consisting of $$$n$$$ integers.Your task is to say the number of such positive integers $$$x$$$ such that $$$x$$$ divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array.For example, if the array $$$a$$$ will be $$$[2, 4, 6, 2, 10]$$$, then $$$1$$$ and $$$2$$$ divide each number from the array (so the answer for this test is $$$2$$$).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 4 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{12}$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the number of such positive integers $$$x$$$ such that $$$x$$$ divides each number from the given array (in other words, the answer is the number of common divisors of all elements in the array).

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

string FMT_F = "%.10f";

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

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

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

long _gcd(long a, long b){
    return b ? _gcd(b , a%b) : a;
}

void main()
{
	auto n = RD!int;
	auto a = RDA;
	long g;
	foreach (i; 0..n)
	{
		g = _gcd(a[i], g);
	}

	long ans;
	for (long i = 1; i*i <= g; ++i)
	{
		if (g % i == 0)
		{
			++ans;
			if (g / i != i)
			{
				++ans;
			}
		}
	}

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


One day n friends met at a party, they hadn't seen each other for a long time and so they decided to make a group photo together. Simply speaking, the process of taking photos can be described as follows. On the photo, each photographed friend occupies a rectangle of pixels: the i-th of them occupies the rectangle of width wi pixels and height hi pixels. On the group photo everybody stands in a line, thus the minimum pixel size of the photo including all the photographed friends, is W × H, where W is the total sum of all widths and H is the maximum height of all the photographed friends.As is usually the case, the friends made n photos — the j-th (1 ≤ j ≤ n) photo had everybody except for the j-th friend as he was the photographer.Print the minimum size of each made photo in pixels.

The first line contains integer n (2 ≤ n ≤ 200 000) — the number of friends.  Then n lines follow: the i-th line contains information about the i-th friend. The line contains a pair of integers wi, hi (1 ≤ wi ≤ 10, 1 ≤ hi ≤ 1000) — the width and height in pixels of the corresponding rectangle.

Print n space-separated numbers b1, b2, ..., bn, where bi — the total number of pixels on the minimum photo containing all friends expect for the i-th one.

import std.stdio;
import std.algorithm;

void main() {

	int n;
	ubyte w;
	ushort h;

	scanf("%d", &n);

	int[] W;
	ushort[] H;
	foreach (i; 0 .. n) {
		readf(" %s %s", &w, &h);
		W ~= w, H ~= h;
	}

	ushort[] tmpH = H.dup;
	sort(tmpH);
	ushort max1 = tmpH[$ - 1], max2 = tmpH[$ - 2];

	int sum = W.reduce!"a + b";

	foreach (i, elem; W)
		write((H[i] != max1) ? ((sum - elem) * max1) : ((sum - elem) * max2), ' ');

	writeln;
}

module main;

import std.stdio, std.string;

void solve(int[] w, int[] h)
{
    int maxs = 0, cnt = 0, smaxs = 0;
    long sum = 0;
    foreach (i; 0 .. w.length)
    {
	if (h[i] > maxs)
	{
	    if (maxs != 0)
	    {
		smaxs = maxs;
	    }
	    maxs = h[i];
	    cnt = 1;
	}
	else if (h[i] == maxs)
	{
	    smaxs = h[i];
	    ++ cnt;
	}
	else if (h[i] > smaxs)
	{
	    smaxs = h[i];
	}
	sum += w[i];
    }
    foreach (i; 0 .. w.length)
    {
	if (h[i] == maxs)
	{
	    if (cnt == 1)
	    {
		writef("%d ", (sum - w[i]) * smaxs);
	    }
	    else
	    {
		writef("%d ", (sum - w[i]) * maxs);
	    }
	}
	else
	{
	    writef("%d ", (sum - w[i]) * maxs);
	}
    }
    writeln();
}

void main(string[] args)
{
    int n;
    while (scanf("%d", &n) == 1)
    {
	auto w = new int[n];
	auto h = new int[n];
	foreach (i; 0 .. n)
	{
	    scanf("%d%d", &w[i], &h[i]);
	}
	solve(w, h);
    }
}

import std.stdio;

int n;
short[] a;

ulong sumW() {
	ulong sum;
	for (size_t i = 0; i < 2 * n; i += 2)
			sum += a[i];
	return sum;
}

size_t j, k, t;

short maxH() {
	short max;
	for (size_t i = 1; i < 2 * n; i += 2)
			if ((a[i] > max) && (i != j)) {
				max = a[i];
				k = i;
			}

	if (t < 1)
		j = k;

	++t;

	return max;
}

void main() {

	scanf("%d", &n);

	short w, h;
	foreach (i; 0 .. n) {
		scanf("%hd%hd", &w, &h);
		a ~= w,	a ~= h;
	}

	ulong sum = sumW();
	short max1 = maxH();
	short max2 = maxH();

	for (size_t i = 0; i < 2 * n; i += 2)
		if (i != j - 1)
			write((sum - a[i]) * max1, ' ');
		else
			write((sum - a[i]) * max2, ' ');

	putchar('\n');
}


You are given an array $$$a$$$ consisting of $$$n$$$ nonnegative integers. Let's define the prefix OR array $$$b$$$ as the array $$$b_i = a_1~\mathsf{OR}~a_2~\mathsf{OR}~\dots~\mathsf{OR}~a_i$$$, where $$$\mathsf{OR}$$$ represents the bitwise OR operation. In other words, the array $$$b$$$ is formed by computing the $$$\mathsf{OR}$$$ of every prefix of $$$a$$$.You are asked to rearrange the elements of the array $$$a$$$ in such a way that its prefix OR array is lexicographically maximum.An array $$$x$$$ is lexicographically greater than an array $$$y$$$ if in the first position where $$$x$$$ and $$$y$$$ differ, $$$x_i > y_i$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ nonnegative integers $$$a_1, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print $$$n$$$ integers — any rearrangement of the array $$$a$$$ that obtains the lexicographically maximum prefix OR array.

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    int mask = 0;
    size_t i = 0;
    while (i < a.length) {
      a[i .. $].sort!((x, y) => (y & ~mask) < (x & ~mask));
      if ((a[i] & ~mask) == 0)
        break;
      mask |= a[i];
      i++;
    }
    writefln("%(%s %)", a);
  }
}

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

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

void solve() {
    int N = read!int;
    auto A = readarray!int;
    auto Y = A.dup;

    auto used = new bool[N];

    int s = 0;
    int[] X;
    for (int i = 0; i < 32; i++) {
        int m = -1;
        int x = 0;
        for (int j = 0; j < N; j++) {
            if (used[j]) continue;
            if (x < Y[j]) {
                x = Y[j];
                m = j;
            }
        }
        if (m < 0) continue;
        used[m] = true;
        X ~= A[m];
        s |= A[m];
        foreach (ref a; Y) {
            a = a & ~s;
        }
    }
    for (int i = 0; i < N; i++) {
        if (used[i]) continue;
        X ~= A[i];
    }
    writefln("%(%s %)", X);
}

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


The only difference between easy and hard versions is on constraints. In this version constraints are higher. You can make hacks only if all versions of the problem are solved.Koa the Koala is at the beach!The beach consists (from left to right) of a shore, $$$n+1$$$ meters of sea and an island at $$$n+1$$$ meters from the shore.She measured the depth of the sea at $$$1, 2, \dots, n$$$ meters from the shore and saved them in array $$$d$$$. $$$d_i$$$ denotes the depth of the sea at $$$i$$$ meters from the shore for $$$1 \le i \le n$$$.Like any beach this one has tide, the intensity of the tide is measured by parameter $$$k$$$ and affects all depths from the beginning at time $$$t=0$$$ in the following way:  For a total of $$$k$$$ seconds, each second, tide increases all depths by $$$1$$$.  Then, for a total of $$$k$$$ seconds, each second, tide decreases all depths by $$$1$$$.  This process repeats again and again (ie. depths increase for $$$k$$$ seconds then decrease for $$$k$$$ seconds and so on ...).Formally, let's define $$$0$$$-indexed array $$$p = [0, 1, 2, \ldots, k - 2, k - 1, k, k - 1, k - 2, \ldots, 2, 1]$$$ of length $$$2k$$$. At time $$$t$$$ ($$$0 \le t$$$) depth at $$$i$$$ meters from the shore equals $$$d_i + p[t \bmod 2k]$$$ ($$$t \bmod 2k$$$ denotes the remainder of the division of $$$t$$$ by $$$2k$$$). Note that the changes occur instantaneously after each second, see the notes for better understanding. At time $$$t=0$$$ Koa is standing at the shore and wants to get to the island. Suppose that at some time $$$t$$$ ($$$0 \le t$$$) she is at $$$x$$$ ($$$0 \le x \le n$$$) meters from the shore:  In one second Koa can swim $$$1$$$ meter further from the shore ($$$x$$$ changes to $$$x+1$$$) or not swim at all ($$$x$$$ stays the same), in both cases $$$t$$$ changes to $$$t+1$$$.  As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed $$$l$$$ at integer points of time (or she will drown). More formally, if Koa is at $$$x$$$ ($$$1 \le x \le n$$$) meters from the shore at the moment $$$t$$$ (for some integer $$$t\ge 0$$$), the depth of the sea at this point  — $$$d_x + p[t \bmod 2k]$$$  — can't exceed $$$l$$$. In other words, $$$d_x + p[t \bmod 2k] \le l$$$ must hold always.  Once Koa reaches the island at $$$n+1$$$ meters from the shore, she stops and can rest.Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there). Koa wants to know whether she can go from the shore to the island. Help her!

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$)  — the number of test cases. Description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$k$$$ and $$$l$$$ ($$$1 \le n \le 3 \cdot 10^5; 1 \le k \le 10^9; 1 \le l \le 10^9$$$) — the number of meters of sea Koa measured and parameters $$$k$$$ and $$$l$$$. The second line of each test case contains $$$n$$$ integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \le d_i \le 10^9$$$)  — the depths of each meter of sea Koa measured. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case: Print Yes if Koa can get from the shore to the island, and No otherwise. You may print each letter in any case (upper or lower).

NoteIn the following $$$s$$$ denotes the shore, $$$i$$$ denotes the island, $$$x$$$ denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at $$$1, 2, \dots, n$$$ meters from the shore.In test case $$$1$$$ we have $$$n = 2, k = 1, l = 1, p = [ 0, 1 ]$$$.Koa wants to go from shore (at $$$x = 0$$$) to the island (at $$$x = 3$$$). Let's describe a possible solution:  Initially at $$$t = 0$$$ the beach looks like this: $$$[\underline{s}, 1, 0, i]$$$.  At $$$t = 0$$$ if Koa would decide to swim to $$$x = 1$$$, beach would look like: $$$[s, \underline{2}, 1, i]$$$ at $$$t = 1$$$, since $$$2 > 1$$$ she would drown. So Koa waits $$$1$$$ second instead and beach looks like $$$[\underline{s}, 2, 1, i]$$$ at $$$t = 1$$$.  At $$$t = 1$$$ Koa swims to $$$x = 1$$$, beach looks like $$$[s, \underline{1}, 0, i]$$$ at $$$t = 2$$$. Koa doesn't drown because $$$1 \le 1$$$.  At $$$t = 2$$$ Koa swims to $$$x = 2$$$, beach looks like $$$[s, 2, \underline{1}, i]$$$ at $$$t = 3$$$. Koa doesn't drown because $$$1 \le 1$$$.  At $$$t = 3$$$ Koa swims to $$$x = 3$$$, beach looks like $$$[s, 1, 0, \underline{i}]$$$ at $$$t = 4$$$.  At $$$t = 4$$$ Koa is at $$$x = 3$$$ and she made it! We can show that in test case $$$2$$$ Koa can't get to the island.

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);
multitest_loop:
	foreach (test; 0..tests)
	{
		int n, k, lim;
		readf !(" %s %s %s") (n, k, lim);
		readln;
		auto d = readln.splitter.map !(to !(int)).array;
		d[] = lim - d[];
		if (d.any !(q{a < 0}))
		{
			writeln ("No");
			continue multitest_loop;
		}
		int cur = -1;
		foreach (i; 0..n)
		{
			cur += 1;
			if (d[i] >= k)
			{
				cur = -1;
			}
			else if (cur < k)
			{
				cur = max (cur, k - d[i]);
			}
			else if (d[i] < k && cur > k + d[i])
			{
				writeln ("No");
				continue multitest_loop;
			}
		}
		writeln ("Yes");
	}
}

import std.stdio;

class Input
{
static:
  import std.container: DList, make;
  DList!string words;
  T next(alias T)()
  {
    import std.conv: to;
    import std.string: split;
    while (words.empty)
      {
        string line = stdin.readln;
        foreach(word; line.split)
          words.insertFront(word);
      }
    string nextWord = words.back;
    words.removeBack;
    return to!T(nextWord);
  }
  void read(Args...)(ref Args args)
  {
    static foreach(i, arg; args)
      arg = next!(Args[i])();
  }
}

struct Interval(string type)
{
  long lowerBound, higherBound;
  bool empty()
  {
    static if (type == "[]")
      return !(lowerBound <= higherBound);
    else
      static assert(false);
  }
}

Interval!type intersect(string type)(Interval!type a, Interval!type b)
{
  import std.algorithm: min, max;
  return Interval!type(max(a.lowerBound, b.lowerBound),
                       min(a.higherBound, b.higherBound));
}

auto intersect(IntervalRange1, IntervalRange2)(IntervalRange1 a, IntervalRange2 b)
  if (isInputRange!IntervalRange1 && isInputRange!IntervalRange2)
{
  import std.algorithm.setops: cartesianProduct;
  import std.algorithm: map, filter;

  return cartesianProduct(a.filter!(i=>!i.empty), b.filter!(i=>!i.empty))
    .map!(t => intersect(t[0], t[1]))
    .filter!(i => !i.empty)();
}

import std.range.primitives: isInputRange;
auto simplifyIntervals(IntervalRange)(IntervalRange range)
  if (isInputRange!IntervalRange)
    {
      struct Event
      {
        long position;
        int type;
      }
      auto less = (Event e1, Event e2)
        {
         if (e1.position < e2.position)
           return true;
         if (e1.position > e2.position)
           return false;
         return e1.type > e2.type;
        };
      import std.algorithm: sort;
      import std.array: appender;

      long[long] events;
      foreach(interval; range)
        {
          events[interval.lowerBound]++;
          events[interval.higherBound + 1]--;
        }
      long start = int.min;
      long cnt = 0;
      auto result = appender!(Interval!"[]"[])();
      result.reserve(range.length);
      foreach(position; sort(events.keys()))
        {
          auto delta = events[position];
          import std.conv;
          assert(cnt >= 0, text("Failed with range ", range, " with events ", events));
          if (cnt == 0)
            {
              cnt += delta;
              start = position;
            }
          else
            {
              cnt += delta;
              if (cnt == 0)
                result.put(Interval!"[]"(start, position - 1));
            }
        }
      return result[];
    }
int main()
{
  long t;
  Input.read(t);
 testCase:while(t--)
    {
      import std.algorithm: min;
      long n, k, l;
      Input.read(n, k, l);
      long mod = 2 * k;
      auto d = new long[cast(size_t)n];
      foreach(ref di; d)
        Input.read(di);
      auto sealimit = new long[cast(size_t)n];
      foreach(i, di; d)
        {
          long maxsea = l - di;
          if (maxsea < 0)
            {
              writeln("No");
              continue testCase;
            }
          if (maxsea < k)
            sealimit[i] = maxsea;
          else
            sealimit[i] = -1;
        }

      Interval!"[]"[] activeIntervals = [Interval!"[]"(0, 2 * k - 1)];
      foreach(i, limit; sealimit)
        {
          import std.array: appender;
          auto newActive = appender!(Interval!"[]"[])();
          foreach(ref interval; activeIntervals) with(interval)
            {
              assert(!interval.empty);
              lowerBound++;
              lowerBound %= 2 * k;
              higherBound++;
              higherBound %= 2 * k;
              if (lowerBound > higherBound)
                {
                  newActive.put(Interval!"[]"(lowerBound, 2 * k - 1));
                  newActive.put(Interval!"[]"(0, higherBound));
                }
              else
                {
                  newActive.put(interval);
                }
            }
          activeIntervals = simplifyIntervals(newActive[]);
          if (limit == -1)
            {
              activeIntervals = [Interval!"[]"(0, 2 * k - 1)];
              continue;
            }
          import std.array: array;
          activeIntervals = intersect([Interval!"[]"(0, limit), Interval!"[]"(2 * k - limit, 2 * k - 1)], activeIntervals).array;
          if (activeIntervals.length == 0)
            {
              writeln("No");
              continue testCase;
            }
        }
      long totalLength = 0;
      import std.algorithm: max;
      foreach(interval; activeIntervals)
        totalLength += max(0, interval.higherBound - interval.lowerBound + 1);
      if (totalLength > 0)
        writeln("Yes");
      else
        writeln("No");
    }
  return 0;
}


You are given three positive (i.e. strictly greater than zero) integers $$$x$$$, $$$y$$$ and $$$z$$$.Your task is to find positive integers $$$a$$$, $$$b$$$ and $$$c$$$ such that $$$x = \max(a, b)$$$, $$$y = \max(a, c)$$$ and $$$z = \max(b, c)$$$, or determine that it is impossible to find such $$$a$$$, $$$b$$$ and $$$c$$$.You have to answer $$$t$$$ independent test cases. Print required $$$a$$$, $$$b$$$ and $$$c$$$ in any (arbitrary) order.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$x$$$, $$$y$$$, and $$$z$$$ ($$$1 \le x, y, z \le 10^9$$$).

For each test case, print the answer:   "NO" in the only line of the output if a solution doesn't exist;  or "YES" in the first line and any valid triple of positive integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^9$$$) in the second line. You can print $$$a$$$, $$$b$$$ and $$$c$$$ in any order.

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

void main()
{
  int t;
  readf!"%d\n"(t);

  foreach (i; 0..t) {
    long x, y, z;
    readf!"%d %d %d\n"(x, y, z);

    // trivial case
    if (x == y && y == z) {
      writefln("YES\n%d %d %d", x, x, x);
      continue;
    }

    // otherwise, 2 of 3 have to be max
    auto m = max(x, y, z);
    auto n = min(x, y, z);
    if ((x == m && y == m) || (x == m && z == m) || (y == m && z == m)) {
      writefln("YES\n%d %d %d", n, n, m);
      continue;
    }

    writeln("NO");
  }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
multitest_loop:
	foreach (test; 0..tests)
	{
		auto x = readln.splitter.map !(to !(int)).array;
		foreach (i; x)
		{
			foreach (j; x)
			{
				foreach (k; x)
				{
					if (max (i, j) == x[0] &&
					    max (i, k) == x[1] &&
					    max (j, k) == x[2])
					{
						writeln ("YES");
						writeln (i, " ", j, " ", k);
						continue multitest_loop;
					}
				}
			}
		}
		writeln ("NO");
	}
}


— Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me?   — Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night? At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai — some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart:   The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible;  the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same;  and of course, the walk should be successful: there must be at least two trees in the woodland belt left. Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?

The first line contains a single integer n — the initial number of trees in the woodland belt, 2 ≤ n. The second line contains space-separated integers ai — the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value.   to get 30 points, you need to solve the problem with constraints: n ≤ 100 (subproblem A1);  to get 100 points, you need to solve the problem with constraints: n ≤ 3·105 (subproblems A1+A2).

In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k. In the next line print k integers — the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right. If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.

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;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n + 1];
		auto b = new int [n + 1];
		auto s = new long [n + 1];
		int [] [int] x;
		s[0] = 0;
		foreach (i; 1..n + 1)
		{
			readf (" %s", &a[i]);
			b[i] = max (a[i], 0);
			s[i] = s[i - 1] + b[i];
			x[a[i]] ~= i;
		}

		long res = long.min;
		int bu, bv;
		foreach (i, c; x)
		{
			if (c.length >= 2)
			{
				int u = c[0];
				int v = c[$ - 1];
				long cur = i * 2 + s[v - 1] - s[u];
				if (res < cur)
				{
					res = cur;
					bu = u;
					bv = v;
				}
			}
		}

		int [] ans;
		foreach (i; 1..n + 1)
		{
			if (i < bu || bv < i ||
			    (i != bu && i != bv && a[i] < 0))
			{
				ans ~= i;
			}
		}
		writefln ("%s %s", res, ans.length);
		writefln ("%(%s %)", ans);
	}
}


Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled!When building the graph, he needs four conditions to be satisfied:   It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops.  The number of vertices must be exactly $$$n$$$ — a number he selected. This number is not necessarily prime.  The total number of edges must be prime.  The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for $$$n = 4$$$. The first graph (left one) is invalid as the degree of vertex $$$2$$$ (and $$$4$$$) equals to $$$1$$$, which is not prime. The second graph (middle one) is invalid as the total number of edges is $$$4$$$, which is not a prime number. The third graph (right one) is a valid answer for $$$n = 4$$$.   Note that the graph can be disconnected.Please help Bob to find any such graph!

The input consists of a single integer $$$n$$$ ($$$3 \leq n \leq 1\,000$$$) — the number of vertices.

If there is no graph satisfying the conditions, print a single line containing the integer $$$-1$$$. Otherwise, first print a line containing a prime number $$$m$$$ ($$$2 \leq m \leq \frac{n(n-1)}{2}$$$) — the number of edges in the graph. Then, print $$$m$$$ lines, the $$$i$$$-th of which containing two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$) — meaning that there is an edge between vertices $$$u_i$$$ and $$$v_i$$$. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops. If there are multiple solutions, you may print any of them. Note that the graph can be disconnected.

NoteThe first example was described in the statement.In the second example, the degrees of vertices are $$$[7, 5, 2, 2, 3, 2, 2, 3]$$$. Each of these numbers is prime. Additionally, the number of edges, $$$13$$$, is also a prime number, hence both conditions are satisfied.

/+ dub.sdl:
    name "D"
    dependency "dunkelheit" version="1.0.1"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dkh.foundation, dkh.scanner, dkh.numeric.prime;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    debug {
        foreach (n; 3..1001) {
            bool ok = false;
            foreach (m; n..(n + n / 4 * 2) + 1) {
                if (isPrime(m)) {
                    ok = true;
                    writefln("find %d : %d", n, m);
                    stdout.flush;
                    break;
                }
            }
            if (!ok) {
                writeln("ERROR ", n);
                return 0;
            }
        }
    }

    int n;
    sc.read(n);
    foreach (m; n..(n + n / 4 * 2) + 1) {
        if (isPrime(m)) {

            int[2][] edges;
            foreach (i; 0..n) {
                edges ~= [i, (i + 1) % n];
            }
            foreach (i; 0..n) {
                if (i % 4 >= 2) continue;
                if (edges.length.to!int >= m) break;
                edges ~= [i, (i + 2) % n];
            }

            writeln(m);
            foreach (d; edges) {
                writeln(d[0] + 1, " ", d[1] + 1);
            }
            return 0;
        }
    }

    return 0;
}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    private File f;

    this(File f) {
        this.f = f;
    }
    private char[512] lineBuf;
    private char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    assert(succW());
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }

    void read(Args...)(auto ref Args args) {
        import std.exception : enforce;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }

    bool hasNext() {
        return succ();
    }
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/numeric/prime.d */
// module dkh.numeric.prime;

import std.traits;
// import dkh.int128;

ulong ulongPowMod(U)(ulong x, U n, ulong md)
if (isIntegral!U || is(U == BigInt)) {
    x %= md;
    ulong r = 1;
    while (n) {
        if (n & 1) {
            r = mul128(r, x).mod128(md);
        }
        x = mul128(x, x).mod128(md);
        n >>= 1;
    }
    return r % md;
}

T[] divisorList(T)(T x) {
    import std.algorithm : sort;
    T[] res;
    for (T i = 1; i*i <= x; i++) {
        if (x%i == 0) {
            res ~= i;
            if (i*i != x) res ~= x/i;
        }
    }
    sort(res);
    return res;
}

T[] factorList(T)(T x) {
    T[] res;
    for (T i = 2; i*i <= x; i++) {
        while (x % i == 0) {
            res ~= i;
            x /= i;
        }
    }
    if (x > 1) res ~= x;

    return res;
}

// import dkh.numeric.primitive;

bool isPrime(ulong n) {
//     import dkh.int128;
    if (n <= 1) return false;
    if (n == 2) return true;
    if (n % 2 == 0) return false;
    ulong d = n-1;
    while (d % 2 == 0) d /= 2;
    ulong[] alist = [2,3,5,7,11,13,17,19,23,29,31,37];
    foreach (a; alist) {
        if (n <= a) break;
        ulong y = ulongPowMod(a, d, n);
        ulong t = d;
        while (t != n-1 && y != 1 && y != n-1) {
            y = mul128(y, y).mod128(n);
            t <<= 1;
        }
        if (y != n-1 && t % 2 == 0) {
            return false;
        }
    }
    return true;
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/numeric/primitive.d */
// module dkh.numeric.primitive;

import std.traits, std.bigint;

T lcm(T)(in T a, in T b) {
    import std.numeric : gcd;
    return a / gcd(a,b) * b;
}

Unqual!T pow(T, U)(T x, U n)
if (!isFloatingPoint!T && (isIntegral!U || is(U == BigInt))) {
    return pow(x, n, T(1));
}

Unqual!T pow(T, U, V)(T x, U n, V e)
if ((isIntegral!U || is(U == BigInt)) && is(Unqual!T == Unqual!V)) {
    Unqual!T b = x, v = e;
    Unqual!U m = n;
    while (m) {
        if (m & 1) v *= b;
        b *= b;
        m /= 2;
    }
    return v;
}

T powMod(T, U, V)(T x, U n, V md)
if (isIntegral!U || is(U == BigInt)) {
    T r = T(1);
    Unqual!U m = n;
    while (m) {
        if (m & 1) r = (r*x)%md;
        x = (x*x)%md;
        m >>= 1;
    }
    return r % md;
}

T[3] extGcd(T)(in T a, in T b)
if (!isIntegral!T || isSigned!T)
{
    if (b==0) {
        return [T(1), T(0), a];
    } else {
        auto e = extGcd(b, a%b);
        return [e[1], e[0]-a/b*e[1], e[2]];
    }
}

T invMod(T)(T x, T md) {
    auto r = extGcd!T(x, md);
    assert(r[2] == 1);
    auto z = r[0];
    return (z % md + md) % md;
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/ldc/inline.d */
// module dkh.ldc.inline;

version(LDC) {
    pragma(LDC_inline_ir) R inlineIR(string s, R, P...)(P);
}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/int128.d */

// module dkh.int128;

version(LDC) {
//     import dkh.ldc.inline;
}

version(LDC) version(X86_64) {
    version = LDC_IR;
}

ulong[2] mul128(ulong a, ulong b) {
    ulong[2] res;
    version(LDC_IR) {
        ulong upper, lower;
        inlineIR!(`
            %r0 = zext i64 %0 to i128
            %r1 = zext i64 %1 to i128
            %r2 = mul i128 %r1, %r0
            %r3 = trunc i128 %r2 to i64
            %r4 = lshr i128 %r2, 64
            %r5 = trunc i128 %r4 to i64
            store i64 %r3, i64* %2
            store i64 %r5, i64* %3`, void)(a, b, &lower, &upper);
        return [lower, upper];
    } else version(D_InlineAsm_X86_64) {
        ulong upper, lower;
        asm {
            mov RAX, a;
            mul b;
            mov lower, RAX;
            mov upper, RDX;
        }
        return [lower, upper];
    } else {
        ulong B = 2UL^^32;
        ulong[2] a2 = [a % B, a / B];
        ulong[2] b2 = [b % B, b / B];
        ulong[4] c;
        foreach (i; 0..2) {
            foreach (j; 0..2) {
                c[i+j] += a2[i] * b2[j] % B;
                c[i+j+1] += a2[i] * b2[j] / B;
            }
        }
        foreach (i; 0..3) {
            c[i+1] += c[i] / B;
            c[i] %= B;
        }
        return [c[0] + c[1] * B, c[2] + c[3] * B];
    }
}

ulong div128(ulong[2] a, ulong b) {
    version(LDC_IR) {
        return inlineIR!(`
            %r0 = zext i64 %0 to i128
            %r1 = zext i64 %1 to i128
            %r2 = shl i128 %r1, 64
            %r3 = add i128 %r0, %r2
            %r4 = zext i64 %2 to i128
            %r5 = udiv i128 %r3, %r4
            %r6 = trunc i128 %r5 to i64
            ret i64 %r6`,ulong)(a[0], a[1], b);
    } else version(D_InlineAsm_X86_64) {
        ulong upper = a[1], lower = a[0];
        ulong res;
        asm {
            mov RDX, upper;
            mov RAX, lower;
            div b;
            mov res, RAX;
        }
        return res;
    } else {
        if (b == 1) return a[0];
        while (!(b & (1UL << 63))) {
            a[1] <<= 1;
            if (a[0] & (1UL << 63)) a[1] |= 1;
            a[0] <<= 1;
            b <<= 1;
        }
        ulong ans = 0;
        foreach (i; 0..64) {
            bool up = (a[1] & (1UL << 63)) != 0;
            a[1] <<= 1;
            if (a[0] & (1UL << 63)) a[1] |= 1;
            a[0] <<= 1;

            ans <<= 1;
            if (up || b <= a[1]) {
                a[1] -= b;
                ans++;
            }
        }
        return ans;
    }
}

ulong mod128(ulong[2] a, ulong b) {
    version(D_InlineAsm_X86_64) {
        ulong upper = a[1], lower = a[0];
        ulong res;
        asm {
            mov RDX, upper;
            mov RAX, lower;
            div b;
            mov res, RDX;
        }
        return res;
    } else {
        return a[0] - div128(a, b) * b;
    }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/

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

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

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

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

enum LIM = 10^^5;
bool[] isnp;

void main() {
  isnp = new bool[LIM];
  foreach (p; 2 .. LIM) {
    if (!isnp[p]) {
      for (int n = 2 * p; n < LIM; n += p) {
        isnp[n] = true;
      }
    }
  }

  debug {
    for (int n = 3; n <= 1000; ++n) {
      bool found;
      foreach (p; n .. n + n / 2) {
        if (p >= 2 && !isnp[p]) {
          found = true;
        }
      }
      if (!found) {
        writeln("failed ", n);
      }
    }
  }

  try {
    for (; ; ) {
      const N = readInt();

      int k;
      for (k = 0; k < N / 2; ++k) {
        if (N + k >= 2 && !isnp[N + k]) {
          break;
        }
      }
      debug {
        writeln("N = ", N, ": k = ", k);
      }

      int[] as, bs;
      foreach (i; 0 .. N) {
        as ~= i;
        bs ~= (i + 1) % N;
      }
      foreach (i; 0 .. k) {
        as ~= i;
        bs ~= (i + N / 2) % N;
      }

      writeln(N + k);
      foreach (i; 0 .. N + k) {
        writeln(as[i] + 1, " ", bs[i] + 1);
      }
    }
  } catch (EOFException e) {
  }
}


After a terrifying forest fire in Berland a forest rebirth program was carried out. Due to it N rows with M trees each were planted and the rows were so neat that one could map it on a system of coordinates so that the j-th tree in the i-th row would have the coordinates of (i, j). However a terrible thing happened and the young forest caught fire. Now we must find the coordinates of the tree that will catch fire last to plan evacuation.The burning began in K points simultaneously, which means that initially K trees started to burn. Every minute the fire gets from the burning trees to the ones that aren’t burning and that the distance from them to the nearest burning tree equals to 1.Find the tree that will be the last to start burning. If there are several such trees, output any.

The first input line contains two integers N, M (1 ≤ N, M ≤ 2000) — the size of the forest. The trees were planted in all points of the (x, y) (1 ≤ x ≤ N, 1 ≤ y ≤ M) type, x and y are integers. The second line contains an integer K (1 ≤ K ≤ 10) — amount of trees, burning in the beginning.  The third line contains K pairs of integers: x1, y1, x2, y2, ..., xk, yk (1 ≤ xi ≤ N, 1 ≤ yi ≤ M) — coordinates of the points from which the fire started. It is guaranteed that no two points coincide.

Output a line with two space-separated integers x and y — coordinates of the tree that will be the last one to start burning. If there are several such trees, output any.

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

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

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

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

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

int M, N, K;
int[] X, Y;

void main(string[] args) {
	auto inp = File("input.txt", "r");
	auto outp = File("output.txt", "w");
	for (string line; (line = inp.readln) != null; ) {
		{
			auto tks = line.split;
			M = tks[0].to!int;
			N = tks[1].to!int;
		}
		K = inp.readln.chomp.to!int;
		X = new int[K];
		Y = new int[K];
		{
			auto tks = inp.readln.split;
			foreach (i; 0 .. K) {
				X[i] = tks[i * 2 + 0].to!int;
				Y[i] = tks[i * 2 + 1].to!int;
			}
		}

		int opt = -1;
		int xm = -1, ym = -1;
		foreach (x; 1 .. M + 1) foreach (y; 1 .. N + 1) {
			int tmp = M + N;
			foreach (i; 0 .. K) {
				chmin(tmp, abs(x - X[i]) + abs(y - Y[i]));
			}
			if (opt < tmp) {
				opt = tmp;
				xm = x;
				ym = y;
			}
		}
		outp.writeln(xm, " ", ym);
	}
}


This is an interactive problem.Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice.As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and  sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists.You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions.

At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students. You are allowed to ask no more than 60 questions.

To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109). When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program. The query that contains your answer is not counted towards the limit of 60 queries. Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language. Hacking Use the following format for hacking: In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students. In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or  - 1. The hacked solution will not have direct access to the sequence ai.

NoteInput-output in statements illustrates example interaction.In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2In the second sample the selection sequence is 1, 2, 3, 2, 1, 0.

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

int ask(int q) {
    writeln("? ", q);
    stdout.flush();
    return readln.chomp.to!int;
}

void answer(int x) {
    writeln("! ", x);
    stdout.flush();
}

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

    if (n % 2 == 1) {
        answer(-1);
        return;
    }

    n /= 2;
    auto stdiff = ask(1) - ask(n+1);

    if (stdiff % 2 == 1) {
        answer(-1);
        return;
    } else if (stdiff == 0) {
        answer(1);
        return;
    }

    auto lo = 2, hi = n;
    while (lo < hi) {
        auto med = (lo + hi) / 2;
        auto d = ask(med) - ask(n+med);
        if (d == 0) {
            answer(med);
            return;
        }

        if (sgn(d) == sgn(stdiff)) lo = med + 1;
        else hi = med - 1;
    }

    if (ask(lo) - ask(lo + n) == 0) {
        answer(lo);
    } else {
        answer(-1);
    }
}

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

void main ()
{
	int n;

	int ask (int pos)
	{
		int x, y;

		writeln ("? ", pos);
		stdout.flush ();
		readf (" %s", &x);

		writeln ("? ", pos + n / 2);
		stdout.flush ();
		readf (" %s", &y);

		return x - y;
	}

	void go (int lo, int hi, int valLo, int valHi)
	{
		int me = (lo + hi) / 2;
		auto d = ask (me);
		if (d == 0)
		{
			writeln ("! ", me);
			stdout.flush ();
		}
		else if (d * 1L * valLo < 0)
		{
			go (lo, me, valLo, d);
		}
		else if (d * 1L * valHi < 0)
		{
			go (me, hi, d, valHi);
		}
		else
		{
			assert (false);
		}
	}

	while (readf (" %s", &n) > 0)
	{
		if (n % 4 == 0)
		{
			auto d = ask (1);
			if (d == 0)
			{
				writeln ("! ", 1);
				stdout.flush ();
			}
			else
			{
				go (1, n / 2 + 1, +d, -d);
			}
		}
		else
		{
			writeln ("! ", -1);
			stdout.flush ();
		}
	}
}

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

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

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

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

int N;
long[] A;

long Ask(int i) {
  debug {
    return A[i];
  } else {
    writefln("? %s", i + 1);
    stdout.flush;
    const res = readLong();
    return res;
  }
}
void Answer(int i) {
  writefln("! %s", i + 1);
  stdout.flush;
  import core.stdc.stdlib;
  exit(0);
}

void main() {
  N = readInt();
  debug {
    A = new long[N];
    foreach (i; 0 .. N) {
      A[i] = readInt();
    }
  }

  if (N % 4 != 0) {
    Answer(-2);
  }

  const a = Ask(0);
  const b = Ask(N / 2);
  if (a == b) {
    Answer(0);
  }
  int lo = 0, hi = N / 2;
  for (; lo + 1 < hi; ) {
    const mid = (lo + hi) / 2;
    const c = Ask(mid);
    const d = Ask(mid + N / 2);
    if (c == d) {
      Answer(mid);
    }
    (((a < b) == (c < d)) ? lo : hi) = mid;
  }
  Answer(hi);
}

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

int ask(int q) {
    writeln("? ", q);
    stdout.flush();
    return readln.chomp.to!int;
}

void answer(int x) {
    writeln("! ", x);
    stdout.flush();
}

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

    if (n % 2 == 1) {
        answer(-1);
        return;
    }

    n /= 2;
    auto stdiff = ask(1) - ask(n+1);

    if (stdiff % 2 == 1) {
        answer(-1);
        return;
    } else if (stdiff == 0) {
        answer(1);
        return;
    }

    auto lo = 2, hi = n;
    while (lo < hi) {
        auto med = (lo + hi) / 2;
        auto d = ask(med) - ask(n+med);
        if (d == 0) {
            answer(med);
            return;
        }

        if (sgn(d) == sgn(stdiff)) lo = med + 1;
        else hi = med - 1;
    }

    answer(lo);
}

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

int ask(int q) {
    writeln("? ", q);
    stdout.flush();
    return readln.chomp.to!int;
}

void answer(int x) {
    writeln("! ", x);
    stdout.flush();
}

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

    if (n % 2 == 1) {
        answer(-1);
        return;
    }

    n /= 2;
    auto stdiff = ask(1) - ask(n+1);

    if (stdiff % 2 == 1) {
        answer(-1);
        return;
    } else if (stdiff == 0) {
        answer(1);
        return;
    }

    auto lo = 2, hi = n;
    while (lo < hi) {
        auto med = (lo + hi) / 2;
        auto d = ask(med) - ask(n+med);
        if (d == 0) {
            answer(med);
            return;
        }

        if (sgn(d) == sgn(stdiff)) lo = med + 1;
        else hi = med - 1;
    }
}

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

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

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

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

int N;
long[] A;

long Ask(int i) {
  debug {
    return A[i];
  } else {
    writefln("? %s", i + 1);
    stdout.flush;
    const res = readLong();
    return res;
  }
}
void Answer(int i) {
  writefln("! %s", i + 1);
  stdout.flush;
  import core.stdc.stdlib;
  exit(0);
}

void main() {
  N = readInt();
  debug {
    A = new long[N];
    foreach (i; 0 .. N) {
      A[i] = readInt();
    }
  }

  if (N % 4 != 0) {
    Answer(-2);
  }

  const a = Ask(0);
  const b = Ask(N / 2);
  if (a == b) {
    Answer(0);
  }
  int lo = 0, hi = N / 2;
  for (; lo + 1 < hi; ) {
    const mid = (lo + hi) / 2;
    const c = Ask(mid);
    const d = Ask(mid + N / 2);
    (((a < b) == (c < d)) ? lo : hi) = mid;
  }
  Answer(hi);
}


You are at the top left cell $$$(1, 1)$$$ of an $$$n \times m$$$ labyrinth. Your goal is to get to the bottom right cell $$$(n, m)$$$. You can only move right or down, one cell per step. Moving right from a cell $$$(x, y)$$$ takes you to the cell $$$(x, y + 1)$$$, while moving down takes you to the cell $$$(x + 1, y)$$$.Some cells of the labyrinth contain rocks. When you move to a cell with rock, the rock is pushed to the next cell in the direction you're moving. If the next cell contains a rock, it gets pushed further, and so on.The labyrinth is surrounded by impenetrable walls, thus any move that would put you or any rock outside of the labyrinth is illegal.Count the number of different legal paths you can take from the start to the goal modulo $$$10^9 + 7$$$. Two paths are considered different if there is at least one cell that is visited in one path, but not visited in the other.

The first line contains two integers $$$n, m$$$ — dimensions of the labyrinth ($$$1 \leq n, m \leq 2000$$$). Next $$$n$$$ lines describe the labyrinth. Each of these lines contains $$$m$$$ characters. The $$$j$$$-th character of the $$$i$$$-th of these lines is equal to "R" if the cell $$$(i, j)$$$ contains a rock, or "." if the cell $$$(i, j)$$$ is empty. It is guaranteed that the starting cell $$$(1, 1)$$$ is empty.

Print a single integer — the number of different legal paths from $$$(1, 1)$$$ to $$$(n, m)$$$ modulo $$$10^9 + 7$$$.

NoteIn the first sample case we can't (and don't have to) move, hence the only path consists of a single cell $$$(1, 1)$$$.In the second sample case the goal is blocked and is unreachable.Illustrations for the third sample case can be found here: https://assets.codeforces.com/rounds/1225/index.html

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

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

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

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

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

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

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

      if (M == 1 && N == 1) {
        writeln(1);
        continue;
      }

      auto rows = new int[][](M, N + 1);
      auto cols = new int[][](N, M + 1);
      foreach (x; 0 .. M) {
        foreach (y; 0 .. N) {
          rows[x][y + 1] = rows[x][y] + ((A[x][y] == 'R') ? 1 : 0);
        }
      }
      foreach (y; 0 .. N) {
        foreach (x; 0 .. M) {
          cols[y][x + 1] = cols[y][x] + ((A[x][y] == 'R') ? 1 : 0);
        }
      }

      bool checkRow(int x, int y0, int y1) {
        return (rows[x][y1 + 1] - rows[x][y0 + 1] <= (N - (y1 + 1)) - (rows[x][N] - rows[x][y1 + 1]));
      }
      bool checkCol(int y, int x0, int x1) {
        return (cols[y][x1 + 1] - cols[y][x0 + 1] <= (M - (x1 + 1)) - (cols[y][M] - cols[y][x1 + 1]));
      }

      auto dp0Sum = new Mint[][](M, N + 1);
      auto dp1Sum = new Mint[][](N, M + 1);
      dp0Sum[0][1] = 1;
      dp1Sum[0][1] = 1;
      auto xs = new int[N];
      auto ys = new int[M];
      foreach (x; 0 .. M) foreach (y; 0 .. N) {
        if (x + y > 0) {
          for (; !checkCol(y, xs[y], x); ++xs[y]) {}
          dp0Sum[x][y + 1] = dp0Sum[x][y] + (dp1Sum[y][x] - dp1Sum[y][xs[y]]);
          for (; !checkRow(x, ys[x], y); ++ys[x]) {}
          dp1Sum[y][x + 1] = dp1Sum[y][x] + (dp0Sum[x][y] - dp0Sum[x][ys[x]]);
        }
      }
      Mint ans;
      ans += dp0Sum[M - 1][N] - dp0Sum[M - 1][N - 1];
      ans += dp1Sum[N - 1][M] - dp1Sum[N - 1][M - 1];
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You are given a line of $$$n$$$ colored squares in a row, numbered from $$$1$$$ to $$$n$$$ from left to right. The $$$i$$$-th square initially has the color $$$c_i$$$.Let's say, that two squares $$$i$$$ and $$$j$$$ belong to the same connected component if $$$c_i = c_j$$$, and $$$c_i = c_k$$$ for all $$$k$$$ satisfying $$$i < k < j$$$. In other words, all squares on the segment from $$$i$$$ to $$$j$$$ should have the same color.For example, the line $$$[3, 3, 3]$$$ has $$$1$$$ connected component, while the line $$$[5, 2, 4, 4]$$$ has $$$3$$$ connected components.The game "flood fill" is played on the given line as follows:   At the start of the game you pick any starting square (this is not counted as a turn).  Then, in each game turn, change the color of the connected component containing the starting square to any other color. Find the minimum number of turns needed for the entire line to be changed into a single color.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of squares. The second line contains integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \le c_i \le 5000$$$) — the initial colors of the squares.

Print a single integer — the minimum number of the turns needed.

NoteIn the first example, a possible way to achieve an optimal answer is to pick square with index $$$2$$$ as the starting square and then play as follows:  $$$[5, 2, 2, 1]$$$  $$$[5, 5, 5, 1]$$$  $$$[1, 1, 1, 1]$$$ In the second example, a possible way to achieve an optimal answer is to pick square with index $$$5$$$ as the starting square and then perform recoloring into colors $$$2, 3, 5, 4$$$ in that order.In the third example, the line already consists of one color only.

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

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

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

    arr = arr.uniq.array;

    debug { arr.writeln; }

    auto dp = new int[][] (arr.length, arr.length);

    int go(int le, int r) {
        if (dp[le][r]) { return dp[le][r]; }

        if (le == r) { return 0; }

        dp[le][r] = 1 + (arr[le] == arr[r] ?
            go(le+1, r-1) : min(go(le+1, r), go(le, r-1)));

        return dp[le][r];
    }

    int ans = go(0, arr.length.to!int - 1);

    ans.writeln;
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;
import std.functional;

alias type = single;
struct TestCase
{
  mixin prettyPrinting;

  int n;
  @Dim("n") int[] c;

  void solve(long tc = -1)
  {
    auto comps = new int[](1);
    comps[0] = c[0];
    foreach(ci; c[1 .. $])
      if (comps[$ - 1] != ci)
        comps ~= ci;
    auto dp = new int[][](comps.length + 1, comps.length + 1);
    foreach(prefix; 0 .. cast(int) comps.length)
      {
        foreach(suffix; 0 .. cast(int) comps.length)
          {
            if (prefix == 0)
              dp[prefix][suffix] = suffix;
            else if (suffix == 0)
              dp[prefix][suffix] = prefix;
            else if (comps[prefix - 1] == comps[$ - suffix])
              dp[prefix][suffix] = 1 + dp[prefix - 1][suffix - 1];
            else
              dp[prefix][suffix] = 1 + min(dp[prefix - 1][suffix], dp[prefix][suffix - 1]);
          }
      }
    iota(0, cast(int)comps.length).map!(i => dp[i][cast(int)comps.length - i - 1]).fold!min.writeln;
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}