This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.You are given a binary table of size $$$n \times m$$$. This table consists of symbols $$$0$$$ and $$$1$$$.You can make such operation: select $$$3$$$ different cells that belong to one $$$2 \times 2$$$ square and change the symbols in these cells (change $$$0$$$ to $$$1$$$ and $$$1$$$ to $$$0$$$).Your task is to make all symbols in the table equal to $$$0$$$. You are allowed to make at most $$$nm$$$ operations. You don't need to minimize the number of operations.It can be proved, that it is always possible.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 5000$$$) — the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n, m \leq 100$$$). Each of the next $$$n$$$ lines contains a binary string of length $$$m$$$, describing the symbols of the next row of the table. It is guaranteed, that the sum of $$$nm$$$ for all test cases does not exceed $$$20000$$$.

For each test case print the integer $$$k$$$ ($$$0 \leq k \leq nm$$$) — the number of operations. In the each of the next $$$k$$$ lines print $$$6$$$ integers $$$x_1, y_1, x_2, y_2, x_3, y_3$$$ ($$$1 \leq x_1, x_2, x_3 \leq n, 1 \leq y_1, y_2, y_3 \leq m$$$) describing the next operation. This operation will be made with three cells $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$. These three cells should be different. These three cells should belong to some $$$2 \times 2$$$ square.

NoteIn the first test case, it is possible to make only one operation with cells $$$(1, 1)$$$, $$$(2, 1)$$$, $$$(2, 2)$$$. After that, all symbols will be equal to $$$0$$$.In the second test case:  operation with cells $$$(2, 1)$$$, $$$(3, 1)$$$, $$$(3, 2)$$$. After it the table will be: 011001000  operation with cells $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 3)$$$. After it the table will be: 000000000 In the fifth test case:  operation with cells $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$. After it the table will be: 010110  operation with cells $$$(1, 2)$$$, $$$(2, 1)$$$, $$$(2, 2)$$$. After it the table will be: 000000

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[][][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto s = new char[][](n);
		foreach (i; 0..n)
			s[i] = RD!(char[]);

		foreach (y; 0..n-1)
		{
			foreach (x; 0..m-1)
			{
				debug writeln("y:", y, " x:", x);
				void draw(long[] pos)
				{
					ans[ti] ~= [pos[0]+1, pos[1]+1, pos[2]+1, pos[3]+1, pos[4]+1, pos[5]+1];
					foreach (i; 0..3)
					{
						auto yy = cast(int)pos[i*2];
						auto xx = cast(int)pos[i*2+1];
						s[yy][xx] = s[yy][xx] == '0' ? '1' : '0';
					}
				}
				void fin()
				{
					long[] tmp;
					foreach (i; 0..2)
					{
						foreach (j; 0..2)
						{
							if (s[y+i][x+j] == '1')
								tmp ~= [y+i, x+j];
						}
					}
					draw(tmp);
				}
				void fin2()
				{
					long[] tmp;
					bool mode;
					foreach (i; 0..2)
					{
						foreach (j; 0..2)
						{
							if (s[y+i][x+j] == '1')
							{
								if (mode) continue;
								mode = true;
								tmp ~= [y+i, x+j];
							}
							else
								tmp ~= [y+i, x+j];
						}
					}
					draw(tmp);
					fin();
				}
				if (y == n-2 && x == m-2)
				{
					long cnt;
					foreach (i; 0..2)
					{
						foreach (j; 0..2)
						{
							if (s[y+i][x+j] == '1')
								++cnt;
						}
					}
					if (cnt == 4)
					{
						draw([y, x, y, x+1, y+1, x+1]);
						draw([y, x, y+1, x, y+1, x+1]);
						draw([y+1, x, y, x+1, y+1, x+1]);
						fin();
					}
					else if (cnt == 3)
					{
						fin();
					}
					else if (cnt == 2)
					{
						fin2();
					}
					else if (cnt == 1)
					{
						long[] tmp;
						int mode;
						foreach (i; 0..2)
						{
							foreach (j; 0..2)
							{
								if (s[y+i][x+j] == '0')
								{
									if (mode == 2) continue;
									++mode;
									tmp ~= [y+i, x+j];
								}
								else
									tmp ~= [y+i, x+j];
							}
						}
						draw(tmp);
						fin2();
					}
				}
				else if (y == n-2)
				{
					if (s[y][x] == '1' && s[y+1][x] == '1')
						draw([y, x, y+1, x, y, x+1]);
					else if (s[y][x] == '1')
						draw([y, x, y, x+1, y+1, x+1]);
					else if (s[y+1][x] == '1')
						draw([y+1, x, y, x+1, y+1, x+1]);
				}
				else if (x == m-2)
				{
					if (s[y][x] == '1' && s[y][x+1] == '1')
						draw([y, x, y, x+1, y+1, x+1]);
					else if (s[y][x] == '1')
						draw([y, x, y+1, x, y+1, x+1]);
					else if (s[y][x+1] == '1')
						draw([y+1, x, y, x+1, y+1, x+1]);
				}
				else
				{
					if (s[y][x] == '0') continue;
					draw([y, x, y, x+1, y+1, x+1]);
				}
			}
		}
		debug
		{
			foreach (i; 0..n)
				writeln(s[i]);
		}
	}

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

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

