This is the easy 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 $$$3nm$$$ 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 3nm$$$) — 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 into 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;
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) {
  }
}

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)
				{
					writeln(s);
					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.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)
			{
				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];
							}
						}
						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+1, 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]);
				}
			}
		}
	}

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

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 (row; 0..rows)
		{
			foreach (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;
						}
						if (row2 == row && col2 == col)
						{
							assert (false);
						}
						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 = seqRow[1..$] ~ seqRow[0];
					seqCol = seqCol[1..$] ~ seqCol[0];
				}
				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 == rows - 1 ||
						    col2 == cols - 1)
						{
							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 = seqRow[1..$] ~ seqRow[0];
					seqCol = seqCol[1..$] ~ seqCol[0];
				}
				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}));
		}
	}
}


Everyone knows that DNA strands consist of nucleotides. There are four types of nucleotides: "A", "T", "G", "C". A DNA strand is a sequence of nucleotides. Scientists decided to track evolution of a rare species, which DNA strand was string s initially. Evolution of the species is described as a sequence of changes in the DNA. Every change is a change of some nucleotide, for example, the following change can happen in DNA strand "AAGC": the second nucleotide can change to "T" so that the resulting DNA strand is "ATGC".Scientists know that some segments of the DNA strand can be affected by some unknown infections. They can represent an infection as a sequence of nucleotides. Scientists are interested if there are any changes caused by some infections. Thus they sometimes want to know the value of impact of some infection to some segment of the DNA. This value is computed as follows:  Let the infection be represented as a string e, and let scientists be interested in DNA strand segment starting from position l to position r, inclusive.  Prefix of the string eee... (i.e. the string that consists of infinitely many repeats of string e) is written under the string s from position l to position r, inclusive.  The value of impact is the number of positions where letter of string s coincided with the letter written under it. Being a developer, Innokenty is interested in bioinformatics also, so the scientists asked him for help. Innokenty is busy preparing VK Cup, so he decided to delegate the problem to the competitors. Help the scientists!

The first line contains the string s (1 ≤ |s| ≤ 105) that describes the initial DNA strand. It consists only of capital English letters "A", "T", "G" and "C". The next line contains single integer q (1 ≤ q ≤ 105) — the number of events. After that, q lines follow, each describes one event. Each of the lines has one of two formats:    1 x c, where x is an integer (1 ≤ x ≤ |s|), and c is a letter "A", "T", "G" or "C", which means that there is a change in the DNA: the nucleotide at position x is now c.  2 l r e, where l, r are integers (1 ≤ l ≤ r ≤ |s|), and e is a string of letters "A", "T", "G" and "C" (1 ≤ |e| ≤ 10), which means that scientists are interested in the value of impact of infection e to the segment of DNA strand from position l to position r, inclusive.

For each scientists' query (second type query) print a single integer in a new line — the value of impact of the infection on the DNA.

ATGCATGC
4
2 1 8 ATGC
2 2 6 TTT
1 4 T
2 2 6 TA

GAGTTGTTAA
6
2 3 4 TATGGTG
1 1 T
1 6 G
2 5 9 AGTAATA
1 10 G
2 2 6 TTGT

NoteConsider the first example. In the first query of second type all characters coincide, so the answer is 8. In the second query we compare string "TTTTT..." and the substring "TGCAT". There are two matches. In the third query, after the DNA change, we compare string "TATAT..."' with substring "TGTAT". There are 4 matches.

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

// floor(a / b)
Int divFloor(Int)(Int a, Int b) {
  return a / b - (((a ^ b) < 0 && a % b != 0) ? 1 : 0);
}

// ceil(a / b)
Int divCeil(Int)(Int a, Int b) {
  return a / b + (((a ^ b) > 0 && a % b != 0) ? 1 : 0);
}

void bAdd(T)(T[] bit, int pos, T val)
in {
  assert(0 <= pos && pos < bit.length, "bAdd: 0 <= pos < |bit| must hold");
}
do {
  for (int x = pos; x < bit.length; x |= x + 1) {
    bit[x] += val;
  }
}

// sum of [0, pos)
T bSum(T)(T[] bit, int pos)
in {
  assert(0 <= pos && pos <= bit.length, "bSum: 0 <= pos <= |bit| must hold");
}
do {
  T ret = 0;
  for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) {
    ret += bit[x];
  }
  return ret;
}

enum M = 11;
enum A = 4;

int[] readDNA() {
  return readToken().map!((dchar c) {
    switch (c) {
      case 'A': return 0;
      case 'C': return 1;
      case 'G': return 2;
      case 'T': return 3;
      default: assert(false);
    }
  }).array;
}

void main() {
  try {
    for (; ; ) {
      const S = readDNA();
      const N = cast(int)(S.length);

      auto ss = S.dup;
      auto bits = new int[][][][M + 1];
      foreach (m; 1 .. M + 1) {
        bits[m] = new int[][][](m, A, (N + m - 1) / m);
        foreach (i; 0 .. N) {
          bits[m][i % m][ss[i]].bAdd(i / m, +1);
        }
      }

      const Q = readInt();
      foreach (q; 0 .. Q) {
        const typ = readInt();
        switch (typ) {
          case 1: {
            const X = readInt() - 1;
            const C = readDNA();
            foreach (m; 1 .. M + 1) {
              bits[m][X % m][ss[X]].bAdd(X / m, -1);
            }
            ss[X] = C[0];
            foreach (m; 1 .. M + 1) {
              bits[m][X % m][ss[X]].bAdd(X / m, +1);
            }
          } break;
          case 2: {
            const L = readInt() - 1;
            const R = readInt();
            const E = readDNA();
            const m = cast(int)(E.length);
            int ans;
            foreach (r; 0 .. m) {
              // L <= m y + r < R
              int j = (r - L) % m;
              if (j < 0) j += m;
              ans -= bits[m][r][E[j]].bSum(divCeil(L - r, m));
              ans += bits[m][r][E[j]].bSum(divCeil(R - r, m));
            }
            writeln(ans);
          } break;
          default: assert(false);
        }
      }
    }
  } catch (EOFException e) {
  }
}


Dmitry has an array of $$$n$$$ non-negative integers $$$a_1, a_2, \dots, a_n$$$.In one operation, Dmitry can choose any index $$$j$$$ ($$$1 \le j \le n$$$) and increase the value of the element $$$a_j$$$ by $$$1$$$. He can choose the same index $$$j$$$ multiple times.For each $$$i$$$ from $$$0$$$ to $$$n$$$, determine whether Dmitry can make the $$$\mathrm{MEX}$$$ of the array equal to exactly $$$i$$$. If it is possible, then determine the minimum number of operations to do it.The $$$\mathrm{MEX}$$$ of the array is equal to the minimum non-negative integer that is not in the array. For example, the $$$\mathrm{MEX}$$$ of the array $$$[3, 1, 0]$$$ is equal to $$$2$$$, and the array $$$[3, 3, 1, 4]$$$ is equal to $$$0$$$.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input.  The descriptions of the test cases follow. The first line of the description of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The second line of the description of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le n$$$) — elements of the array $$$a$$$. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2\cdot10^5$$$.

For each test case, output $$$n + 1$$$ integer — $$$i$$$-th number is equal to the minimum number of operations for which you can make the array $$$\mathrm{MEX}$$$ equal to $$$i$$$ ($$$0 \le i \le n$$$), or -1 if this cannot be done.

NoteIn the first set of example inputs, $$$n=3$$$:  to get $$$\mathrm{MEX}=0$$$, it is enough to perform one increment: $$$a_1$$$++;  to get $$$\mathrm{MEX}=1$$$, it is enough to perform one increment: $$$a_2$$$++;  $$$\mathrm{MEX}=2$$$ for a given array, so there is no need to perform increments;  it is impossible to get $$$\mathrm{MEX}=3$$$ by performing increments.

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

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

enum long INF = 1L<<50;

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

    int[int] m;
    foreach (a; A) {
        m[a] = m.get(a, 0) + 1;
    }

    auto s = new RedBlackTree!(int, "a < b", true)();
    auto f = new long[N + 1];
    for (int k = 0; k < N; k++) {
        if (k in m) {
            foreach (_; 0 .. m[k]) {
                s.insert(k);
            }
        }
        if (s.empty) {
            f[k + 1] = INF;
        } else {
            int sm = s.back;
            f[k + 1] = f[k] + (k - sm);
            s.removeKey(sm);
        }
    }
    auto ans = new long[N + 1];
    for (int k = 0; k <= N; k++) {
        ans[k] = f[k] + m.get(k, 0);
    }
    writefln("%(%s %)", ans.map!(x => x >= INF ? -1 : x).array);
}

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

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    TEST_LOOP: foreach (test_index; 0 .. tests) {
        immutable n = (){ uint n; readf!"%s\n"(n); return n; }();

        immutable vec =
            readln.chomp
            .split(' ')
            .to!(uint[]);

        immutable frec = (){
            uint[uint] ret;
            vec.each!(x => ++ ret[x]);
            return ret.assumeUnique;
        }();

        ulong previousCost;
        immutable(int)[] ans; ans.reserve(n);
        uint[200_000] stack; /* Imagine having a stack in the standard library */
        assert(stack.length >= n);
        size_t top;

        if (0 !in frec) {
            writefln!"0 %(%s %)"(repeat(-1, n));
            continue;
        }

        write(frec[0]);
        previousCost = 0;
        foreach (_; 1 .. frec[0])
            stack[top ++] = 0;

        foreach (i; 1 .. n + 1) {
            if (i !in frec) {
                write(' ', previousCost);
                if (top != 0) {
                    previousCost += i - stack[-- top];
                } else {
                    writefln!" %(%s %)"(repeat(-1, n - i));
                    continue TEST_LOOP;
                }
            } else {
                write(' ', previousCost + frec[i]);
                foreach (_; 1 .. frec[i])
                    stack[top ++] = i;
            }
        }
    }
}
// ""

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

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

enum int INF = 1<<28;

void solve() {
    int N = read!int;
    auto A = readarray!int;
    sort(A);

    int[int] m;
    foreach (a; A) {
        m[a] = m.get(a, 0) + 1;
    }

    auto s = new RedBlackTree!(int, "a < b", true)();
    auto f = new int[N + 1];
    for (int k = 0; k < N; k++) {
        if (k in m) {
            foreach (_; 0 .. m[k]) {
                s.insert(k);
            }
        }
        if (s.empty) {
            f[k + 1] = INF;
        } else {
            int sm = s.back;
            f[k + 1] = f[k] + (k - sm);
            s.removeKey(sm);
        }
    }
    auto ans = new int[N + 1];
    for (int k = 0; k <= N; k++) {
        ans[k] = f[k] + m.get(k, 0);
    }
    writefln("%(%s %)", ans.map!(x => x >= INF ? -1 : x).array);
}

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

import std;

void main () {
    immutable tests = (){ uint t; readf!"%s\n"(t); return t; }();

    TEST_LOOP: foreach (test_index; 0 .. tests) {
        immutable n = (){ uint n; readf!"%s\n"(n); return n; }();

        immutable vec =
            readln.chomp
            .split(' ')
            .to!(uint[]);

        immutable frec = (){
            uint[uint] ret;
            vec.each!(x => ++ ret[x]);
            return ret.assumeUnique;
        }();

        uint previousCost;
        immutable(int)[] ans; ans.reserve(n);
        uint[200_000] stack; /* Imagine having a stack in the standard library */
        assert(stack.length >= n);
        size_t top;

        if (0 !in frec) {
            writefln!"0 %(%s %)"(repeat(-1, n));
            continue;
        }

        write(frec[0]);
        previousCost = 0;
        foreach (_; 1 .. frec[0])
            stack[top ++] = 0;

        foreach (i; 1 .. n + 1) {
            if (i !in frec) {
                write(' ', previousCost);
                if (top != 0) {
                    previousCost += i - stack[-- top];
                } else {
                    writefln!" %(%s %)"(repeat(-1, n - i));
                    continue TEST_LOOP;
                }
            } else {
                write(' ', previousCost + frec[i]);
                foreach (_; 1 .. frec[i])
                    stack[top ++] = i;
            }
        }
    }
}
// ""


In Morse code, an letter of English alphabet is represented as a string of some length from $$$1$$$ to $$$4$$$. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1".Because there are $$$2^1+2^2+2^3+2^4 = 30$$$ strings with length $$$1$$$ to $$$4$$$ containing only "0" and/or "1", not all of them correspond to one of the $$$26$$$ English letters. In particular, each string of "0" and/or "1" of length at most $$$4$$$ translates into a distinct English letter, except the following four strings that do not correspond to any English alphabet: "0011", "0101", "1110", and "1111".You will work with a string $$$S$$$, which is initially empty. For $$$m$$$ times, either a dot or a dash will be appended to $$$S$$$, one at a time. Your task is to find and report, after each of these modifications to string $$$S$$$, the number of non-empty sequences of English letters that are represented with some substring of $$$S$$$ in Morse code.Since the answers can be incredibly tremendous, print them modulo $$$10^9 + 7$$$.

The first line contains an integer $$$m$$$ ($$$1 \leq m \leq 3\,000$$$) — the number of modifications to $$$S$$$.  Each of the next $$$m$$$ lines contains either a "0" (representing a dot) or a "1" (representing a dash), specifying which character should be appended to $$$S$$$.

Print $$$m$$$ lines, the $$$i$$$-th of which being the answer after the $$$i$$$-th modification to $$$S$$$.

NoteLet us consider the first sample after all characters have been appended to $$$S$$$, so S is "111".As you can see, "1", "11", and "111" all correspond to some distinct English letter. In fact, they are translated into a 'T', an 'M', and an 'O', respectively. All non-empty sequences of English letters that are represented with some substring of $$$S$$$ in Morse code, therefore, are as follows.  "T" (translates into "1")  "M" (translates into "11")  "O" (translates into "111")  "TT" (translates into "11")  "TM" (translates into "111")  "MT" (translates into "111")  "TTT" (translates into "111") Although unnecessary for this task, a conversion table from English alphabets into Morse code can be found here.

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

enum MO = 10L^^9 + 7;