void main () {
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests) {
		int rows, cols;
		readf !(" %s %s ") (rows, cols);
		uint [] [] board;
		foreach (row; 0..rows)
			board ~= readln.strip.map !(q{a - '0'}).array;

		int [] [] answer;

		void go (int row, int col, int row1, int col1, int row2, int col2) {
			answer ~= [row, col, row1, col1, row2, col2];
			board[row][col] ^= 1;
			board[row1][col1] ^= 1;
			board[row2][col2] ^= 1;
		}

		foreach_reverse (row; 0..rows)
			foreach_reverse (col; 0..cols)
				if ((row == rows - 1 && rows % 2 == 1) || (col == cols - 1 && cols % 2 == 1))
					if (board[row][col]) {
						auto row1 = max (row - 1, 0);
						auto col1 = max (col - 1, 0);
						auto row2 = row1 + 1;
						auto col2 = col1;
						if (row2 == row && col2 == col) {
							row2 = row1;
							col2 = col1 + 1;
						}
						go (row, col, row1, col1, row2, col2);
					}

		void doSquare (int row, int col) {
			while (true) {
				auto total = board[row + 0][col + 0] +
				    board[row + 1][col + 0] +
				    board[row + 0][col + 1] +
				    board[row + 1][col + 1];
				if (total == 0)
					break;
				int [] seqRow, seqCol;
				foreach_reverse (value; 0..2)
					foreach (rowT; row..row + 2)
						foreach (colT; col..col + 2)
							if (board[rowT][colT] == value) {
								seqRow ~= rowT;
								seqCol ~= colT;
							}
				if (total == 2) {
					seqRow.popFront ();
					seqCol.popFront ();
				}
				go (seqRow[0], seqCol[0],
				    seqRow[1], seqCol[1],
				    seqRow[2], seqCol[2]);
			}
		}

		for (int row = 0; row + 1 < rows; row += 2)
			for (int col = 0; col + 1 < cols; col += 2)
				doSquare (row, col);

		writeln (answer.length);
		foreach (ref line; answer)
			writefln !("%(%s %)") (line.map !(q{a + 1}));
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		uint [] [] board;
		foreach (row; 0..rows)
		{
			board ~= readln.strip.map !(q{a - '0'}).array;
		}

		int [] [] answer;

		void go (int row, int col,
		    int row1, int col1, int row2, int col2)
		{
			answer ~= [row, col, row1, col1, row2, col2];
			board[row][col] ^= 1;
			board[row1][col1] ^= 1;
			board[row2][col2] ^= 1;
		}

		foreach_reverse (row; 0..rows)
		{
			foreach_reverse (col; 0..cols)
			{
				if ((row == rows - 1 && rows % 2 == 1) ||
				    (col == cols - 1 && cols % 2 == 1))
				{
					if (board[row][col])
					{
						auto row1 = max (row - 1, 0);
						auto col1 = max (col - 1, 0);
						auto row2 = row1 + 1;
						auto col2 = col1;
						if (row2 == row &&
						    col2 == col)
						{
							row2 = row1;
							col2 = col1 + 1;
						}
						go (row, col,
						    row1, col1, row2, col2);
					}
				}
			}
		}

		void doSquare (int row, int col)
		{
			while (true)
			{
				auto total = board[row + 0][col + 0] +
				    board[row + 1][col + 0] +
				    board[row + 0][col + 1] +
				    board[row + 1][col + 1];
				if (total == 0)
				{
					break;
				}
				int [] seqRow;
				int [] seqCol;
				foreach_reverse (value; 0..2)
				{
					foreach (rowT; row..row + 2)
					{
						foreach (colT; col..col + 2)
						{
							if (board[rowT][colT]
							    == value)
							{
								seqRow ~= rowT;
								seqCol ~= colT;
							}
						}
					}
				}
				if (total == 2)
				{
					seqRow.popFront ();
					seqCol.popFront ();
				}
				go (seqRow[0], seqCol[0],
				    seqRow[1], seqCol[1],
				    seqRow[2], seqCol[2]);
			}
		}

		for (int row = 0; row + 1 < rows; row += 2)
		{
			for (int col = 0; col + 1 < cols; col += 2)
			{
				doSquare (row, col);
			}
		}

		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (board[row][col])
				{
					assert (false);
				}
			}
		}

		writeln (answer.length);
		foreach (ref line; answer)
		{
			writefln !("%(%s %)") (line.map !(q{a + 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)); }

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

        auto a = new int[][](M, N);
        foreach (x; 0 .. M) foreach (y; 0 .. N) {
          a[x][y] = A[x][y] - '0';
        }

        int[][] ans;
        void oper(int x0, int y0, int x1, int y1, int x2, int y2) {
          ans ~= [x0, y0, x1, y1, x2, y2];
          a[x0][y0] ^= 1;
          a[x1][y1] ^= 1;
          a[x2][y2] ^= 1;
        }

        foreach (x; 0 .. M - 2) foreach (y; 0 .. N - 2) {
          if (a[x][y]) {
            oper(x, y, x, y + 1, x + 1, y);
          }
        }
        foreach (x; 0 .. M - 2) {
          const y = N - 2;
          if (a[x][y]) {
            if (a[x][y + 1]) {
              oper(x, y, x, y + 1, x + 1, y);
            } else {
              oper(x, y, x + 1, y, x + 1, y + 1);
            }
          } else {
            if (a[x][y + 1]) {
              oper(x, y + 1, x + 1, y, x + 1, y + 1);
            } else {
              oper(x, y, x, y + 1, x + 1, y);
              oper(x, y, x, y + 1, x + 1, y);
            }
          }
        }
        foreach (y; 0 .. N - 2) {
          const x = M - 2;
          if (a[x][y]) {
            if (a[x + 1][y]) {
              oper(x, y, x + 1, y, x, y + 1);
            } else {
              oper(x, y, x, y + 1, x + 1, y + 1);
            }
          } else {
            if (a[x + 1][y]) {
              oper(x + 1, y, x, y + 1, x + 1, y + 1);
            } else {
              oper(x, y, x + 1, y, x, y + 1);
              oper(x, y, x + 1, y, x, y + 1);
            }
          }
        }
        {
          const x = M - 2, y = N - 2;
          foreach (p; 0 .. 1 << 4) {
            auto bs = new int[4];
            foreach (i; 0 .. 4) {
              if (p & 1 << i) {
                foreach (j; 0 .. 4) {
                  if (i != j) {
                    bs[j] ^= 1;
                  }
                }
              }
            }
            debug {
              writeln(p, ": ", bs);
            }
            bool ok = true;
            foreach (j; 0 .. 4) {
              ok = ok && (a[x + j / 2][y + j % 2] == bs[j]);
            }
            if (ok) {
              if (p & 1 << 0) oper(x, y + 1, x + 1, y, x + 1, y + 1);
              if (p & 1 << 1) oper(x, y, x + 1, y, x + 1, y + 1);
              if (p & 1 << 2) oper(x, y, x, y + 1, x + 1, y + 1);
              if (p & 1 << 3) oper(x, y, x, y + 1, x + 1, y);
            }
          }
        }

        writeln(ans.length);
        foreach (row; ans) {
          foreach (i; 0 .. 6) {
            if (i > 0) write(" ");
            write(row[i] + 1);
          }
          writeln;
        }
        debug {
          writeln("a = ", a);
        }
      }
    }
  } catch (EOFException e) {
  }
}


Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 10 000, n ≥ 2m) — the number of participants of the qualifying contest and the number of regions in Berland. Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive). It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.

Print m lines. On the i-th line print the team of the i-th region — the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region.

5 2
Ivanov 1 763
Andreev 2 800
Petrov 1 595
Sidorov 1 790
Semenov 2 503

5 2
Ivanov 1 800
Andreev 2 763
Petrov 1 800
Sidorov 1 800
Semenov 2 503

NoteIn the first sample region teams are uniquely determined.In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.

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

class Student
{
    string surname;
    int region;
    int score;
}

void main()
{
    int n, m;
    Student[] students;

    readf("%d %d ", &n, &m);
    students = new Student[n];
    for (int i = 0; i < n; i++) {
        Student s = new Student();

        string buffer = readln();
        string[] tokens = split(buffer);

        s.surname = tokens[0];
        s.region = to!(int)(tokens[1]);
        s.score = to!(int)(tokens[2]);

        students[i] = s;
    }

    sort!(function (Student a, Student b) {
        if (a.region != b.region)
            return a.region < b.region;
        return a.score > b.score;
    })(students);

    int i = 0;
    while (i < n) {
        if (i + 2 < n && students[i + 2].region == students[i].region && students[i + 1].score == students[i + 2].score) {
            writef("?\n");
        }
        else {
            writef("%s %s\n", students[i].surname, students[i + 1].surname);
        }

        i++;
        while (i < n && students[i].region == students[i - 1].region) {
            i++;
        }
    }
}