int M;
int[] A;

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

      auto dp = new long[][](M + 1, M + 1);
      foreach (i; 0 .. M + 1) {
        dp[i][i] = 1;
        foreach (j; i + 1 .. M + 1) {
          foreach (k; 1 .. 4 + 1) {
            if (i <= j - k) {
              if (k == 4) {
                if (A[j - 4 .. j] == [0, 0, 1, 1]) continue;
                if (A[j - 4 .. j] == [0, 1, 0, 1]) continue;
                if (A[j - 4 .. j] == [1, 1, 1, 0]) continue;
                if (A[j - 4 .. j] == [1, 1, 1, 1]) continue;
              }
              if ((dp[i][j] += dp[i][j - k]) >= MO) {
                dp[i][j] -= MO;
              }
            }
          }
        }
      }

      auto com = new int[][](M + 1, M + 1);
      foreach_reverse (i; 0 .. M + 1) foreach_reverse (j; 0 .. M + 1) {
        com[i][j] = (i == M || j == M || A[i] != A[j]) ? 0 : (1 + com[i + 1][j + 1]);
      }

      auto rs = new int[M];
      foreach (i; 0 .. M) {
        foreach (j; 0 .. i) {
          chmax(rs[i], com[j][i]);
        }
      }

      long ans;
      foreach (j; 1 .. M + 1) {
        foreach (i; 0 .. j) {
          if (j - i > rs[i]) {
            debug {
              writeln("add ", i, " ", j, ": ", dp[i][j]);
            }
            if ((ans += dp[i][j]) >= MO) {
              ans -= MO;
            }
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array.SaMer wishes to create more cases from the test case he already has. His test case has an array $$$A$$$ of $$$n$$$ integers, and he needs to find the number of contiguous subarrays of $$$A$$$ that have an answer to the problem equal to $$$k$$$ for each integer $$$k$$$ between $$$1$$$ and $$$n$$$ (inclusive).

The first line of input contains a single integer $$$n$$$ ($$$1 \leq n \leq 5000$$$), the size of the array. The second line contains $$$n$$$ integers $$$a_1$$$,$$$a_2$$$,$$$\dots$$$,$$$a_n$$$ ($$$-10^8 \leq a_i \leq 10^8$$$), the values of the array.

Output $$$n$$$ space-separated integers, the $$$k$$$-th integer should be the number of contiguous subarrays of $$$A$$$ that have an answer to the problem equal to $$$k$$$.

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

void solve(int[] a, int n)
{
    auto f = new bool[][](n, n);
    auto c = new int[n];
    foreach (i; 0 .. n)
    {
        c[i] = 0;
        auto num = cast(long)a[i];
        foreach (j; 0 .. i)
        {
            f[j][i] = false;
            auto m = num * a[j];
            if (m > 0)
            {
                auto r = cast(long)sqrt(cast(double)m);
                if (r * r == m)
                {
                    f[j][i] = true;
                    ++ c[i];
                }
            }
        }
    }
    auto res = new int[n + 1];
    fill(res, 0);
    foreach (i; 0 .. n)
    {
        auto cnt = 0;
        auto flag = false;
        foreach (j; i .. n)
        {
            if (a[j] == 0)
            {
                if (cnt == 0)
                {
                    ++ cnt;
                }
            }
            else
            {
                if (i > 0 && f[i - 1][j])
                {
                    -- c[j];
                }
                if (flag == false)
                {
                    if (cnt == 0)
                    {
                        ++ cnt;
                    }
                }
                else if (c[j] == 0)
                {
                    ++ cnt;
                }
            }
            ++ res[cnt];
            if (a[j] != 0)
            {
                flag = true;
            }
        }
    }
    foreach (i; 1 .. n)
    {
        write(res[i], " ");
    }
    writeln(res[n]);
}

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, n);
    }
    return 0;
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}
void writeA(T)(size_t n,T t){foreach(i,v;t.enumerate){write(v);if(i<n-1)write(" ");}writeln;}

void main()
{
  int n; readV(n);
  int[] a; readA(n, a);

  auto b = new int[](n);
  foreach (i; 0..n)
    b[i] = div(a[i]);

  int[int] z;
  foreach (i, bi; (b ~ [0]).dup.sort.uniq.enumerate) z[bi] = i.to!int;
  auto nz = z.length.to!int, zz = z[0];

  foreach (ref bi; b) bi = z[bi];

  auto r = new int[](n+1), c = new bool[](nz);
  foreach (i; 0..n) {
    c[] = false; c[b[i]] = true;
    auto e = 1;
    r[e]++;
    foreach (j; i+1..n) {
      if (c[zz]) {
        c[zz] = false;
        --e;
      }

      if (e == 0 || b[j] != zz && !c[b[j]]) {
        c[b[j]] = true;
        ++e;
      }

      r[e]++;
    }
  }

  writeA(n, r[1..$]);
}

auto div(int a)
{
  int[] r;
  if (a == 0) return 0;

  if (a < 0) {
    r ~= [-1];
    a = -a;
  }

  foreach (pi; 2..a.nsqrt+1) {
    if (a == 1) break;
    auto c = 0;
    while (a%pi == 0) {
      ++c;
      a /= pi;
    }
    if (c%2 == 1) r ~= pi;
  }

  if (a != 1) r ~= a;

  return r.fold!"a*b"(1);
}

pure T[] primes(T)(T n)
{
  import std.algorithm, std.bitmanip, std.conv, std.range;

  auto sieve = BitArray();
  sieve.length((n+1)/2);
  sieve = ~sieve;

  foreach (p; 1..((nsqrt(n)-1)/2+1))
    if (sieve[p])
      for (auto q = p*3+1; q < (n+1)/2; q += p*2+1)
        sieve[q] = false;

  auto r = sieve.bitsSet.map!(to!T).map!("a*2+1").array;
  r[0] = 2;

  return r;
}

pure T factor(T)(T n, const T[] p)
{
  auto ma = nsqrt(n)+1;
  foreach (pi; p)
    if (pi > ma) return n;
    else if (n%pi == 0) return pi;
  return n;
}

pure T nsqrt(T)(T n)
{
  import std.algorithm, std.conv, std.range, core.bitop;
  if (n <= 1) return n;
  T m = T(1) << (n.bsr/2+1);
  return iota(1, m).map!"a*a".assumeSorted!"a <= b".lowerBound(n).length.to!T;
}

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

void solve(int[] a, int n)
{
    auto f = new bool[][](n, n);
    auto c = new int[n];
    foreach (i; 0 .. n)
    {
        c[i] = 0;
        auto num = cast(long)a[i];
        foreach (j; 0 .. i)
        {
            f[j][i] = false;
            auto m = num * a[j];
            if (m >= 0)
            {
                auto r = sqrt(cast(double)m);
                if (r - cast(int)r <= 1e-9)
                {
                    f[j][i] = true;
                    ++ c[i];
                }
            }
        }
    }
    auto res = new int[n + 1];
    fill(res, 0);
    foreach (i; 0 .. n)
    {
        auto cnt = 0;
        foreach (j; i .. n)
        {
            if (i > 0 && f[i - 1][j])
            {
                -- c[j];
            }
            if (c[j] == 0)
            {
                ++ cnt;
            }
            ++ res[cnt];
        }
    }
    foreach (i; 1 .. n)
    {
        write(res[i], " ");
    }
    writeln(res[n]);
}

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, n);
    }
    return 0;
}

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

void solve(int[] a, int n)
{
    auto f = new bool[][](n, n);
    auto c = new int[n];
    foreach (i; 0 .. n)
    {
        c[i] = 0;
        auto num = cast(long)a[i];
        foreach (j; 0 .. i)
        {
            auto m = num * a[j];
            if (m >= 0)
            {
                auto r = sqrt(cast(double)m);
                f[j][i] = false;
                if (cast(long)r == r)
                {
                    f[j][i] = true;
                    ++ c[i];
                }
            }
        }
    }
    auto res = new int[n + 1];
    fill(res, 0);
    foreach (i; 0 .. n)
    {
        auto cnt = 0;
        foreach (j; i .. n)
        {
            if (i > 0 && f[i - 1][j])
            {
                -- c[j];
            }
            if (c[j] == 0)
            {
                ++ cnt;
            }
            ++ res[cnt];
        }
    }
    foreach (i; 1 .. n)
    {
        write(res[i], " ");
    }
    writeln(res[n]);
}

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, n);
    }
    return 0;
}

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

void solve(int[] a, int n)
{
    auto f = new bool[][](n, n);
    auto c = new int[n];
    foreach (i; 0 .. n)
    {
        c[i] = 0;
        auto num = cast(long)a[i];
        foreach (j; 0 .. i)
        {
            auto m = num * a[j];
            if (m >= 0)
            {
                auto r = sqrt(cast(double)m);
                f[j][i] = false;
                if (r - cast(int)r <= 1e-9)
                {
                    f[j][i] = true;
                    ++ c[i];
                }
            }
        }
    }
    auto res = new int[n + 1];
    fill(res, 0);
    foreach (i; 0 .. n)
    {
        auto cnt = 0;
        foreach (j; i .. n)
        {
            if (i > 0 && f[i - 1][j])
            {
                -- c[j];
            }
            if (c[j] == 0)
            {
                ++ cnt;
            }
            ++ res[cnt];
        }
    }
    foreach (i; 1 .. n)
    {
        write(res[i], " ");
    }
    writeln(res[n]);
}

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, n);
    }
    return 0;
}

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

void solve(int[] a, int n)
{
    auto f = new bool[][](n, n);
    auto c = new int[n];
    foreach (i; 0 .. n)
    {
        c[i] = 0;
        auto num = cast(double)a[i];
        foreach (j; 0 .. i)
        {
            f[j][i] = false;
            auto m = num * a[j];
            if (m > 0)
            {
                auto r = cast(long)sqrt(m);
                if (r * r == m)
                {
                    f[j][i] = true;
                    ++ c[i];
                }
            }
        }
    }
    auto res = new int[n + 1];
    fill(res, 0);
    foreach (i; 0 .. n)
    {
        auto cnt = 0;
        auto flag = false;
        foreach (j; i .. n)
        {
            if (a[j] == 0)
            {
                if (cnt == 0) ++ cnt;
            }
            else
            {
                if (i > 0 && f[i - 1][j])
                {
                    -- c[j];
                }
                if (flag == false)
                {
                    if (cnt == 0) ++ cnt;
                }
                else if (c[j] == 0)
                {
                    ++ cnt;
                }
            }
            ++ res[cnt];
            if (a[j] != 0)
            {
                flag = true;
            }
        }
    }
    foreach (i; 1 .. n)
    {
        write(res[i], " ");
    }
    writeln(res[n]);
}

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, n);
    }
    return 0;
}

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

void solve(int[] a, int n)
{
    auto f = new bool[][](n, n);
    auto c = new int[n];
    foreach (i; 0 .. n)
    {
        c[i] = 0;
        auto num = cast(long)a[i];
        foreach (j; 0 .. i)
        {
            f[j][i] = false;
            double m = num * a[j];
            if (m >= 0)
            {
                auto r = cast(long)sqrt(cast(double)m);
                if (r * r == m)
                {
                    f[j][i] = true;
                    ++ c[i];
                }
            }
        }
    }
    auto res = new int[n + 1];
    fill(res, 0);
    foreach (i; 0 .. n)
    {
        auto cnt = 0;
        foreach (j; i .. n)
        {
            if (i > 0 && f[i - 1][j])
            {
                -- c[j];
            }
            if (c[j] == 0)
            {
                ++ cnt;
            }
            ++ res[cnt];
        }
    }
    foreach (i; 1 .. n)
    {
        write(res[i], " ");
    }
    writeln(res[n]);
}

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, n);
    }
    return 0;
}

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

void solve(int[] a, int n)
{
    auto f = new bool[][](n, n);
    auto c = new int[n];
    foreach (i; 0 .. n)
    {
        c[i] = 0;
        auto num = cast(long)a[i];
        foreach (j; 0 .. i)
        {
            f[j][i] = false;
            auto m = num * a[j];
            if (m >= 0)
            {
                auto r = cast(long)sqrt(cast(double)m);
                if (r * r == m)
                {
                    f[j][i] = true;
                    ++ c[i];
                }
            }
        }
    }
    auto res = new int[n + 1];
    fill(res, 0);
    foreach (i; 0 .. n)
    {
        auto cnt = 0;
        foreach (j; i .. n)
        {
            if (i > 0 && f[i - 1][j])
            {
                -- c[j];
            }
            if (c[j] == 0)
            {
                ++ cnt;
            }
            ++ res[cnt];
        }
    }
    foreach (i; 1 .. n)
    {
        write(res[i], " ");
    }
    writeln(res[n]);
}

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, n);
    }
    return 0;
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n; readV(n);
  int[] a; readA(n, a);

  auto p = primes(10^^4);
  auto b = new int[][](n);
  foreach (i; 0..n)
    b[i] = div(a[i], p);

  auto r = new int[](n+1);
  foreach (i; 0..n) {
    auto rbt = redBlackTree!(false, int[])(b[i]);
    r[1]++;
    foreach (j; i+1..n) {
      if (!rbt.empty && rbt.front == [0]) {
        rbt.removeFront();
      }
      if (b[j] != [0]) {
        rbt.insert(b[j]);
      }
      r[rbt.length]++;
    }
  }

  foreach (i; 0..n)
    write(r[i+1], " ");
  writeln;
}

auto div(int a, int[] p)
{
  int[] r;
  if (a == 0) return [0];

  if (a < 0) {
    r ~= [-1];
    a = -a;
  }

  foreach (pi; p) {
    if (a == 1) break;
    auto c = 0;
    while (a%pi == 0) {
      ++c;
      a /= pi;
    }
    if (c%2 == 1) r ~= pi;
  }

  return r;
}

pure T[] primes(T)(T n)
{
  import std.algorithm, std.bitmanip, std.conv, std.range;

  auto sieve = BitArray();
  sieve.length((n+1)/2);
  sieve = ~sieve;

  foreach (p; 1..((nsqrt(n)-1)/2+1))
    if (sieve[p])
      for (auto q = p*3+1; q < (n+1)/2; q += p*2+1)
        sieve[q] = false;

  auto r = sieve.bitsSet.map!(to!T).map!("a*2+1").array;
  r[0] = 2;

  return r;
}

pure T factor(T)(T n, const T[] p)
{
  auto ma = nsqrt(n)+1;
  foreach (pi; p)
    if (pi > ma) return n;
    else if (n%pi == 0) return pi;
  return n;
}

pure T nsqrt(T)(T n)
{
  import std.algorithm, std.conv, std.range, core.bitop;
  if (n <= 1) return n;
  T m = T(1) << (n.bsr/2+1);
  return iota(1, m).map!"a*a".assumeSorted!"a <= b".lowerBound(n).length.to!T;
}


This is the easy version of the problem. The only difference is maximum value of $$$a_i$$$.Once in Kostomuksha Divan found an array $$$a$$$ consisting of positive integers. Now he wants to reorder the elements of $$$a$$$ to maximize the value of the following function: $$$$$$\sum_{i=1}^n \operatorname{gcd}(a_1, \, a_2, \, \dots, \, a_i),$$$$$$ where $$$\operatorname{gcd}(x_1, x_2, \ldots, x_k)$$$ denotes the greatest common divisor of integers $$$x_1, x_2, \ldots, x_k$$$, and $$$\operatorname{gcd}(x) = x$$$ for any integer $$$x$$$.Reordering elements of an array means changing the order of elements in the array arbitrary, or leaving the initial order.Of course, Divan can solve this problem. However, he found it interesting, so he decided to share it with you.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the size of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_{1}, \, a_{2}, \, \dots, \, a_{n}$$$ ($$$1 \le a_{i} \le 5 \cdot 10^6$$$) — the array $$$a$$$.