You are given a permutation of length $$$n$$$. Recall that the permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2, 3, 1, 5, 4]$$$ is a permutation, but $$$[1, 2, 2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1, 3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).You can perform at most $$$n-1$$$ operations with the given permutation (it is possible that you don't perform any operations at all). The $$$i$$$-th operation allows you to swap elements of the given permutation on positions $$$i$$$ and $$$i+1$$$. Each operation can be performed at most once. The operations can be performed in arbitrary order.Your task is to find the lexicographically minimum possible permutation obtained by performing some of the given operations in some order.You can see the definition of the lexicographical order in the notes section.You have to answer $$$q$$$ independent test cases.For example, let's consider the permutation $$$[5, 4, 1, 3, 2]$$$. The minimum possible permutation we can obtain is $$$[1, 5, 2, 4, 3]$$$ and we can do it in the following way:  perform the second operation (swap the second and the third elements) and obtain the permutation $$$[5, 1, 4, 3, 2]$$$;  perform the fourth operation (swap the fourth and the fifth elements) and obtain the permutation $$$[5, 1, 4, 2, 3]$$$;  perform the third operation (swap the third and the fourth elements) and obtain the permutation $$$[5, 1, 2, 4, 3]$$$.  perform the first operation (swap the first and the second elements) and obtain the permutation $$$[1, 5, 2, 4, 3]$$$; Another example is $$$[1, 2, 4, 3]$$$. The minimum possible permutation we can obtain is $$$[1, 2, 3, 4]$$$ by performing the third operation (swap the third and the fourth elements).

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of test cases. Then $$$q$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation.

For each test case, print the answer on it — the lexicograhically minimum possible permutation obtained by performing some of the given operations in some order.

NoteRecall that the permutation $$$p$$$ of length $$$n$$$ is lexicographically less than the permutation $$$q$$$ of length $$$n$$$ if there is such index $$$i \le n$$$ that for all $$$j$$$ from $$$1$$$ to $$$i - 1$$$ the condition $$$p_j = q_j$$$ is satisfied, and $$$p_i < q_i$$$. For example:  $$$p = [1, 3, 5, 2, 4]$$$ is less than $$$q = [1, 3, 5, 4, 2]$$$ (such $$$i=4$$$ exists, that $$$p_i < q_i$$$ and for each $$$j < i$$$ holds $$$p_j = q_j$$$),  $$$p = [1, 2]$$$ is less than $$$q = [2, 1]$$$ (such $$$i=1$$$ exists, that $$$p_i < q_i$$$ and for each $$$j < i$$$ holds $$$p_j = q_j$$$).

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[][](q);
	foreach (i; 0..q)
	{
		auto n = RD!int;
		auto a = RDA;
		ans[i] ~= 1;
		long num = 1;
		foreach (j; 0..n)
		{
			if (num == a[j])
			{
				if (j == n-1) break;
				auto p = a[j+1..$].MIN_POS();
				num = a[j+1+p];
				ans[i] ~= num;
				if (ans[i][$-2] > ans[i][$-1])
				{
					swap(ans[i][$-2], ans[i][$-1]);
				}
			}
			else
			{
				ans[i] ~= a[j];
			}
		}
	}

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


Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:   if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or  burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.

The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.

Output one integer — the minimum power needed to destroy the avengers base.

NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto a = s[2];
    auto b = s[3];
    auto A = readln.split.map!(x => x.to!long-1).array;
    A.sort();

    long dfs(long l, long r) {
        auto lb1 = A.assumeSorted.lowerBound(l).length.to!int;
        auto lb2 = A.assumeSorted.lowerBound(r+1).length.to!int;
        long cnt = lb2 - lb1;

        if (cnt == 0) {
            return a;
        } else if (l == r) {
            return b * cnt;
        } else {
            return min(b * cnt * (r - l + 1), dfs(l, (l+r)/2) + dfs((l+r)/2+1, r));
        }
    }

    dfs(0, (1L << N) - 1).writeln;
}

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto K = s[1];
    auto a = s[2];
    auto b = s[3];
    auto A = readln.split.map!(to!long).array;
    A.sort();

    long dfs(long l, long r) {
        auto lb1 = A.assumeSorted.lowerBound(l).length.to!int;
        auto lb2 = A.assumeSorted.lowerBound(r+1).length.to!int;
        long cnt = lb2 - lb1;

        if (cnt == 0) {
            return a;
        } else if (l == r) {
            return b * cnt;
        } else {
            return min(b * cnt * (r - l + 1), dfs(l, (l+r)/2) + dfs((l+r)/2+1, r));
        }
    }

    dfs(0, (1L << N) - 1).writeln;
}


You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.

The only line contains a string $$$s$$$ consisting of zeroes and ones ($$$1 \le |s| \le 1000$$$). Zero describes vertical tile, one describes horizontal tile.

Output $$$|s|$$$ lines — for each tile you should output two positive integers $$$r,c$$$, not exceeding $$$4$$$, representing numbers of smallest row and column intersecting with it. If there exist multiple solutions, print any of them.

NoteFollowing image illustrates the example after placing all three tiles:    Then the first row is deleted:

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

void main() {
    auto S = readln.chomp;
    auto N = S.length.to!int;

    int v_count = 0;
    int h_count = 0;

    foreach (s; S) {
        if (s == '1') {
            writeln(1, " ", h_count + 1);
            h_count += 2;
            if (h_count == 4) h_count = 0;
        } else {
            writeln(3, " ", v_count + 1);
            v_count += 1;
            if (v_count == 4) v_count = 0;
        }
    }
}

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

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		bool have0 = false;
		bool have1 = false;
		foreach (ref c; s)
		{
			if (c == '0')
			{
				writeln (have0 ? 1 : 3, " ", 1);
				have0 ^= true;
			}
			else
			{
				writeln (1, " ", have1 ? 1 : 3);
				have1 ^= true;
			}
		}
	}
}


Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array $$$a$$$ with $$$n$$$ integers. You need to count the number of funny pairs $$$(l, r)$$$ $$$(l \leq r)$$$. To check if a pair $$$(l, r)$$$ is a funny pair, take $$$mid = \frac{l + r - 1}{2}$$$, then if $$$r - l + 1$$$ is an even number and $$$a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r$$$, then the pair is funny. In other words, $$$\oplus$$$ of elements of the left half of the subarray from $$$l$$$ to $$$r$$$ should be equal to $$$\oplus$$$ of elements of the right half. Note that $$$\oplus$$$ denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i < 2^{20}$$$) — array itself.

Print one integer — the number of funny pairs. You should consider only pairs where $$$r - l + 1$$$ is even number.

NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is $$$(2, 5)$$$, as $$$2 \oplus 3 = 4 \oplus 5 = 1$$$.In the second example, funny pairs are $$$(2, 3)$$$, $$$(1, 4)$$$, and $$$(3, 6)$$$.In the third example, there are no funny pairs.

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

immutable long INF = 10L ^^ 18 + 23;

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

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

    int[int][2] cnt;
    cnt[1][0] = 1;
    long ans = 0;
    int xr = 0;
    for (int i = 0; i < a.length; ++i) {
        xr ^= a[i];
        ans += cnt[i % 2].get(xr, 0);
        cnt[i % 2][xr] += 1;
    }

    ans.writeln;
}


For his birthday, Kevin received the set of pairwise distinct numbers $$$1, 2, 3, \ldots, n$$$ as a gift.He is going to arrange these numbers in a way such that the minimum absolute difference between two consecutive numbers be maximum possible. More formally, if he arranges numbers in order $$$p_1, p_2, \ldots, p_n$$$, he wants to maximize the value $$$$$$\min \limits_{i=1}^{n - 1} \lvert p_{i + 1} - p_i \rvert,$$$$$$ where $$$|x|$$$ denotes the absolute value of $$$x$$$.Help Kevin to do that.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$2 \le n \leq 1\,000$$$) — the size of the set.

For each test case print a single line containing $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$) describing the arrangement that maximizes the minimum absolute difference of consecutive elements.  Formally, you have to print a permutation $$$p$$$ which maximizes the value $$$\min \limits_{i=1}^{n - 1} \lvert p_{i + 1} - p_i \rvert$$$. If there are multiple optimal solutions, print any of them.

NoteIn the first test case the minimum absolute difference of consecutive elements equals $$$\min \{\lvert 4 - 2 \rvert, \lvert 1 - 4 \rvert, \lvert 3 - 1 \rvert \} = \min \{2, 3, 2\} = 2$$$. It's easy to prove that this answer is optimal.In the second test case each permutation of numbers $$$1, 2, 3$$$ is an optimal answer. The minimum absolute difference of consecutive elements equals to $$$1$$$.

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) {
    int n;
    readf!" %d "(n);
    int starto = n / 2 + 1;
    int starte = 1;
    int[] a;
    while (a.length < n) {
      a ~= starto++;
      if (a.length == n)
        break;
      a ~= starte++;
    }
    writefln("%(%s %)", a);
  }
}


Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can get in his new game for a given tree.

The first input line contains integer number n (1 ≤ n ≤ 700) — amount of vertices in the tree. The following n - 1 lines contain the description of the edges. Each line contains the pair of vertices' indexes, joined by an edge, ai, bi (1 ≤ ai, bi ≤ n). It's guaranteed that the graph described in the input is a tree.

Output the only number — the maximum product of sizes of the connected components, that Bob can get after deleting some of the tree's edges.

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

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

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

int N;
int[] A, B;

int[][] G;

BigInt[] dpP, dp0, dp1;