Output the maximum value of the function that you can get by reordering elements of the array $$$a$$$.

NoteIn the first example, it's optimal to rearrange the elements of the given array in the following order: $$$[6, \, 2, \, 2, \, 2, \, 3, \, 1]$$$:$$$$$$\operatorname{gcd}(a_1) + \operatorname{gcd}(a_1, \, a_2) + \operatorname{gcd}(a_1, \, a_2, \, a_3) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4, \, a_5) + \operatorname{gcd}(a_1, \, a_2, \, a_3, \, a_4, \, a_5, \, a_6) = 6 + 2 + 2 + 2 + 1 + 1 = 14.$$$$$$ It can be shown that it is impossible to get a better answer.In the second example, it's optimal to rearrange the elements of a given array in the following order: $$$[100, \, 10, \, 10, \, 5, \, 1, \, 3, \, 3, \, 7, \, 42, \, 54]$$$.

immutable multi = false;

immutable int maxAi = 5000000;
int[][] pd;

void solve(int tc)
{
	debug writeln("starting");
	pd = new int[][](maxAi+1);
	foreach(n; 2 .. pd.length)
	{
		if (pd[n].length == 0)
		{
			for (int m = cast(int)n;
			     m < pd.length;
			     m += n)
			{
				pd[m] ~= cast(int)n;
			}
		}
	}
	long[int][] ans = new long[int][](maxAi+1);
	int[] cnt = new int[](maxAi+1);
	debug writeln("after computing pd");
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	debug writeln("after reading");
	foreach(i, ai; a)
	{
		for (int d = 1; d * d <= ai; d++)
		{
			int div = ai / d;
			int rem = ai - div * d;
			if (rem == 0)
			{
				cnt[div]++;
				if (d != div) cnt[d]++;
			}
		}
	}
	long dp(int n, int tkn)
	{
		assert(tkn <= cnt[n]);
		if (auto val = tkn in ans[n]) return *val;
		long rem = cnt[n] - tkn;
		long val = n * rem;
		long best = 0;
		debug writeln("on ", n, " ", tkn);
		foreach(p; pd[n])
		{
			debug writeln("p ", p);
			best = max(best, dp(n/p, cnt[n]));
		}
		val += best;
		debug writeln("value of ", n, " ", tkn, " is ", val);
		return ans[n][tkn] = val;
	}
	debug writeln(cnt[0 .. 7]);
	long best = long.min;
	foreach(i, ai; a) best = max(best, dp(ai, 0));
	best.writeln;
}

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

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

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

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

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

immutable multi = false;

immutable int maxAi = 5000000;
int[][] pd;

void solve(int tc)
{
	debug writeln("starting");
	pd = new int[][](maxAi+1);
	foreach(n; 2 .. pd.length)
	{
		if (pd[n].length == 0)
		{
			for (int m = cast(int)n;
			     m < pd.length;
			     m += n)
			{
				pd[m] ~= cast(int)n;
			}
		}
	}
	long[int][] ans = new long[int][](maxAi+1);
	int[] cnt = new int[](maxAi+1);
	debug writeln("after computing pd");
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	debug writeln("after reading");
	foreach(i, ai; a)
	{
		for (int d = 1; d * d <= ai; d++)
		{
			int div = ai / d;
			int rem = ai - div * d;
			if (rem == 0)
			{
				cnt[div]++;
				if (d != div) cnt[d]++;
			}
		}
	}
	long dp(int n, int tkn)
	{
		assert(tkn <= cnt[n]);
		if (auto val = tkn in ans[n]) return *val;
		int rem = cnt[n] - tkn;
		long val = n * rem;
		long best = 0;
		debug writeln("on ", n, " ", tkn);
		foreach(p; pd[n])
		{
			debug writeln("p ", p);
			best = max(best, dp(n/p, cnt[n]));
		}
		val += best;
		debug writeln("value of ", n, " ", tkn, " is ", val);
		return ans[n][tkn] = val;
	}
	debug writeln(cnt[0 .. 7]);
	long best = long.min;
	foreach(i, ai; a) best = max(best, dp(ai, 0));
	best.writeln;
}

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

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

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

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

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


There are k sensors located in the rectangular room of size n × m meters. The i-th sensor is located at point (xi, yi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0, 0) and (n, m). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0, 0) the laser ray is released in the direction of point (1, 1). The ray travels with a speed of  meters per second. Thus, the ray will reach the point (1, 1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print  - 1 for such sensors.

The first line of the input contains three integers n, m and k (2 ≤ n, m ≤ 100 000, 1 ≤ k ≤ 100 000) — lengths of the room's walls and the number of sensors. Each of the following k lines contains two integers xi and yi (1 ≤ xi ≤ n - 1, 1 ≤ yi ≤ m - 1) — coordinates of the sensors. It's guaranteed that no two sensors are located at the same point.

Print k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or  - 1 if this will never happen.

NoteIn the first sample, the ray will consequently pass through the points (0, 0), (1, 1), (2, 2), (3, 3). Thus, it will stop at the point (3, 3) after 3 seconds.  In the second sample, the ray will consequently pass through the following points: (0, 0), (1, 1), (2, 2), (3, 3), (2, 4), (1, 3), (0, 2), (1, 1), (2, 0), (3, 1), (2, 2), (1, 3), (0, 4). The ray will stop at the point (0, 4) after 12 seconds. It will reflect at the points (3, 3), (2, 4), (0, 2), (2, 0) and (3, 1).

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

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

    Tuple!(int, int)[] pts;
    foreach (i; 0 .. k) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        pts ~= tuple(x, y);
    }

    int[][int] up, dwn;
    foreach (i, p; pts) {
        up[p[1] - p[0]] ~= i.to!int;
        dwn[p[1] + p[0]] ~= i.to!int;
    }

    debug { up.writeln; dwn.writeln; }

    auto ans = new long[k];
    ans[] = -1;

    auto vis = new bool[][] (4, max(n+1, m+1));

    Tuple!(int, int) toVis(int x, int y) {
        if (y == 0) { return tuple(0, x); }
        if (y == m) { return tuple(1, x); }
        if (x == 0) { return tuple(2, y); }
        if (x == n) { return tuple(3, y); }

        assert(false);
    }

    vis[0][0] = vis[1][0] = vis[0][n] = vis[1][n] = true;
    int cx = 0, cy = 0, dir = 1;
    long tm = 0;
    do {
        vis[toVis(cx, cy)[0]][toVis(cx, cy)[1]] = true;
        int nx, ny, mv;
        if (dir == 1) {
            mv = min(n - cx, m - cy);
            nx = cx + mv;
            ny = cy + mv;
            dir = ny != m ? 2 : 4;
        } else if (dir == 2) {
            mv = min(cx, m - cy);
            nx = cx - mv;
            ny = cy + mv;
            dir = ny == m ? 3 : 1;
        } else if (dir == 3) {
            mv = min(cx, cy);
            nx = cx - mv;
            ny = cy - mv;
            dir = nx == 0 ? 4 : 2;
        } else {
            mv = min(n - cx, cy);
            nx = cx + mv;
            ny = cy - mv;
            dir = ny == 0 ? 1 : 3;
        }

        bool isUp = (nx - cx).to!long * (ny - cy) > 0;
        int coord = isUp ? ny - nx : ny + nx;
        auto dct = isUp ? &up : &dwn;
        foreach (idx; dct.get(coord, [])) {
            if (ans[idx] != -1) { continue; }

            ans[idx] = tm + abs(pts[idx][0] - cx);
        }

        cx = nx;
        cy = ny;
        tm += mv;

        debug { writeln(cx, ' ', cy, ' ', tm, ' ', dir); }

    } while (!vis[toVis(cx, cy)[0]][toVis(cx, cy)[1]]);

    ans.each!writeln;
}

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

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

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

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