void solve(int u, int p) {
	foreach (v; G[u]) if (v != p) {
		solve(v, u);
	}

	int numChildren;
	foreach (v; G[u]) if (v != p) {
		++numChildren;
	}

	dpP[u] = 1;
	foreach (v; G[u]) if (v != p) {
		dpP[u] *= dp0[v];
	}

	auto crt = new BigInt[numChildren + 1];
	crt[0] = 1;
	foreach (v; G[u]) if (v != p) {
		auto nxt = new BigInt[numChildren + 1];
		foreach (x; 0 .. numChildren + 1) {
			//	disconnect
			{
				chmax(nxt[x], crt[x] * dp0[v]);
			}
			//	connect
			if (x < numChildren) {
				chmax(nxt[x + 1], crt[x] * dpP[v]);
			}
		}
		crt = nxt;
	}

	foreach (x; 0 .. numChildren + 1) {
		chmax(dp0[u], (1 + x) * crt[x]);
	}
	//	connect with one
	foreach (v; G[u]) if (v != p) {
		chmax(dp0[u], dpP[u] / dp0[v] * dp1[v]);
	}

	foreach (x; 0 .. numChildren + 1) {
		chmax(dp1[u], (2 + x) * crt[x]);
	}
}

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

		G = new int[][N];
		foreach (i; 0 .. N - 1) {
			G[A[i]] ~= B[i];
			G[B[i]] ~= A[i];
		}

		dpP = new BigInt[N];
		dp0 = new BigInt[N];
		dp1 = new BigInt[N];
		solve(0, -1);
debug{
writeln("dpP = ",dpP);
writeln("dp0 = ",dp0);
writeln("dp1 = ",dp1);
}

		writeln(dp0[0]);

	}
	} catch (EOFException) {}
}


Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!

The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.

Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.

NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto A = scan!int(N);

  auto solve() {
    int ans = int.max;
    foreach(i; 1..N - 1) {
      const mi = min(A[i - 1], A[i + 1]);
      const ma = max(A[i - 1], A[i + 1]);
      ans = min(ans, mi + (ma - mi + 1) / 2);
    }

    foreach(i; 1..N) {
      auto arr = A[i - 1..i + 1].dup;
      auto t = min((arr.maxElement + 1) / 2, arr.maxElement - arr.minElement);
      auto rest = arr.minElement - t;
      if (rest <= 0) {
        ans = min(ans, t);
      } else {
        auto dec = (rest / 3) * 2;
        ans = min(ans, t + dec + rest%3);
      }
    }

    auto sorted = A.sort;
    ans = min(ans, (sorted[0] + 1) / 2 + (sorted[1] + 1) / 2);

    return ans;
  }

  outputForAtCoder(&solve);
}

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

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

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

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}


Egor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help!Before you start solving the problem, Egor wants to remind you how the chess pieces move. Chess rook moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, it can stop. The queen walks in all directions vertically and diagonally at any distance. You can see the examples below.  To reach the goal, Egor should research the next topic:There is an $$$N \times N$$$ board. Each cell of the board has a number from $$$1$$$ to $$$N ^ 2$$$ in it and numbers in all cells are distinct.In the beginning, some chess figure stands in the cell with the number $$$1$$$. Note that this cell is already considered as visited. After that every move is determined by the following rules:   Among all not visited yet cells to which the figure can get in one move, it goes to the cell that has minimal number. If all accessible cells were already visited and some cells are not yet visited, then the figure is teleported to the not visited cell that has minimal number. If this step happens, the piece pays a fee of $$$1$$$ vun. If all cells are already visited, the process is stopped. Egor should find an $$$N \times N$$$ board on which the rook pays strictly less vuns than the queen during the round with this numbering. Help him to find such $$$N \times N$$$ numbered board, or tell that it doesn't exist.

The only line contains one integer $$$N$$$  — the size of the board, $$$1\le N \le 500$$$.

The output should contain $$$N$$$ lines. In $$$i$$$-th line output $$$N$$$ numbers  — numbers on the $$$i$$$-th row of the board. All numbers from $$$1$$$ to $$$N \times N$$$ must be used exactly once. On your board rook must pay strictly less vuns than the queen. If there are no solutions, print $$$-1$$$. If there are several solutions, you can output any of them.

NoteIn case we have $$$1 \times 1$$$ board, both rook and queen do not have a chance to pay fees.In second sample rook goes through cells $$$1 \to 3 \to 4 \to 6 \to 9 \to 5 \to 7 \to 13 \to 2 \to 8 \to 16 \to 11 \to 10 \to 12 \to 15 \to \textbf{(1 vun)} \to 14$$$. Queen goes through $$$1 \to 3 \to 4 \to 2 \to 5 \to 6 \to 9 \to 7 \to 13 \to 8 \to 11 \to 10 \to 12 \to 15 \to \textbf{(1 vun)} \to 14 \to \textbf{(1 vun)} \to 16$$$.As a result rook pays 1 vun and queen pays 2 vuns.

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		if (n < 3)
		{
			writeln (-1);
			continue;
		}
		auto board = new int [] [] (n, n);
		int cur = 0;
		int row = 0;
		int col = n - 1;

		void mark ()
		{
			cur += 1;
			board[row][col] = cur;
		}

		while (n > 3)
		{
			mark ();
			if (row < col)
			{
				while (row < col)
				{
					row += 1;
					mark ();
				}
				while (col > 0)
				{
					col -= 1;
					mark ();
				}
			}
			else
			{
				while (col < row)
				{
					col += 1;
					mark ();
				}
				while (row > 0)
				{
					row -= 1;
					mark ();
				}
			}
			n -= 1;
			row = min (row, n - 1);
			col = min (col, n - 1);
		}
		if (cur > 0)
		{
			if (row == 0)
			{
				swap (board[0][col + 1], board[1][col + 1]);
				row = 1;
			}
			else
			{
				swap (board[row + 1][0], board[row + 1][1]);
				col = 1;
			}
		}
		board[0][0..3] = [cur + 6, cur + 8, cur + 4];
		board[1][0..3] = [cur + 3, cur + 2, cur + 1];
		board[2][0..3] = [cur + 7, cur + 5, cur + 9];
		if (col == 1)
		{
			swap (board[0][1], board[1][0]);
			swap (board[0][2], board[2][0]);
			swap (board[1][2], board[2][1]);
		}

		writefln !("%(%(%s %)\n%)") (board);
	}
}


You are managing a mobile phone network, and want to offer competitive prices to connect a network.The network has $$$n$$$ nodes.Your competitor has already offered some connections between some nodes, with some fixed prices. These connections are bidirectional. There are initially $$$m$$$ connections the competitor is offering. The $$$i$$$-th connection your competitor is offering will connect nodes $$$fa_i$$$ and $$$fb_i$$$ and costs $$$fw_i$$$. You have a list of $$$k$$$ connections that you want to offer. It is guaranteed that this set of connection does not form any cycle. The $$$j$$$-th of these connections will connect nodes $$$ga_j$$$ and $$$gb_j$$$. These connections are also bidirectional. The cost of these connections have not been decided yet.You can set the prices of these connections to any arbitrary integer value. These prices are set independently for each connection. After setting the prices, the customer will choose such $$$n - 1$$$ connections that all nodes are connected in a single network and the total cost of chosen connections is minimum possible. If there are multiple ways to choose such networks, the customer will choose an arbitrary one that also maximizes the number of your connections in it.You want to set prices in such a way such that all your $$$k$$$ connections are chosen by the customer, and the sum of prices of your connections is maximized.Print the maximum profit you can achieve, or $$$-1$$$ if it is unbounded.

The first line of input will contain three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \leq n, k, m \leq 5 \cdot 10^5, k \leq n-1$$$), the number of nodes, the number of your connections, and the number of competitor connections, respectively. The next $$$k$$$ lines contain two integers $$$ga_i$$$ and $$$gb_i$$$ ($$$1 \leq ga_i, gb_i \leq n$$$, $$$ga_i \not= gb_i$$$), representing one of your connections between nodes $$$ga_i$$$ and $$$gb_i$$$. Your set of connections is guaranteed to be acyclic. The next $$$m$$$ lines contain three integers each, $$$fa_i$$$, $$$fb_i$$$ and $$$fw_i$$$ ($$$1 \leq fa_i, fb_i \leq n$$$, $$$fa_i \not= fb_i$$$, $$$1 \leq fw_i \leq 10^9$$$), denoting one of your competitor's connections between nodes $$$fa_i$$$ and $$$fb_i$$$ with cost $$$fw_i$$$. None of these connections connects a node to itself, and no pair of these connections connect the same pair of nodes. In addition, these connections are given by non-decreasing order of cost (that is, $$$fw_{i-1} \leq fw_i$$$ for all valid $$$i$$$). Note that there may be some connections that appear in both your set and your competitor's set (though no connection will appear twice in one of this sets). It is guaranteed that the union of all of your connections and your competitor's connections form a connected network.

Print a single integer, the maximum possible profit you can achieve if you set the prices on your connections appropriately. If the profit is unbounded, print $$$-1$$$.

NoteIn the first sample, it's optimal to give connection $$$1-3$$$ cost $$$3$$$, connection $$$1-2$$$ cost $$$3$$$, and connection $$$3-4$$$ cost $$$8$$$. In this case, the cheapest connected network has cost $$$14$$$, and the customer will choose one that chooses all of your connections.In the second sample, as long as your first connection costs $$$30$$$ or less, the customer chooses both your connections no matter what is the cost of the second connection, so you can get unbounded profit in this case.

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.numeric, std.regex, std.typecons;
import core.bitop;

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

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

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

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

class Heap(T) {
  Heap l, r;
  T val;
  this () {}
  this (T val) { this.val = val; }
}
Heap!T merge(T)(Heap!T a, Heap!T b) {
  if (!a) return b;
  if (!b) return a;
  if (a.val > b.val) swap(a, b);
  a.r = merge(a.r, b);
  swap(a.l, a.r);
  return a;
}
void pop(T)(ref Heap!T a) {
  a = merge(a.l, a.r);
}

enum E = 21;

int N, K, M;
int[] GA, GB;
int[] FA, FB;
long[] FW;

int[][] graph;
int[] dep;
int[][] par;
Tuple!(int, int)[][] inss;
int[] anss;

void dfs(int u, int p) {
  dep[u] = (p == u) ? 0 : (dep[p] + 1);
  par[0][u] = p;
  foreach (k; graph[u]) {
    const v = (k < K) ? (GA[k] ^ GB[k] ^ u) : (FA[k - K] ^ FB[k - K] ^ u);
    if (v != p) {
      dfs(v, u);
    }
  }
}

int lca(int u, int v) {
  foreach_reverse (e; 0 .. E) {
    if (dep[u] - (1 << e) >= dep[v]) {
      u = par[e][u];
    }
    if (dep[v] - (1 << e) >= dep[u]) {
      v = par[e][v];
    }
  }
  foreach_reverse (e; 0 .. E) {
    if (par[e][u] != par[e][v]) {
      u = par[e][u];
      v = par[e][v];
    }
  }
  if (u != v) {
    u = par[0][u];
    v = par[0][v];
  }
  return u;
}

Heap!(Tuple!(int, int)) solve(int u, int p) {
  Heap!(Tuple!(int, int)) ret;
  foreach (k; graph[u]) {
    const v = (k < K) ? (GA[k] ^ GB[k] ^ u) : (FA[k - K] ^ FB[k - K] ^ u);
    if (v != p) {
      auto res = solve(v, u);
      for (; res && dep[res.val[1]] >= dep[v]; res.pop) {}
      if (k < K) {
        anss[k] = res ? res.val[0] : -1;
      }
      ret = ret.merge(res);
    }
  }
  foreach (m; inss[u]) {
    ret = ret.merge(new Heap!(Tuple!(int, int))(m));
  }
  return ret;
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      K = readInt();
      M = readInt();
      GA = new int[K];
      GB = new int[K];
      foreach (k; 0 .. K) {
        GA[k] = readInt() - 1;
        GB[k] = readInt() - 1;
      }
      FA = new int[M];
      FB = new int[M];
      FW = new long[M];
      foreach (m; 0 .. M) {
        FA[m] = readInt() - 1;
        FB[m] = readInt() - 1;
        FW[m] = readLong();
      }

      auto uf = new int[N];
      uf[] = -1;
      graph = new int[][N];
      foreach (k; 0 .. K) {
        uf.connect(GA[k], GB[k]);
        graph[GA[k]] ~= k;
        graph[GB[k]] ~= k;
      }
      foreach (m; 0 .. M) {
        if (uf.connect(FA[m], FB[m])) {
          graph[FA[m]] ~= K + m;
          graph[FB[m]] ~= K + m;
        }
      }

      dep = new int[N];
      par = new int[][](E, N);
      dep[] = -1;
      foreach (u; 0 .. N) {
        if (dep[u] == -1) {
          dfs(u, u);
        }
      }
      foreach (e; 0 .. E - 1) {
        foreach (u; 0 .. N) {
          par[e + 1][u] = par[e][par[e][u]];
        }
      }
      debug {
        writeln("par[0] = ", par[0]);
      }

      inss = new Tuple!(int, int)[][N];
      foreach (m; 0 .. M) {
        int l = lca(FA[m], FB[m]);
        if (FA[m] != l) {
          inss[FA[m]] ~= tuple(m, l);
        }
        if (FB[m] != l) {
          inss[FB[m]] ~= tuple(m, l);
        }
      }
      debug {
        writeln("inss = ", inss);
      }
      anss = new int[K];
      anss[] = -1;
      foreach (u; 0 .. N) {
        if (par[0][u] == u) {
          solve(u, u);
        }
      }
      debug {
        writeln("anss = ", anss);
      }

      long ans;
      foreach (k; 0 .. K) {
        if (anss[k] == -1) {
          ans = -1;
          break;
        } else {
          ans += FW[anss[k]];
        }
      }
      writeln(ans);
    }
  } 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.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 E = 21;

int N, K, M;
int[] GA, GB;
int[] FA, FB;
long[] FW;

int[][] graph;
int[] dep;
int[][] par;
int[][] inss, rems;
int[] anss;

void dfs(int u, int p) {
  dep[u] = (p == u) ? 0 : (dep[p] + 1);
  par[0][u] = p;
  foreach (k; graph[u]) {
    const v = GA[k] ^ GB[k] ^ u;
    if (v != p) {
      dfs(v, u);
    }
  }
}

int lca(int u, int v) {
  foreach_reverse (e; 0 .. E) {
    if (dep[u] - (1 << e) >= dep[v]) {
      u = par[e][u];
    }
    if (dep[v] - (1 << e) >= dep[u]) {
      v = par[e][v];
    }
  }
  foreach_reverse (e; 0 .. E) {
    if (par[e][u] != par[e][v]) {
      u = par[e][u];
      v = par[e][v];
    }
  }
  if (u != v) {
    u = par[0][u];
    v = par[0][v];
  }
  return u;
}