Int gojo(Int)(Int a, Int b, out Int x, out Int y) {
  if (b != 0) { Int g = gojo(b, a % b, y, x); y -= (a / b) * x; return g; }
  x = 1; y = 0; return a;
}
Tuple!(Int, "b", Int, "m") modSol(Int)(Int b0, Int m0, Int b1, Int m1) {
  Int b, m, x, y;
  const g = gojo(m0, m1, x, y);
  if ((b1 - b0) % g == 0) {
    b = b0 + m0 * ((x * (((b1 - b0) / g) % (m1 / g))) % (m1 / g));
    m = m0 * (m1 / g);
    if ((b %= m) < 0) {
      b += m;
    }
  }
  return Tuple!(Int, "b", Int, "m")(b, m);
}

enum INF = 10L^^18;

void main() {
  try {
    for (; ; ) {
      const M = readLong();
      const N = readLong();
      const K = readInt();
      auto X = new long[K];
      auto Y = new long[K];
      foreach (k; 0 .. K) {
        X[k] = readLong();
        Y[k] = readLong();
      }

      long calc(long x, long y) {
        const res = modSol(x, 2 * M, y, 2 * N);
        debug {
          writeln(x, " ", y, ": ", res);
        }
        return (res.m == 0) ? INF : res.b;
      }

      foreach (k; 0 .. K) {
        long ans = INF;
        foreach (x; [X[k], 2 * M - X[k]]) foreach (y; [Y[k], 2 * N - Y[k]]) {
          const res = calc(x, y);
          chmin(ans, res);
        }
        writeln((ans >= INF) ? -1 : ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

    Tuple!(int, int)[] pts;
    foreach (i; 0 .. k) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        pts ~= tuple(x, y);
    }

    int[][int] up, dwn;
    foreach (i, p; pts) {
        up[p[1] - p[0]] ~= i.to!int;
        dwn[p[1] + p[0]] ~= i.to!int;
    }

    debug { up.writeln; dwn.writeln; }

    auto ans = new long[k];
    ans[] = -1;

    auto vis = new bool[][] (4, max(n+1, m+1));

    Tuple!(int, int) toVis(int x, int y) {
        if (y == 0) { return tuple(0, x); }
        if (y == m) { return tuple(1, x); }
        if (x == 0) { return tuple(0, y); }
        if (x == n) { return tuple(1, y); }

        assert(false);
    }

    vis[0][0] = vis[1][0] = vis[0][n] = vis[1][n] = true;
    int cx = 0, cy = 0, dir = 1;
    long tm = 0;
    do {
        vis[toVis(cx, cy)[0]][toVis(cx, cy)[1]] = true;
        int nx, ny, mv;
        if (dir == 1) {
            mv = min(n - cx, m - cy);
            nx = cx + mv;
            ny = cy + mv;
            dir = ny != m ? 2 : 4;
        } else if (dir == 2) {
            mv = min(cx, m - cy);
            nx = cx - mv;
            ny = cy + mv;
            dir = ny == m ? 3 : 1;
        } else if (dir == 3) {
            mv = min(cx, cy);
            nx = cx - mv;
            ny = cy - mv;
            dir = nx == 0 ? 4 : 2;
        } else {
            mv = min(n - cx, cy);
            nx = cx + mv;
            ny = cy - mv;
            dir = ny == 0 ? 1 : 3;
        }

        bool isUp = (nx - cx).to!long * (ny - cy) > 0;
        int coord = isUp ? ny - nx : ny + nx;
        auto dct = isUp ? &up : &dwn;
        foreach (idx; dct.get(coord, [])) {
            if (ans[idx] != -1) { continue; }

            ans[idx] = tm + abs(pts[idx][0] - cx);
        }

        cx = nx;
        cy = ny;
        tm += mv;

        debug { writeln(cx, ' ', cy, ' ', tm, ' ', dir); }

    } while (!vis[toVis(cx, cy)[0]][toVis(cx, cy)[1]]);

    ans.each!writeln;
}

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

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

    Tuple!(int, int)[] pts;
    foreach (i; 0 .. k) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        pts ~= tuple(x, y);
    }

    int[][int] up, dwn;
    foreach (i, p; pts) {
        up[p[1] - p[0]] ~= i.to!int;
        dwn[p[1] + p[0]] ~= i.to!int;
    }

    debug { up.writeln; dwn.writeln; }

    auto ans = new int[k];
    ans[] = -1;

    auto vis = new bool[][] (4, max(n+1, m+1));

    Tuple!(int, int) toVis(int x, int y) {
        if (y == 0) { return tuple(0, x); }
        if (y == m) { return tuple(1, x); }
        if (x == 0) { return tuple(2, y); }
        if (x == n) { return tuple(3, y); }

        assert(false);
    }

    vis[0][0] = vis[1][0] = vis[0][n] = vis[1][n] = true;
    int cx = 0, cy = 0, dir = 1, tm = 0;
    do {
        vis[toVis(cx, cy)[0]][toVis(cx, cy)[1]] = true;
        int nx, ny, mv;
        if (dir == 1) {
            mv = min(n - cx, m - cy);
            nx = cx + mv;
            ny = cy + mv;
            dir = ny != m ? 2 : 4;
        } else if (dir == 2) {
            mv = min(cx, m - cy);
            nx = cx - mv;
            ny = cy + mv;
            dir = ny == m ? 3 : 1;
        } else if (dir == 3) {
            mv = min(cx, cy);
            nx = cx - mv;
            ny = cy - mv;
            dir = nx == 0 ? 4 : 2;
        } else {
            mv = min(n - cx, cy);
            nx = cx + mv;
            ny = cy - mv;
            dir = ny == 0 ? 1 : 3;
        }

        bool isUp = (nx - cx).to!long * (ny - cy) > 0;
        int coord = isUp ? ny - nx : ny + nx;
        auto dct = isUp ? &up : &dwn;
        foreach (idx; dct.get(coord, [])) {
            if (ans[idx] != -1) { continue; }

            ans[idx] = tm + abs(pts[idx][0] - cx);
        }

        cx = nx;
        cy = ny;
        tm += mv;

        debug { writeln(cx, ' ', cy, ' ', tm, ' ', dir); }

    } while (!vis[toVis(cx, cy)[0]][toVis(cx, cy)[1]]);

    ans.each!writeln;
}

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

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

    Tuple!(int, int)[] pts;
    foreach (i; 0 .. k) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        pts ~= tuple(x, y);
    }

    int[][int] up, dwn;
    foreach (i, p; pts) {
        up[p[1] - p[0]] ~= i.to!int;
        dwn[p[1] + p[0]] ~= i.to!int;
    }

    debug { up.writeln; dwn.writeln; }

    auto ans = new int[k];
    ans[] = -1;

    auto vis = new bool[][] (4, max(n+1, m+1));

    Tuple!(int, int) toVis(int x, int y) {
        if (y == 0) { return tuple(0, x); }
        if (y == m) { return tuple(1, x); }
        if (x == 0) { return tuple(0, y); }
        if (x == n) { return tuple(1, y); }

        assert(false);
    }

    vis[0][0] = vis[1][0] = vis[0][n] = vis[1][n] = true;
    int cx = 0, cy = 0, dir = 1, tm = 0;
    do {
        vis[toVis(cx, cy)[0]][toVis(cx, cy)[1]] = true;
        int nx, ny, mv;
        if (dir == 1) {
            mv = min(n - cx, m - cy);
            nx = cx + mv;
            ny = cy + mv;
            dir = ny != m ? 2 : 4;
        } else if (dir == 2) {
            mv = min(cx, m - cy);
            nx = cx - mv;
            ny = cy + mv;
            dir = ny == m ? 3 : 1;
        } else if (dir == 3) {
            mv = min(cx, cy);
            nx = cx - mv;
            ny = cy - mv;
            dir = nx == 0 ? 4 : 2;
        } else {
            mv = min(n - cx, cy);
            nx = cx + mv;
            ny = cy - mv;
            dir = ny == 0 ? 1 : 3;
        }

        bool isUp = (nx - cx).to!long * (ny - cy) > 0;
        int coord = isUp ? ny - nx : ny + nx;
        auto dct = isUp ? &up : &dwn;
        foreach (idx; dct.get(coord, [])) {
            if (ans[idx] != -1) { continue; }

            ans[idx] = tm + abs(pts[idx][0] - cx);
        }

        cx = nx;
        cy = ny;
        tm += mv;

        debug { writeln(cx, ' ', cy, ' ', tm, ' ', dir); }

    } while (!vis[toVis(cx, cy)[0]][toVis(cx, cy)[1]]);

    ans.each!writeln;
}