alias Set = RedBlackTree!(int, "a < b", true);
Set solve(int u, int p) {
  Set ret = new Set;
  foreach (k; graph[u]) {
    const v = GA[k] ^ GB[k] ^ u;
    if (v != p) {
      Set res = solve(v, u);
      debug {
        writefln("%s -> %s: %s", u, v, res);
      }
      anss[k] = res.empty ? -1 : res.front;
      if (ret.length < res.length) {
        swap(ret, res);
      }
      foreach (m; res) {
        ret.insert(m);
      }
    }
  }
  foreach (m; rems[u]) {
    ret.removeKey(m);
  }
  foreach (m; inss[u]) {
    ret.insert(m);
  }
  return ret;
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      K = readInt();
      M = readInt();
      GA = new int[K];
      GB = new int[K];
      foreach (k; 0 .. K) {
        GA[k] = readInt() - 1;
        GB[k] = readInt() - 1;
      }
      FA = new int[M];
      FB = new int[M];
      FW = new long[M];
      foreach (m; 0 .. M) {
        FA[m] = readInt() - 1;
        FB[m] = readInt() - 1;
        FW[m] = readLong();
      }

      graph = new int[][N];
      foreach (k; 0 .. K) {
        graph[GA[k]] ~= k;
        graph[GB[k]] ~= k;
      }
      dep = new int[N];
      par = new int[][](E, N);
      dep[] = -1;
      foreach (u; 0 .. N) {
        if (dep[u] == -1) {
          dfs(u, u);
        }
      }
      foreach (e; 0 .. E - 1) {
        foreach (u; 0 .. N) {
          par[e + 1][u] = par[e][par[e][u]];
        }
      }
      debug {
        writeln("par[0] = ", par[0]);
      }

      inss = new int[][N];
      rems = new int[][N];
      foreach (m; 0 .. M) {
        const u = FA[m], v = FB[m];
        const l = lca(u, v);
        if (u != l) {
          inss[u] ~= m;
          rems[l] ~= m;
        }
        if (v != l) {
          inss[v] ~= m;
          rems[l] ~= m;
        }
      }
      debug {
        writeln("inss = ", inss);
        writeln("rems = ", rems);
      }
      anss = new int[K];
      anss[] = -1;
      foreach (u; 0 .. N) {
        if (par[0][u] == u) {
          solve(u, u);
        }
      }
      debug {
        writeln("anss = ", anss);
      }

      long ans;
      foreach (k; 0 .. K) {
        if (anss[k] == -1) {
          ans = -1;
          break;
        } else {
          ans += FW[anss[k]];
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

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

immutable int mod = 10^^9 + 7;

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

    auto x = new int[](n);
    auto y = new int[](n);

    foreach(i ; 0 .. n){
        readVars(x[i], y[i]);
    }

    auto visited = new bool[](n);

    int ans;

    foreach(i ; 0 .. n){
        if(!visited[i]){
            dfs(n, x, y, visited, i);
            ans++;
        }
    }

    writeln(ans - 1);
}

void dfs(int n, int[] x, int[] y, bool[] visited, int i) {
    visited[i] = true;

    foreach(j ; 0 .. n){
        if((x[j] == x[i] || y[j] == y[i]) && !visited[j]){
            dfs(n, x, y, visited, j);
        }
    }
}

void readVars(T...)(auto ref T args){
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

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

immutable int mod = 10^^9 + 7;

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

    auto x = new int[](n);
    auto y = new int[](n);

    foreach(i ; 0 .. n){
        readVars(x[i], y[i]);
    }

    int ans;

    foreach(i ; 1 .. n){
        bool flag = true;

        foreach(j ; 0 .. i){
            if (x[j] == x[i] || y[j] == y[i]) {
                flag = false;
                break;
            }
        }

        ans += flag;
    }

    writeln(ans);
}

void readVars(T...)(auto ref T args){
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Let's denote monotonic renumeration of array $$$a$$$ as an array $$$b$$$ consisting of $$$n$$$ integers such that all of the following conditions are met:  $$$b_1 = 0$$$;  for every pair of indices $$$i$$$ and $$$j$$$ such that $$$1 \le i, j \le n$$$, if $$$a_i = a_j$$$, then $$$b_i = b_j$$$ (note that if $$$a_i \ne a_j$$$, it is still possible that $$$b_i = b_j$$$);  for every index $$$i \in [1, n - 1]$$$ either $$$b_i = b_{i + 1}$$$ or $$$b_i + 1 = b_{i + 1}$$$. For example, if $$$a = [1, 2, 1, 2, 3]$$$, then two possible monotonic renumerations of $$$a$$$ are $$$b = [0, 0, 0, 0, 0]$$$ and $$$b = [0, 0, 0, 0, 1]$$$.Your task is to calculate the number of different monotonic renumerations of $$$a$$$. The answer may be large, so print it modulo $$$998244353$$$.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print one integer — the number of different monotonic renumerations of $$$a$$$, taken modulo $$$998244353$$$.

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

immutable int INF = 10L ^^ 9 + 23;
immutable int MD = 998244353;

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

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

    int [int] mxr;

    foreach (i, e; arr) { mxr[e] = i.to!int; }

    int ans = 1;
    int curr = mxr[arr[0]];
    foreach (i, e; arr) {
        if (curr < i) { ans = ans * 2 % MD; }

        curr = max(curr, mxr[e]);
    }

    ans.writeln;
}


There are $$$n$$$ piles of stones, where the $$$i$$$-th pile has $$$a_i$$$ stones. Two people play a game, where they take alternating turns removing stones.In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who cannot make a move (because all piles are empty) loses the game. If both players play optimally, determine the winner of the game.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$)  — the number of piles. The second line of each test case contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$)  — $$$a_i$$$ is equal to the number of stones in the $$$i$$$-th pile. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.

For each test case, if the player who makes the first move will win, output "First". Otherwise, output "Second".

First
Second
Second
First
First
Second
First

NoteIn the first test case, the first player will win the game. His winning strategy is:   The first player should take the stones from the first pile. He will take $$$1$$$ stone. The numbers of stones in piles will be $$$[1, 5, 4]$$$.  The second player should take the stones from the first pile. He will take $$$1$$$ stone because he can't take any other number of stones. The numbers of stones in piles will be $$$[0, 5, 4]$$$.  The first player should take the stones from the second pile because the first pile is empty. He will take $$$4$$$ stones. The numbers of stones in piles will be $$$[0, 1, 4]$$$.  The second player should take the stones from the second pile because the first pile is empty. He will take $$$1$$$ stone because he can't take any other number of stones. The numbers of stones in piles will be $$$[0, 0, 4]$$$.  The first player should take the stones from the third pile because the first and second piles are empty. He will take $$$4$$$ stones. The numbers of stones in piles will be $$$[0, 0, 0]$$$.  The second player will lose the game because all piles will be empty.

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 p = readln.splitter.countUntil !(q{a != "1"});
		writeln (((p < 0 ? ~n : p) & 1) ? "Second" : "First");
	}
}

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

void main() {
	long tt = readln().chomp.to!long;
	foreach (t; 0 .. tt) {
		readln();
		long[] piles = readln().chomp.split(" ").map!(to!long).array;
		bool winner = true;
		bool didBreak = false;
		foreach (i; piles) {
			if (i == 1) {
				winner = !winner;
			}
			else {
				didBreak = true;
				break;
			}
		}
		if (!didBreak) {
			winner = !winner;
		}
		writeln(winner ? "First" : "Second");
	}
}


Thanos sort is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process.Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort?*Infinity Gauntlet required.

The first line of input contains a single number $$$n$$$ ($$$1 \le n \le 16$$$) — the size of the array. $$$n$$$ is guaranteed to be a power of 2. The second line of input contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$1 \le a_i \le 100$$$) — the elements of the array.

Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order.

NoteIn the first example the array is already sorted, so no finger snaps are required.In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array.In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction.

// This file is a "Hello, world!" in D language by DMD for wandbox.
import std.stdio;
import std.bigint;
import std.conv;
import std.string;
import std.algorithm;

ulong dfs(int[] arr)
{
	bool flag = true;
	int prev = -1;
	foreach (v; arr)
	{
		flag &= prev <= v;
		prev = v;
	}
	if (flag)
	{
		return arr.length;
	}
	else
	{
		return max(arr[0..$/2].dfs, arr[$/2..$].dfs);
	}
}

void main()
{
	int n = readln.chomp.to!int;
	int[] arr = readln.chomp.split.to!(int[]);
	arr.dfs.writeln;
}

// DMD reference:
//   https://dlang.org/dmd-linux.html

// D language references:
//   https://dlang.org
//   http://www.kmonos.net/alang/d/ ( Japanese p