Ivan has $$$n$$$ songs on his phone. The size of the $$$i$$$-th song is $$$a_i$$$ bytes. Ivan also has a flash drive which can hold at most $$$m$$$ bytes in total. Initially, his flash drive is empty.Ivan wants to copy all $$$n$$$ songs to the flash drive. He can compress the songs. If he compresses the $$$i$$$-th song, the size of the $$$i$$$-th song reduces from $$$a_i$$$ to $$$b_i$$$ bytes ($$$b_i < a_i$$$).Ivan can compress any subset of the songs (possibly empty) and copy all the songs to his flash drive if the sum of their sizes is at most $$$m$$$. He can compress any subset of the songs (not necessarily contiguous).Ivan wants to find the minimum number of songs he needs to compress in such a way that all his songs fit on the drive (i.e. the sum of their sizes is less than or equal to $$$m$$$).If it is impossible to copy all the songs (even if Ivan compresses all the songs), print "-1". Otherwise print the minimum number of songs Ivan needs to compress.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5, 1 \le m \le 10^9$$$) — the number of the songs on Ivan's phone and the capacity of Ivan's flash drive. The next $$$n$$$ lines contain two integers each: the $$$i$$$-th line contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$, $$$a_i > b_i$$$) — the initial size of the $$$i$$$-th song and the size of the $$$i$$$-th song after compression.

If it is impossible to compress a subset of the songs in such a way that all songs fit on the flash drive, print "-1". Otherwise print the minimum number of the songs to compress.

NoteIn the first example Ivan can compress the first and the third songs so after these moves the sum of sizes will be equal to $$$8 + 7 + 1 + 5 = 21 \le 21$$$. Also Ivan can compress the first and the second songs, then the sum of sizes will be equal $$$8 + 4 + 3 + 5 = 20 \le 21$$$. Note that compressing any single song is not sufficient to copy all the songs on the flash drive (for example, after compressing the second song the sum of sizes will be equal to $$$10 + 4 + 3 + 5 = 22 > 21$$$).In the second example even if Ivan compresses all the songs the sum of sizes will be equal $$$8 + 4 + 1 + 4 = 17 > 16$$$.

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

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

    Tuple!(int, int)[] arr;
    foreach (_; 0 .. n) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        arr ~= tuple(a, b);
    }

    arr.schwartzSort!(t => t[0] - t[1]).reverse();

    debug { arr.writeln; }

    long total = arr.map!(t => t[0]).sum(0L);
    int ans = 0;
    foreach (e; arr) {
        if (total <= m) break;

        total -= e[0] - e[1];
        ++ans;
    }

    if (total > m) {
        writeln(-1);
        return;
    }

    ans.writeln;
}

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

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

    Tuple!(int, int)[] arr;
    auto fnc = (int[] a) => tuple(a[0], a[1]);
    foreach (_; 0 .. n) {
        int a, b;
        readf("%s %s", &a, &b);
        readln;

        arr ~= tuple(a, b);
    }

    arr.schwartzSort!(t => t[0] - t[1]).reverse();

    debug { arr.writeln; }

    long total = arr.map!(t => t[0]).sum(0L);
    int ans = 0;
    foreach (e; arr) {
        if (total <= m) break;

        total -= e[0] - e[1];
        ++ans;
    }

    if (total > m) {
        writeln(-1);
        return;
    }

    ans.writeln;
}

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

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		readln;
		auto a = new int [n];
		auto b = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s %s", &a[i], &b[i]);
		}
		b[] = a[] - b[];
		sort !(q{a > b}) (b);
		auto total = sum (a, 0L);
		int res = 0;
		while (total > m && !b.empty)
		{
			res += 1;
			total -= b[0];
			b = b[1..$];
		}
		if (total > m)
		{
			res = -1;
		}
		writeln (res);
	}
}


You are given three positive integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$a < b < c$$$). You have to find three positive integers $$$x$$$, $$$y$$$, $$$z$$$ such that:$$$$$$x \bmod y = a,$$$$$$ $$$$$$y \bmod z = b,$$$$$$ $$$$$$z \bmod x = c.$$$$$$Here $$$p \bmod q$$$ denotes the remainder from dividing $$$p$$$ by $$$q$$$. It is possible to show that for such constraints the answer always exists.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. Description of the test cases follows. Each test case contains a single line with three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a < b < c \le 10^8$$$).

For each test case output three positive integers $$$x$$$, $$$y$$$, $$$z$$$ ($$$1 \le x, y, z \le 10^{18}$$$) such that $$$x \bmod y = a$$$, $$$y \bmod z = b$$$, $$$z \bmod x = c$$$. You can output any correct answer.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto a = readln.splitter.map !(to !(long)).array;
		a[1] += a[2];
		a[0] += a[1];
		writefln !("%(%s %)") (a);
	}
}


Shinju loves permutations very much! Today, she has borrowed a permutation $$$p$$$ from Juju to play with.The $$$i$$$-th cyclic shift of a permutation $$$p$$$ is a transformation on the permutation such that $$$p = [p_1, p_2, \ldots, p_n] $$$ will now become $$$ p = [p_{n-i+1}, \ldots, p_n, p_1,p_2, \ldots, p_{n-i}]$$$.Let's define the power of permutation $$$p$$$ as the number of distinct elements in the prefix maximums array $$$b$$$ of the permutation. The prefix maximums array $$$b$$$ is the array of length $$$n$$$ such that $$$b_i = \max(p_1, p_2, \ldots, p_i)$$$. For example, the power of $$$[1, 2, 5, 4, 6, 3]$$$ is $$$4$$$ since $$$b=[1,2,5,5,6,6]$$$ and there are $$$4$$$ distinct elements in $$$b$$$.Unfortunately, Shinju has lost the permutation $$$p$$$! The only information she remembers is an array $$$c$$$, where $$$c_i$$$ is the power of the $$$(i-1)$$$-th cyclic shift of the permutation $$$p$$$. She's also not confident that she remembers it correctly, so she wants to know if her memory is good enough.Given the array $$$c$$$, determine if there exists a permutation $$$p$$$ that is consistent with $$$c$$$. You do not have to construct the permutation $$$p$$$.A 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).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^3$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1,c_2,\ldots,c_n$$$ ($$$1 \leq c_i \leq n$$$).  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print "YES" if there is a permutation $$$p$$$ exists that satisfies the array $$$c$$$, and "NO" otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive response).