import std.conv, std.functional, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.container, std.math, std.numeric, std.range, 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;
int[] A;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      A = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt();
      }
      int ans;
      for (int k = 1; k <= N; k <<= 1) {
        for (int i = 0; i < N; i += k) {
          debug {
            writeln(k, " ", i, " ", A[i .. i + k]);
          }
          bool ok = true;
          foreach (j; i + 1 .. i + k) {
            ok = ok && (A[j - 1] <= A[j]);
          }
          if (ok) {
            chmax(ans, k);
          }
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his string — each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2·ai ≤ |s|.You face the following task: determine what Pasha's string will look like after m days.

The first line of the input contains Pasha's string s of length from 2 to 2·105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≤ m ≤ 105) —  the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1 ≤ ai; 2·ai ≤ |s|) — the position from which Pasha started transforming the string on the i-th day.

In the first line of the output print what Pasha's string s will look like after m days.

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

void main() {
	auto s = cast(char[])readln.strip;
	readln;

	uint n = cast(uint)s.length;

    auto r = readln.strip
				.splitter(' ')
				.map!(a => a.to!uint - 1).array;

	r.sort!((a, b) => a < b);
	auto ss = r.assumeSorted;

	bool swap;

    foreach(i, c; s) {
    	auto d = s.length - i - 1;
        auto j = i > s.length / 2 ? d + 1 : i;

    	swap ^= !!(ss.equalRange(j).length % 2);

		if(swap) s[d].write;
		else c.write;
    }
}

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

void main() {
	auto s = cast(char[])readln.strip;
	readln;

	uint n = cast(uint)s.length;

    auto r = readln.strip
				.splitter(' ')
				.map!(a => a.to!uint - 1).array;

	r.sort!((a, b) => a < b);

	auto cnt = (uint c) => r.count!(a => c >= a && c < n - a + 2);

    foreach(i, c; s) {
		if(cnt(cast(uint)i) % 2) s[$ - i - 1].write;
		else c.write;
    }
}


Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?

First line of input contains an integer n (2 ≤ n ≤ 105), the number of players. The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109) — the bids of players.

Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.

NoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal.

import std.stdio, std.string;

void solve(int[] a)
{
    auto n = cast(int)a.length;
    foreach (i; 0 .. n)
    {
        while (a[i] % 2 == 0)
        {
            a[i] >>= 1;
        }
        while (a[i] % 3 == 0)
        {
            a[i] /= 3;
        }
        if (i > 0 && a[i] != a[i - 1])
        {
            writeln("No");
            return;
        }
    }
    writeln("Yes");
}

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

import std.algorithm;
import std.conv;
import std.math;
import std.numeric;
import std.random;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto a = readln.split.map !(to !(int)).array;
		foreach (k; 2..4)
		{
			foreach (i; 0..n)
			{
				while (a[i] % k == 0)
				{
					a[i] /= k;
				}
			}
		}
		writeln (a.all !(x => x == a[0]) ? "Yes" : "No");
	}
}


As the boat drifts down the river, a wood full of blossoms shows up on the riverfront."I've been here once," Mino exclaims with delight, "it's breathtakingly amazing.""What is it like?""Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses.The wood can be represented by a rectangular grid of $$$n$$$ rows and $$$m$$$ columns. In each cell of the grid, there is exactly one type of flowers.According to Mino, the numbers of connected components formed by each kind of flowers are $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers.You are to help Kanno depict such a grid of flowers, with $$$n$$$ and $$$m$$$ arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem.Note that you can choose arbitrary $$$n$$$ and $$$m$$$ under the constraints below, they are not given in the input.

The first and only line of input contains four space-separated integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$1 \leq a, b, c, d \leq 100$$$) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively.

In the first line, output two space-separated integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 50$$$) — the number of rows and the number of columns in the grid respectively. Then output $$$n$$$ lines each consisting of $$$m$$$ consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively. In case there are multiple solutions, print any. You can output each letter in either case (upper or lower).

7 7
DDDDDDD
DDDBDBD
DDCDCDD
DBDADBD
DDCDCDD
DBDBDDD
DDDDDDD

NoteIn the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one.

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

immutable long MOD = 10^^9+7;

void main() {
    auto s = readln.split.map!(to!int);
    auto A = s[0];
    auto B = s[1];
    auto C = s[2];
    auto D = s[3];
    --A, --B, --C, --D;

    const int H = 50;
    const int W = 50;
    auto ans = new int[][](H, W);

    foreach (i; 0..H)
        foreach (j; 0..W) {
            if (i < H/2 && j < W/2)
                ans[i][j] = 1;
            else if (i < H/2 && j >= W/2)
                ans[i][j] = 2;
            else if (i >= H/2 && j < W/2)
                ans[i][j] = 3;
            else
                ans[i][j] = 4;
        }

    for (int i = 0; i < H/2-1; i += 2) {
        for (int j = 0; j < W/2-1; ++j) {
            if (j % 3 == 0 && B > 0)
                ans[i][j] = 2, --B;
            else if (j % 3 == 1 && C > 0)
                ans[i][j] = 3, --C;
            else if (j % 3 == 2 && D > 0)
                ans[i][j] = 4, --D;
        }
    }

    for (int i = 0; i < H/2-1; i += 2) {
        for (int j = W/2+1; j < W; ++j) {
            if (j % 3 == 0 && A > 0)
                ans[i][j] = 1, --A;
            else if (j % 3 == 1 && C > 0)
                ans[i][j] = 3, --C;
            else if (j % 3 == 2 && D > 0)
                ans[i][j] = 4, --D;
        }
    }

    for (int i = H/2+1; i < H; i += 2) {
        for (int j = 0; j < W/2-1; ++j) {
            if (j % 3 == 0 && A > 0)
                ans[i][j] = 1, --A;
            else if (j % 3 == 1 && B > 0)
                ans[i][j] = 2, --B;
            else if (j % 3 == 2 && D > 0)
                ans[i][j] = 4, --D;
        }
    }

    for (int i = H/2+1; i < H; i += 2) {
        for (int j = W/2+1; j < W; ++j) {
            if (j % 3 == 0 && A > 0)
                ans[i][j] = 1, --A;
            else if (j % 3 == 1 && B > 0)
                ans[i][j] = 2, --B;
            else if (j % 3 == 2 && C > 0)
                ans[i][j] = 3, --C;
        }
    }

    writeln(H, " ", W);
    ans.map!(a => a.map!(b => ('A' + b - 1).to!char)).each!writeln;
}

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

void main()
{
    auto v = readln.chomp.split.map!(to!int).array;

    char[50][44] ans;
    debug { ans.length.writeln; }

    foreach (ref e; v) e -= 1;
    debug { v.writeln; }

    auto clrs = ['a', 'b', 'c', 'd'];

    foreach (i; 0..44) ans[i].fill(clrs[i / 11]);

    void go(char c, int x, int st) {
        if (x == 0) return;

        outer: foreach (ref r; ans[st..st+11].dropOne.dropBackOne.stride(2)) {
            foreach (ref p; r.length.iota.dropOne.dropBackOne.stride(2)) {
                r[p] = c;
                --x;
                if (x == 0) {
                    debug { r.writeln; }
                    break outer;
                }
            }
        }
    }

    foreach (i; (44).iota.stride(11)) {
        auto nxt = ((i/11) + 1) % 4;
        debug { i.writeln; nxt.writeln; clrs[nxt].writeln; }
        go(clrs[nxt], v[nxt], i);
    }

    writeln(ans.length, ' ', ans[0].length);
    ans.each!writeln;
}


Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.

The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers.

Print the number of operations needed to destroy all towers.

NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color.    After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation.

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.string;
import std.range;
import std.range.primitives;
import std.conv;

int main() {
    debug stdin = File("in.txt", "r");

    int[100_000] arr, ht;
    int n;
    int curht = 0, maxht = 0;
    readf(" %s\n", &n);
    foreach ( i ; 0 .. n ) {
        readf(" %s", &arr[i]);
        if (arr[i] > curht) {
            ++curht;
            if (curht > maxht) maxht = curht;
        }
        else curht = arr[i];
        ht[i] = curht;
    }
    curht = 0;
    foreach_reverse ( i ; 0 .. n ) {
        if (arr[i] > curht) {
            ++curht;
            if (curht > maxht) maxht = curht;
        }
        else curht = arr[i];
        int joinht = min(curht, ht[i]) * 2;
        if (joinht > maxht) maxht = joinht;
    }
    ++maxht;
    maxht /= 2;
    writeln(maxht);

    return 0;
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.string;
import std.range;
import std.range.primitives;
import std.conv;

int main() {
    debug stdin = File("in.txt", "r");

    int[100_000] arr, ht;
    int n;
    int curht = 0, maxht = 0;
    readf(" %s\n", &n);
    foreach ( i ; 0 .. n ) {
        readf(" %s", &arr[i]);
        if (arr[i] > curht) ++curht;
        else curht = arr[i];
        ht[i] = curht;
    }
    curht = 0;
    foreach_reverse ( i ; 0 .. n ) {
        if (arr[i] > curht) ++curht;
        else curht = arr[i];
        int joinht = min(curht, ht[i]);
        if (joinht > maxht) maxht = joinht;
    }
    writeln(maxht);

    return 0;
}

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

immutable int INF = 10L ^^ 9 + 23;

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

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

    auto d = new int[](n);
    d.fill(INF);

    void go(int[] h, int[] d) {
        int cur = 1;
        foreach (i, e; h) {
            cur = min(cur, e);
            d[i] = min(cur, d[i]);
            cur += 1;
        }
    }

    go(h, d);

    h.reverse();
    d.reverse();
    go(h, d);

    int ans = d.maxElement;
    ans.writeln;
}

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