NoteIn the first test case, the permutation $$$[1]$$$ satisfies the array $$$c$$$.In the second test case, the permutation $$$[2,1]$$$ satisfies the array $$$c$$$.In the fifth test case, the permutation $$$[5, 1, 2, 4, 6, 3]$$$ satisfies the array $$$c$$$. Let's see why this is true.  The zeroth cyclic shift of $$$p$$$ is $$$[5, 1, 2, 4, 6, 3]$$$. Its power is $$$2$$$ since $$$b = [5, 5, 5, 5, 6, 6]$$$ and there are $$$2$$$ distinct elements — $$$5$$$ and $$$6$$$.  The first cyclic shift of $$$p$$$ is $$$[3, 5, 1, 2, 4, 6]$$$. Its power is $$$3$$$ since $$$b=[3,5,5,5,5,6]$$$.  The second cyclic shift of $$$p$$$ is $$$[6, 3, 5, 1, 2, 4]$$$. Its power is $$$1$$$ since $$$b=[6,6,6,6,6,6]$$$.  The third cyclic shift of $$$p$$$ is $$$[4, 6, 3, 5, 1, 2]$$$. Its power is $$$2$$$ since $$$b=[4,6,6,6,6,6]$$$.  The fourth cyclic shift of $$$p$$$ is $$$[2, 4, 6, 3, 5, 1]$$$. Its power is $$$3$$$ since $$$b = [2, 4, 6, 6, 6, 6]$$$.  The fifth cyclic shift of $$$p$$$ is $$$[1, 2, 4, 6, 3, 5]$$$. Its power is $$$4$$$ since $$$b = [1, 2, 4, 6, 6, 6]$$$. Therefore, $$$c = [2, 3, 1, 2, 3, 4]$$$.In the third, fourth, and sixth testcases, we can show that there is no permutation that satisfies array $$$c$$$.

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

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

void solve() {
    int N = read!int;
    auto C = readarray!int;

    bool f() {
        if (C.count(1) != 1) return false;
        int first = N - C.find(1).length;
        int i = first;
        do {
            int j = (i + 1) % N;
            if (C[j] > C[i] + 1) return false;
            i = j;
        } while (i != first);
        return true;
    }
    writeln(f() ? "YES" : "NO");
}

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


You have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar. In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.For example, if you have a chocolate bar consisting of 2 × 3 unit squares then you can break it horizontally and get two 1 × 3 pieces (the cost of such breaking is 32 = 9), or you can break it vertically in two ways and get two pieces: 2 × 1 and 2 × 2 (the cost of such breaking is 22 = 4).For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining n·m - k squares are not necessarily form a single rectangular piece.

The first line of the input contains a single integer t (1 ≤ t ≤ 40910) — the number of values n, m and k to process. Each of the next t lines contains three integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ min(n·m, 50)) — the dimensions of the chocolate bar and the number of squares you want to eat respectively.

For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.

NoteIn the first query of the sample one needs to perform two breaks:  to split 2 × 2 bar into two pieces of 2 × 1 (cost is 22 = 4),  to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 12 = 1). In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.

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

int dp[31][31][51];
immutable auto inf = 1 << 29;

int saiki(int n, int m, int k)
{
    int res = dp[n][m][k];
    if (res != -1) return res;
    if (k == 0)
    {
        dp[n][m][k] = 0;
        return 0;
    }
    if (n * m < k)
    {
        dp[n][m][k] = inf;
        return dp[n][m][k];
    }
    if (n * m == k) return 0;
    res = inf;
    foreach (i; 1 .. (n >> 1) + 1)
    {
        foreach (j; 0 .. to!int(fmin(i * m, k)) + 1)
        {
            auto ret = saiki(i, m, j) + saiki(n - i, m, k - j) + m * m;
            res = to!int(fmin(res, ret));
        }
    }
    foreach (i; 1 .. (m >> 1) + 1)
    {
        foreach (j; 0 .. to!int(fmin(i * n, k)) + 1)
        {
            auto ret = saiki(n, i, j) + saiki(n, m - i, k - j) + n * n;
            res = to!int(fmin(res, ret));
        }
    }
    dp[n][m][k] = res;
    return res;
}

void main(string[] args)
{
    int t;
    foreach (i; 0 .. 31)
    {
        foreach (j; 0 .. 31)
        {
            foreach (k; 0 .. 51)
            {
                dp[i][j][k] = -1;
            }
        }
    }
    scanf("%d", &t);
    foreach (i; 0 .. t)
    {
        int n, m, k;
        scanf("%d%d%d", &n, &m, &k);
        auto ans = saiki(n, m, k);
        writeln(ans);
    }
}

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

int dp[31][31][51];
immutable auto inf = 1 << 29;

int saiki(int n, int m, int k)
{
    int res = dp[n][m][k];
    if (res != -1) return res;
    if (k == 0 || n * m == k) return 0;
    if (n * m < k) return inf;
    res = inf;
    foreach (i; 1 .. (n >> 1) + 1)
    {
        foreach (j; 0 .. to!int(fmin(i * m, k)) + 1)
        {
            auto ret = saiki(i, m, j) + saiki(n - i, m, k - j) + m * m;
            res = to!int(fmin(res, ret));
        }
    }
    foreach (i; 1 .. (m >> 1) + 1)
    {
        foreach (j; 0 .. to!int(fmin(i * n, k)) + 1)
        {
            auto ret = saiki(n, i, j) + saiki(n, m - i, k - j) + n * n;
            res = to!int(fmin(res, ret));
        }
    }
    dp[n][m][k] = res;
    return res;
}

void main(string[] args)
{
    int t;
    foreach (i; 0 .. 31)
    {
        foreach (j; 0 .. 31)
        {
            foreach (k; 0 .. 51)
            {
                dp[i][j][k] = -1;
            }
        }
    }
    scanf("%d", &t);
    foreach (i; 0 .. t)
    {
        int n, m, k;
        scanf("%d%d%d", &n, &m, &k);
        auto ans = saiki(n, m, k);
        writeln(ans);
    }
}

import std.algorithm;
import std.functional;
import std.stdio;

immutable int MAX_N = 31;
immutable int MAX_K = 51;
immutable int INF = int.max / 4;
immutable int NA = -1;

int [] [] [] f;

int mfun (int n, int m, int k)
{
	if (f[n][m][k] == NA)
	{
		f[n][m][k] = fun (n, m, k);
	}
	return f[n][m][k];
}

int fun (int n, int m, int k)
{
	if (k == 0)
	{
		return 0;
	}
	if (n * m == k)
	{
		return 0;
	}
	if (n * m < k)
	{
		return INF;
	}
	int res = INF;
	foreach (p; 0..k + 1)
	{
		foreach (i; 1..n)
		{
			int cost = m * m;
			res = min (res, cost + mfun (i, m, p) +
			    mfun (n - i, m, k - p));
		}
		foreach (j; 1..m)
		{
			int cost = n * n;
			res = min (res, cost + mfun (n, j, p) +
			    mfun (n, m - j, k - p));
		}
	}
	return res;
}

void main ()
{
	f = new int [] [] [] (MAX_N, MAX_N, MAX_K);
	foreach (ref g; f)
	{
		foreach (ref h; g)
		{
			h[] = NA;
		}
	}

	int tests;
	readf (" %s", &tests);
	foreach (test; 0..tests)
	{
		int n, m, k;
		readf (" %s %s %s", &n, &m, &k);
		writeln (mfun (n, m, k));
	}
}