immutable long INF = 10L ^^ 18 + 23;

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

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

    auto d = new int[](n);
    int cur = 1;
    foreach (i, e; h) {
        cur = min(cur, e);
        d[i] = cur;
        cur += 1;
    }

    cur = 1;
    foreach_reverse (i, e; h) {
        cur = min(cur, e);
        d[i] = min(d[i], cur);
        cur += 1;
    }

    int ans = d.maxElement;
    ans.writeln;
}

import std.algorithm;
import std.conv;
import std.math;
import std.numeric;
import std.random;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto a = readln.split.map !(to !(int)).array;
		auto lo = new int [n];
		lo.front = 1;
		foreach (i; 1..n)
		{
			lo[i] = min (lo[i - 1] + 1, a[i]);
		}

		auto hi = new int [n];
		hi.back = 1;
		foreach_reverse (i; 0..n - 1)
		{
			hi[i] = min (hi[i + 1] + 1, a[i]);
		}

		int res = 0;
		foreach (i; 0..n)
		{
			res = max (res, min (lo[i], hi[i]));
		}

		writeln (res);
	}
}


Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point $$$T$$$, which coordinates to be found out.Bob travelled around the world and collected clues of the treasure location at $$$n$$$ obelisks. These clues were in an ancient language, and he has only decrypted them at home. Since he does not know which clue belongs to which obelisk, finding the treasure might pose a challenge. Can you help him?As everyone knows, the world is a two-dimensional plane. The $$$i$$$-th obelisk is at integer coordinates $$$(x_i, y_i)$$$. The $$$j$$$-th clue consists of $$$2$$$ integers $$$(a_j, b_j)$$$ and belongs to the obelisk $$$p_j$$$, where $$$p$$$ is some (unknown) permutation on $$$n$$$ elements. It means that the treasure is located at $$$T=(x_{p_j} + a_j, y_{p_j} + b_j)$$$. This point $$$T$$$ is the same for all clues.In other words, each clue belongs to exactly one of the obelisks, and each obelisk has exactly one clue that belongs to it. A clue represents the vector from the obelisk to the treasure. The clues must be distributed among the obelisks in such a way that they all point to the same position of the treasure.Your task is to find the coordinates of the treasure. If there are multiple solutions, you may print any of them.Note that you don't need to find the permutation. Permutations are used only in order to explain the problem.

The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the number of obelisks, that is also equal to the number of clues. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^6 \leq x_i, y_i \leq 10^6$$$) — the coordinates of the $$$i$$$-th obelisk. All coordinates are distinct, that is $$$x_i \neq x_j$$$ or $$$y_i \neq y_j$$$ will be satisfied for every $$$(i, j)$$$ such that $$$i \neq j$$$.  Each of the next $$$n$$$ lines contains two integers $$$a_i$$$, $$$b_i$$$ ($$$-2 \cdot 10^6 \leq a_i, b_i \leq 2 \cdot 10^6$$$) — the direction of the $$$i$$$-th clue. All coordinates are distinct, that is $$$a_i \neq a_j$$$ or $$$b_i \neq b_j$$$ will be satisfied for every $$$(i, j)$$$ such that $$$i \neq j$$$.  It is guaranteed that there exists a permutation $$$p$$$, such that for all $$$i,j$$$ it holds $$$\left(x_{p_i} + a_i, y_{p_i} + b_i\right) = \left(x_{p_j} + a_j, y_{p_j} + b_j\right)$$$.

Output a single line containing two integers $$$T_x, T_y$$$ — the coordinates of the treasure. If there are multiple answers, you may print any of them.

NoteAs $$$n = 2$$$, we can consider all permutations on two elements. If $$$p = [1, 2]$$$, then the obelisk $$$(2, 5)$$$ holds the clue $$$(7, -2)$$$, which means that the treasure is hidden at $$$(9, 3)$$$. The second obelisk $$$(-6, 4)$$$ would give the clue $$$(-1,-3)$$$ and the treasure at $$$(-7, 1)$$$. However, both obelisks must give the same location, hence this is clearly not the correct permutation.If the hidden permutation is $$$[2, 1]$$$, then the first clue belongs to the second obelisk and the second clue belongs to the first obelisk. Hence $$$(-6, 4) + (7, -2) = (2,5) + (-1,-3) = (1, 2)$$$, so $$$T = (1,2)$$$ is the location of the treasure.  In the second sample, the hidden permutation is $$$[2, 3, 4, 1]$$$.

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

void main() {
    auto N = readln.chomp.to!int;
    auto X = new long[](N);
    auto Y = new long[](N);
    auto A = new long[](N);
    auto B = new long[](N);
    foreach (i; 0..N) {
        auto s = readln.split.map!(to!long);
        X[i] = s[0];
        Y[i] = s[1];
    }
    foreach (i; 0..N) {
        auto s = readln.split.map!(to!long);
        A[i] = s[0];
        B[i] = s[1];
    }

    long[long][long] mp;
    foreach (i; 0..N) {
        foreach (j; 0..N) {
            long x = X[i] + A[j];
            long y = Y[i] + B[j];
            mp[x][y] += 1;
        }
    }

    foreach (x; mp.keys) {
        foreach (y; mp[x].keys) {
            if (mp[x][y] == N) {
                writeln(x, " ", y);
                return;
            }
        }
    }
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		long x = 0;
		long y = 0;
		foreach (i; 0..n * 2)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			x += u;
			y += v;
		}
		writeln (x / n, " ", y / n);
	}
}

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

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

void main() {
    int n;
    scan(n);

    auto xys = new Point[](n);
    auto abs = new Point[](n);

    foreach (i ; 0 .. n) {
        int x, y;
        scan(x, y);
        xys[i] = Point(x, y);
    }

    foreach (i ; 0 .. n) {
        int a, b;
        scan(a, b);
        abs[i] = Point(a, b);
    }

    int[Point] cnt;

    foreach (i ; 0 .. n) {
        foreach (j ; 0 .. n) {
            int xx = xys[i].x + abs[j].x;
            int yy = xys[i].y + abs[j].y;

            cnt[Point(xx, yy)]++;

            if (cnt[Point(xx, yy)] == n) {
                writefln("%d %d", xx, yy);
                return;
            }
        }
    }

}

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

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

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

  int n;
  rd(n);
  struct P {
    int y, x;
  }

  auto xs = new int[](n), ys = new int[](n);
  bool[P] seen;
  foreach (i; 0 .. n) {
    rd(xs[i], ys[i]);
    if (i > 0) {
      seen[P(xs[i], ys[i])] = true;
    }
  }
  auto vy = new int[](n), vx = new int[](n);
  foreach (i; 0 .. n) {
    rd(vx[i], vy[i]);
  }
  foreach (i; 0 .. n) {
    auto tx = xs[0] + vx[i], ty = ys[0] + vy[i];
    foreach (j; 0 .. n) {
      if (i != j) {
        auto p = P(tx - vx[j], ty - vy[j]);
        if ((p in seen) == null || !seen[p]) {
          goto hell;
        }
        seen[p] = false;
      }
    }
    writeln(tx, " ", ty);
    return;
  hell:
    // revert
    foreach (j; 1 .. n) {
      seen[P(xs[j], ys[j])] = true;
    }
  }
  import std.exception : enforce;

  enforce(false);
}

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

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