Eric has an array $$$b$$$ of length $$$m$$$, then he generates $$$n$$$ additional arrays $$$c_1, c_2, \dots, c_n$$$, each of length $$$m$$$, from the array $$$b$$$, by the following way:Initially, $$$c_i = b$$$ for every $$$1 \le i \le n$$$. Eric secretly chooses an integer $$$k$$$ $$$(1 \le k \le n)$$$ and chooses $$$c_k$$$ to be the special array.There are two operations that Eric can perform on an array $$$c_t$$$: Operation 1: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-1$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+1]$$$. That operation can only be used on a non-special array, that is when $$$t \neq k$$$.; Operation 2: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-2$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+2]$$$. That operation can only be used on a special array, that is when $$$t = k$$$.Note that Eric can't perform an operation if any element of the array will become less than $$$0$$$ after that operation.Now, Eric does the following:  For every non-special array $$$c_i$$$ ($$$i \neq k$$$), Eric uses only operation 1 on it at least once. For the special array $$$c_k$$$, Eric uses only operation 2 on it at least once.Lastly, Eric discards the array $$$b$$$.For given arrays $$$c_1, c_2, \dots, c_n$$$, your task is to find out the special array, i.e. the value $$$k$$$. Also, you need to find the number of times of operation $$$2$$$ was used on it.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$3 \leq n \leq 10^5$$$, $$$7 \leq m \leq 3 \cdot 10^5$$$) — the number of arrays given to you, and the length of each array. The next $$$n$$$ lines contains $$$m$$$ integers each, $$$c_{i,1}, c_{i,2}, \dots , c_{i,m}$$$. It is guaranteed that each element of the discarded array $$$b$$$ is in the range $$$[0,10^6]$$$, and therefore $$$0 \leq c_{i,j} \leq 3 \cdot 10^{11}$$$ for all possible pairs of $$$(i,j)$$$. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. It is guaranteed that the input is generated according to the procedure above.

For each test case, output one line containing two integers — the index of the special array, and the number of times that Operation 2 was performed on it. It can be shown that under the constraints given in the problem, this value is unique and won't exceed $$$10^{18}$$$, so you can represent it as a $$$64$$$-bit integer. It can also be shown that the index of the special array is uniquely determined. In this problem, hacks are disabled.

NoteIn the first test case, the secret array $$$b$$$ is $$$[0, 1, 1, 1, 1, 1, 1, 1, 0]$$$. Array $$$c_1$$$ and array $$$c_2$$$ are generated by using operation 1. Array $$$c_3$$$ is generated by using operation 2.For Array $$$c_1$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 1 one time to generate it. For Array $$$c_2$$$, you can choose $$$i=6$$$ and $$$j=7$$$ perform Operation 1 one time to generate it. For Array $$$c_3$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 2 one time to generate it.In the second test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.In the third test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.

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 n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto c = new long [] [n];
		auto w = new long [n];
		foreach (i; 0..n)
		{
			c[i] = readln.splitter.map !(to !(long)).array;
			foreach (j; 0..m)
			{
				w[i] += c[i][j] * j;
			}
		}
		auto p = w.length - w.maxPos.length;
		writeln (p + 1, " ", w[p] - w[!p]);
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const N = readInt;
        const M = readInt;
        auto C = new long[][](N, M);
        foreach (i; 0 .. N) {
          foreach (j; 0 .. M) {
            C[i][j] = readLong;
          }
        }

        auto fs = new long[N];
        foreach (i; 0 .. N) {
          foreach (j; 0 .. M) {
            fs[i] += j * C[i][j];
          }
        }
        debug {
          writeln("fs = ", fs);
        }
        const minF = fs.minElement;
        const maxF = fs.maxElement;

        int im = -1;
        foreach (i; 0 .. N) {
          if (maxF == fs[i]) {
            im = i;
            break;
          }
        }
        writeln(im + 1, " ", maxF - minF);
      }
    }
  } catch (EOFException e) {
  }
}

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 n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto c = new int [] [n];
		auto w = new long [n];
		foreach (i; 0..n)
		{
			c[i] = readln.splitter.map !(to !(int)).array;
			foreach (j; 0..m)
			{
				w[i] += c[i][j] * j;
			}
		}
		auto p = w.length - w.maxPos.length;
		writeln (p + 1, " ", w[p] - w[!p]);
	}
}


Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble.There is a set $$$S$$$ containing very important numbers on his dad's desk. The minute Johnny heard about it, he decided that it's a good idea to choose a positive integer $$$k$$$ and replace each element $$$s$$$ of the set $$$S$$$ with $$$s \oplus k$$$ ($$$\oplus$$$ denotes the exclusive or operation). Help him choose such $$$k$$$ that Johnny's dad will not see any difference after his son is done playing (i.e. Johnny will get the same set as before playing). It is possible that no such number exists. It is also possible that there are many of them. In such a case, output the smallest one. Note that the order of elements in a set doesn't matter, i.e. set $$$\{1, 2, 3\}$$$ equals to set $$$\{2, 1, 3\}$$$.Formally, find the smallest positive integer $$$k$$$ such that $$$\{s \oplus k | s \in S\} = S$$$ or report that there is no such number.For example, if $$$S = \{1, 3, 4\}$$$ and $$$k = 2$$$, new set will be equal to $$$\{3, 1, 6\}$$$. If $$$S = \{0, 1, 2, 3\}$$$ and $$$k = 1$$$, after playing set will stay the same.

In the first line of input, there is a single integer $$$t$$$ ($$$1 \leq t \leq 1024$$$), the number of test cases. In the next lines, $$$t$$$ test cases follow. Each of them consists of two lines.  In the first line there is a single integer $$$n$$$ ($$$1 \leq n \leq 1024$$$) denoting the number of elements in set $$$S$$$. Second line consists of $$$n$$$ distinct integers $$$s_i$$$ ($$$0 \leq s_i < 1024$$$), elements of $$$S$$$. It is guaranteed that the sum of $$$n$$$ over all test cases will not exceed $$$1024$$$.

Print $$$t$$$ lines; $$$i$$$-th line should contain the answer to the $$$i$$$-th test case, the minimal positive integer $$$k$$$ satisfying the conditions or $$$-1$$$ if no such $$$k$$$ exists.

NoteIn the first test case, the answer is $$$1$$$ because it is a minimum positive integer and it satisfies all the conditions.

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

void main () {
	foreach (t; 0..readln.strip.to!int) {
		int n = readln.strip.to!int, v;
		auto a = readln.splitter.map !(to!int).array;
		a.sort;
		for (v = 1; v < 1024; v++) {
			auto b = a.dup;
			b[] ^= v;
			b.sort;
			if (a == b) break;
		}
		if (v == 1024) v = -1;
		v.writeln;
	}
}

import std.stdio;
import std.stdio;
import std.algorithm;
import std.range;
import std.functional;
import std.conv;
import std.string;
import std.math;
import core.bitop;

ulong[] arr;
ulong[] clone;

bool check(ulong k) { // O(3n + n log n)
	foreach (i, v; arr) { // O(n)
		clone[i] = v;
	}
	foreach (ref v; clone) { // O(n)
		v ^= k;
	}
	clone.sort(); // O(n log n)
	return clone == arr; // O(n)
}

void main() {
	int tt = readln().chomp.to!int;
	outer: foreach (t; 0 .. tt) {
		size_t n = readln().chomp.to!size_t;
		arr = readln().chomp.split(" ").map!(to!ulong).array;
		arr.sort();
		clone.length = arr.length;
		// 1026 * (3 * 1024 + 1024 log 1024)
		foreach (k; 1 .. 1026) {
			if (check(k)) {
				writeln(k);
				continue outer;
			}
		}
		writeln(-1);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] = -1;
		foreach (i; 1..2^^10)
		{
			auto cnt = new int[](2^^10);
			foreach (j; 0..n)
			{
				++cnt[s[j]];
			}
			foreach (j; 0..n)
			{
				auto num = s[j] ^ i;
				--cnt[num];
			}
			bool ok = true;
			foreach (j; 0..2^^10)
			{
				if (cnt[j] != 0)
				{
					ok = false;
					break;
				}
			}
			if (ok)
			{
				ans[ti] = i;
				break;
			}
		}
	}

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


You are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height $$$h$$$, and there is a moving platform on each height $$$x$$$ from $$$1$$$ to $$$h$$$.Each platform is either hidden inside the cliff or moved out. At first, there are $$$n$$$ moved out platforms on heights $$$p_1, p_2, \dots, p_n$$$. The platform on height $$$h$$$ is moved out (and the character is initially standing there).If you character is standing on some moved out platform on height $$$x$$$, then he can pull a special lever, which switches the state of two platforms: on height $$$x$$$ and $$$x - 1$$$. In other words, the platform you are currently standing on will hide in the cliff and the platform one unit below will change it state: it will hide if it was moved out or move out if it was hidden. In the second case, you will safely land on it. Note that this is the only way to move from one platform to another.Your character is quite fragile, so it can safely fall from the height no more than $$$2$$$. In other words falling from the platform $$$x$$$ to platform $$$x - 2$$$ is okay, but falling from $$$x$$$ to $$$x - 3$$$ (or lower) is certain death. Sometimes it's not possible to come down from the cliff, but you can always buy (for donate currency) several magic crystals. Each magic crystal can be used to change the state of any single platform (except platform on height $$$h$$$, which is unaffected by the crystals). After being used, the crystal disappears.What is the minimum number of magic crystal you need to buy to safely land on the $$$0$$$ ground level?

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Each query contains two lines and is independent of all other queries. The first line of each query contains two integers $$$h$$$ and $$$n$$$ ($$$1 \le h \le 10^9$$$, $$$1 \le n \le \min(h, 2 \cdot 10^5)$$$) — the height of the cliff and the number of moved out platforms. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$h = p_1 > p_2 > \dots > p_n \ge 1$$$) — the corresponding moved out platforms in the descending order of their heights. The sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.

For each query print one integer — the minimum number of magic crystals you have to spend to safely come down on the ground level (with height $$$0$$$).

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);
	foreach (i; 0..q)
	{
		auto h = RD;
		auto n = RD!int;
		auto p = RDA;
		long last = h;
		long score;
		foreach (j; 1..n)
		{
			auto d = last - p[j];
			if (d == 0)
			{
				--score;
			}
			else
			{
				last = p[j] - 1;
				++score;
			}
		}
		if (last == 0) --score;
		ans[i] = score;
	}

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

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);
	foreach (i; 0..q)
	{
		auto h = RD;
		auto n = RD!int;
		auto p = RDA;
		long last = h;
		long score;
		foreach (j; 1..n)
		{
			auto d = last - p[j];
			if (d == 0)
			{
				--score;
			}
			else
			{
				last = p[j] - 1;
				++score;
			}
		}
		if (last == 0) --score;
		score += (last-1) / 2;
		ans[i] = score;
	}

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

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);
	foreach (i; 0..q)
	{
		auto h = RD;
		auto n = RD!int;
		auto p = RDA;
		long last = h;
		long score;
		foreach (j; 1..n)
		{
			auto d = last - p[j];
			if (d == 0)
			{
				--score;
			}
			else
			{
				last = p[j] - 1;
				++score;
			}
			debug writeln("last:", last);
		}
		if (last == 0)
			--score;
		else
			score += (last-1) / 2;
		ans[i] = max(0, score);
	}

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

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);
	foreach (i; 0..q)
	{
		auto h = RD;
		auto n = RD!int;
		auto p = RDA;
		auto dp = new long[][][](n, 2, 2);
		foreach (j; 0..n)
		{
			dp[j][0][1] = long.max;
			dp[j][1][1] = long.max;
		}
		dp[0][0] = [h, 0];
		dp[0][1] = [h, 0];
		foreach (j; 1..n)
		{
			foreach (k; 0..2)
			{
				auto last = dp[j-1][k][0];
				auto score = dp[j-1][k][1];
				auto d = last - p[j];
				if (d == 0)
				{
					if (dp[j-1][k][1]-1 < dp[j][0][1])
					{
						dp[j][0][0] = dp[j-1][k][0];
						dp[j][0][1] = dp[j-1][k][1]-1;
					}
				}
				else
				{
					auto last1 = p[j] - 1;
					auto last2 = p[j];
					if (dp[j-1][k][1]+1 < dp[j][0][1])
					{
						dp[j][0][0] = last1;
						dp[j][0][1] = dp[j-1][k][1]+1;
					}
					if (dp[j-1][k][1]+1 < dp[j][1][1])
					{
						dp[j][1][0] = last2;
						dp[j][1][1] = dp[j-1][k][1]+1;
					}
				}
			}
		}
		foreach (j; 0..2)
		{
			if (dp[n-1][j][0] == 0)
				--dp[n-1][j][1];
			else
				dp[n-1][j][1] += (dp[n-1][j][0]-1) / 2;
		}
		if (dp[n-1][0][1] < dp[n-1][1][1])
			ans[i] = dp[n-1][0][1];
		else
			ans[i] = dp[n-1][1][1];
	}

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

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

string FMT_F = "%.10f";

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

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

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

void main()
{
	auto q = RD!int;
	auto ans = new long[](q);
	foreach (i; 0..q)
	{
		auto h = RD;
		auto n = RD!int;
		auto p = RDA;
		auto dp = new long[][][](n, 2, 2);
		foreach (j; 0..n)
		{
			dp[j][0][1] = long.max;
			dp[j][1][1] = long.max;
		}
		dp[0][0] = [h, 0];
		dp[0][1] = [h, 0];
		foreach (j; 1..n)
		{
			foreach (k; 0..2)
			{
				auto last = dp[j-1][k][0];
				auto score = dp[j-1][k][1];
				auto d = last - p[j];
				if (d == 0)
				{
					dp[j][k] = dp[j-1][k];
					--dp[j][k][1];
				}
				else
				{
					auto last1 = p[j] - 1;
					auto last2 = p[j];
					if (dp[j-1][k][1]+1 < dp[j][0][1])
					{
						dp[j][0][0] = last1;
						dp[j][0][1] = dp[j-1][k][1]+1;
					}
					if (dp[j-1][k][1]+1 < dp[j][1][1])
					{
						dp[j][1][0] = last2;
						dp[j][1][1] = dp[j-1][k][1]+1;
					}
				}
			}
		}
		foreach (j; 0..2)
		{
			if (dp[n-1][j][0] == 0)
				--dp[n-1][j][1];
			else
				dp[n-1][j][1] += (dp[n-1][j][0]-1) / 2;
		}
		if (dp[n-1][0][1] < dp[n-1][1][1])
			ans[i] = dp[n-1][0][1];
		else
			ans[i] = dp[n-1][1][1];
	}

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


You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that .

The first line contains integer n (1 ≤ n ≤ 5·105), showing how many numbers are in the array. The second line contains n integers a[1], a[2], ..., a[n] (|a[i]| ≤  109) — the elements of array a.

Print a single integer — the number of ways to split the array into three parts with the same sum.

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

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

    if (A.sum % 3 != 0) {
        writeln(0);
        return;
    }

    auto ave = A.sum / 3;

    auto acm_f = new long[](N);
    acm_f[0] = A[0];
    auto acm_b = new long[](N);
    acm_b[N-1] = A[N-1];

    foreach (i; 0..N-1) {
        acm_f[i+1] = acm_f[i] + A[i+1];
        acm_b[N-i-2] = acm_b[N-i-1] + A[N-i-2];
    }

    int[] f;
    int[] b;
    foreach (i; 0..N) {
        if (acm_f[i] == ave) f ~= i;
        if (acm_b[i] == ave) b ~= i;
    }

    auto B = b.assumeSorted;
    long ans = 0;

    foreach (i; f) {
        ans += B.upperBound(i+1).length;
    }

    ans.writeln;
}

module main;

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

class XD
{
    public:
        this(int n)
        {
            len = n << 4;
            h = new int[][len];
            f = new bool[len];
            v = new long[len];
        }
        int getPosition(long n)
        {
            auto s = to!string(n);
            int pos = calc(s);
            while (f[pos] == true && v[pos] != n)
            {
                ++ pos;
                if (pos == len)
                {
                    pos = 0;
                }
            }
            return pos;
        }
        void insert(long n, int idx)
        {
            auto pos = getPosition(n);
            //writefln("%d %d", pos, n);
            v[pos] = n;
            f[pos] = true;
            h[pos] ~= idx;
        }
        int[] find(long n)
        {
            auto pos = getPosition(n);
            return h[pos];
        }
        int calc(string s)
        {
            long hash = 0;
            foreach (i, val; s)
            {
                hash = (hash << 4) ^ (hash >> 28) ^ val;
            }
            return (hash % len);
        }
    protected:
        int len;
        long[] v;
        bool[] f;
        int[][] h;
};

int search(int[] a, int bound)
{
    int left = 0, right = a.length - 1, mid, res = 0;
    while (left <= right)
    {
        mid = (left + right) >> 1;
        if (a[mid] >= bound)
        {
            right = mid - 1;
        }
        else
        {
            res = mid + 1;
            left = mid + 1;
        }
    }
    //writefln("%d %d", bound, res);
    return res;
}

void solve(int[] a)
{
    XD xd = new XD(a.length);
    auto s = new long[a.length];
    s[0] = a[0];
    xd.insert(s[0], 0);
    foreach (i; 1 .. a.length)
    {
        s[i] = a[i] + s[i - 1];
        xd.insert(s[i], i);
    }
    long ans = 0;
    foreach (i; 2 .. a.length)
    {
        long sum = s[a.length - 1] - s[i - 1];
        if ((s[i - 1] & 1) == 0 && s[i - 1] / 2 == sum)
        {
            auto arr = xd.find(sum);
            //foreach (j, val; arr) writef("%d ", val);
            //writeln();
            ans += search(arr, i - 1);
        }
    }
    writefln("%d", ans);
}

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

module main;

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

class XD
{
    public:
        this(int n)
        {
            len = n << 3;
            h = new int[][len];
            f = new bool[len];
            v = new long[len];
        }
        int getPosition(long n)
        {
            auto s = to!string(n);
            int pos = calc(s);
            while (f[pos] == true && v[pos] != n)
            {
                ++ pos;
                if (pos == len)
                {
                    pos = 0;
                }
            }
            return pos;
        }
        void insert(long n, int idx)
        {
            auto pos = getPosition(n);
            //writefln("%d %d", pos, n);
            v[pos] = n;
            f[pos] = true;
            h[pos] ~= idx;
        }
        int[] find(long n)
        {
            auto pos = getPosition(n);
            return h[pos];
        }
        int calc(string s)
        {
            long hash = 0;
            foreach (i, val; s)
            {
                hash = (hash << 4) ^ (hash >> 28) ^ val;
            }
            return (hash % len);
        }
    protected:
        int len;
        long[] v;
        bool[] f;
        int[][] h;
};

int search(int[] a, int bound)
{
    int left = 0, right = a.length - 1, mid, res = 0;
    while (left <= right)
    {
        mid = (left + right) >> 1;
        if (a[mid] >= bound)
        {
            right = mid - 1;
        }
        else
        {
            res = mid + 1;
            left = mid + 1;
        }
    }
    //writefln("%d %d", bound, res);
    return res;
}

void solve(int[] a)
{
    XD xd = new XD(a.length);
    auto s = new long[a.length];
    s[0] = a[0];
    xd.insert(s[0], 0);
    foreach (i; 1 .. a.length)
    {
        s[i] = a[i] + s[i - 1];
        xd.insert(s[i], i);
    }
    long ans = 0;
    foreach (i; 2 .. a.length)
    {
        long sum = s[a.length - 1] - s[i - 1];
        if ((s[i - 1] & 1) == 0 && s[i - 1] / 2 == sum)
        {
            auto arr = xd.find(sum);
            //foreach (j, val; arr) writef("%d ", val);
            //writeln();
            ans += search(arr, i - 1);
        }
    }
    writefln("%d", ans);
}

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

module main;

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

class XD
{
    public:
        this(int n)
        {
            len = n;
            h = new int[][len];
            f = new bool[len];
            v = new long[len];
        }
        int getPosition(long n)
        {
            auto s = to!string(n);
            int pos = calc(s);
            while (f[pos] == true && v[pos] != n)
            {
                ++ pos;
                if (pos == len)
                {
                    pos = 0;
                }
            }
            return pos;
        }
        void insert(long n, int idx)
        {
            auto pos = getPosition(n);
            //writefln("%d %d", pos, n);
            v[pos] = n;
            f[pos] = true;
            h[pos] ~= idx;
        }
        int[] find(long n)
        {
            auto pos = getPosition(n);
            return h[pos];
        }
        int calc(string s)
        {
            long hash = 0;
            foreach (i, val; s)
            {
                hash = (hash << 4) ^ (hash >> 28) ^ val;
            }
            return (hash % len);
        }
    protected:
        int len;
        long[] v;
        bool[] f;
        int[][] h;
};

int search(int[] a, int bound)
{
    int left = 0, right = a.length - 1, mid, res = 0;
    while (left <= right)
    {
        mid = (left + right) >> 1;
        if (a[mid] >= bound)
        {
            right = mid - 1;
        }
        else
        {
            res = mid + 1;
            left = mid + 1;
        }
    }
    //writefln("%d %d", bound, res);
    return res;
}

void solve(int[] a)
{
    XD xd = new XD(a.length);
    auto s = new long[a.length];
    s[0] = a[0];
    xd.insert(s[0], 0);
    foreach (i; 1 .. a.length)
    {
        s[i] = a[i] + s[i - 1];
        xd.insert(s[i], i);
    }
    long ans = 0;
    foreach (i; 2 .. a.length)
    {
        long sum = s[a.length - 1] - s[i - 1];
        if ((s[i - 1] & 1) == 0 && s[i - 1] / 2 == sum)
        {
            auto arr = xd.find(sum);
            //foreach (j, val; arr) writef("%d ", val);
            //writeln();
            ans += search(arr, i - 1);
        }
    }
    writefln("%d", ans);
}

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

module main;

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

class XD
{
    public:
        this(int n)
        {
            len = n << 2;
            h = new int[][len];
            f = new bool[len];
            v = new long[len];
        }
        int getPosition(long n)
        {
            auto s = to!string(n);
            int pos = calc(s);
            while (f[pos] == true && v[pos] != n)
            {
                ++ pos;
                if (pos == len)
                {
                    pos = 0;
                }
            }
            return pos;
        }
        void insert(long n, int idx)
        {
            auto pos = getPosition(n);
            //writefln("%d %d", pos, n);
            v[pos] = n;
            f[pos] = true;
            h[pos] ~= idx;
        }
        int[] find(long n)
        {
            auto pos = getPosition(n);
            return h[pos];
        }
        int calc(string s)
        {
            long hash = 0;
            foreach (i, val; s)
            {
                hash = (hash << 4) ^ (hash >> 28) ^ val;
            }
            return (hash % len);
        }
    protected:
        int len;
        long[] v;
        bool[] f;
        int[][] h;
};

int search(int[] a, int bound)
{
    int left = 0, right = a.length - 1, mid, res = 0;
    while (left <= right)
    {
        mid = (left + right) >> 1;
        if (a[mid] >= bound)
        {
            right = mid - 1;
        }
        else
        {
            res = mid + 1;
            left = mid + 1;
        }
    }
    //writefln("%d %d", bound, res);
    return res;
}

void solve(int[] a)
{
    XD xd = new XD(a.length);
    auto s = new long[a.length];
    s[0] = a[0];
    xd.insert(s[0], 0);
    foreach (i; 1 .. a.length)
    {
        s[i] = a[i] + s[i - 1];
        xd.insert(s[i], i);
    }
    long ans = 0;
    foreach (i; 2 .. a.length)
    {
        long sum = s[a.length - 1] - s[i - 1];
        if ((s[i - 1] & 1) == 0 && s[i - 1] / 2 == sum)
        {
            auto arr = xd.find(sum);
            //foreach (j, val; arr) writef("%d ", val);
            //writeln();
            ans += search(arr, i - 1);
        }
    }
    writefln("%d", ans);
}

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

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

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

    if (A.sum % 3 != 0) {
        writeln(0);
        return;
    }

    auto ave = A.sum / 3;

    auto acm_f = new int[](N);
    acm_f[0] = A[0];
    auto acm_b = new int[](N);
    acm_b[N-1] = A[N-1];

    foreach (i; 0..N-1) {
        acm_f[i+1] = acm_f[i] + A[i+1];
        acm_b[N-i-2] = acm_b[N-i-1] + A[N-i-2];
    }

    int[] f;
    int[] b;
    foreach (i; 0..N) {
        if (acm_f[i] == ave) f ~= i;
        if (acm_b[i] == ave) b ~= i;
    }

    auto B = b.assumeSorted;
    long ans = 0;

    foreach (i; f) {
        ans += B.upperBound(i+1).length;
    }

    ans.writeln;
}

module main;

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

class XD
{
    public:
        this(int n)
        {
            len = n << 3;
            h = new int[][n << 3];
            f = new bool[n << 3];
            v = new long[n << 3];
        }
        int getPosition(long n)
        {
            auto s = to!string(n);
            int pos = calc(s);
            while (f[pos] == true && v[pos] != n)
            {
                ++ pos;
                if (pos == len)
                {
                    pos = 0;
                }
            }
            return pos;
        }
        void insert(long n, int idx)
        {
            auto pos = getPosition(n);
            v[pos] = n;
            f[pos] = true;
            h[pos] ~= idx;
        }
        int[] find(long n)
        {
            auto pos = getPosition(n);
            return h[pos];
        }
        int calc(string s)
        {
            long hash = 0;
            foreach (i, val; s)
            {
                hash = (hash << 4) ^ (hash >> 28) ^ val;
            }
            return (hash % len);
        }
    protected:
        int len;
        long[] v;
        bool[] f;
        int[][] h;
};

int search(int[] a, int bound)
{
    int left = 0, right = a.length - 1, mid, res = 0;
    while (left <= right)
    {
        mid = (left + right) >> 1;
        if (a[mid] >= bound)
        {
            right = mid - 1;
        }
        else
        {
            res = mid - left + 1;
            left = mid + 1;
        }
    }
    return res;
}

void solve(int[] a)
{
    XD xd = new XD(a.length);
    auto s = new long[a.length];
    s[0] = a[0];
    xd.insert(s[0], 0);
    foreach (i; 1 .. a.length)
    {
        s[i] = a[i] + s[i - 1];
        xd.insert(s[i], i);
    }
    long ans = 0;
    foreach (i; 2 .. a.length)
    {
        long sum = s[a.length - 1] - s[i - 1];
        if ((s[i - 1] & 1) == 0 && s[i - 1] / 2 == sum)
        {
            auto arr = xd.find(sum);
            ans += search(arr, i - 1);
        }
    }
    writefln("%d", ans);
}

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

module main;

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

class XD
{
    public:
        this(int n)
        {
            len = n;
            h = new int[][n << 3];
            f = new bool[n << 3];
            v = new long[n << 3];
        }
        int getPosition(long n)
        {
            auto s = to!string(n);
            int pos = calc(s);
            while (f[pos] == true && v[pos] != n)
            {
                ++ pos;
                if (pos == len)
                {
                    pos = 0;
                }
            }
            return pos;
        }
        void insert(long n, int idx)
        {
            auto pos = getPosition(n);
            v[pos] = n;
            f[pos] = true;
            h[pos] ~= idx;
        }
        int[] find(long n)
        {
            auto pos = getPosition(n);
            return h[pos];
        }
        int calc(string s)
        {
            long hash = 0;
            foreach (i, val; s)
            {
                hash = (hash << 4) ^ (hash >> 28) ^ val;
            }
            return (hash % len);
        }
    protected:
        int len;
        long[] v;
        bool[] f;
        int[][] h;
};

int search(int[] a, int bound)
{
    int left = 0, right = a.length - 1, mid, res = 0;
    while (left <= right)
    {
        mid = (left + right) >> 1;
        if (a[mid] >= bound)
        {
            right = mid - 1;
        }
        else
        {
            res = mid - left + 1;
            left = mid + 1;
        }
    }
    return res;
}

void solve(int[] a)
{
    XD xd = new XD(a.length);
    auto s = new long[a.length];
    s[0] = a[0];
    xd.insert(s[0], 0);
    foreach (i; 1 .. a.length)
    {
        s[i] = a[i] + s[i - 1];
        xd.insert(s[i], i);
    }
    long ans = 0;
    foreach (i; 2 .. a.length)
    {
        long sum = s[a.length - 1] - s[i - 1];
        auto arr = xd.find(sum);
        ans += search(arr, i - 1);
    }
    writefln("%d", ans);
}

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

module main;

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

class XD
{
    public:
        this(int n)
        {
            len = n;
            h = new int[][n << 3];
            f = new bool[n << 3];
            v = new long[n << 3];
        }
        int getPosition(long n)
        {
            auto s = to!string(n);
            int pos = calc(s);
            while (f[pos] == true && v[pos] != n)
            {
                ++ pos;
                if (pos == len)
                {
                    pos = 0;
                }
            }
            return pos;
        }
        void insert(long n, int idx)
        {
            auto pos = getPosition(n);
            v[pos] = n;
            f[pos] = true;
            h[pos] ~= idx;
        }
        int[] find(long n)
        {
            auto pos = getPosition(n);
            return h[pos];
        }
        int calc(string s)
        {
            long hash = 0;
            foreach (i, val; s)
            {
                hash = (hash << 4) ^ (hash >> 28) ^ val;
            }
            return (hash % len);
        }
    protected:
        int len;
        long[] v;
        bool[] f;
        int[][] h;
};

int search(int[] a, int bound)
{
    int left = 0, right = a.length - 1, mid, res = 0;
    while (left <= right)
    {
        mid = (left + right) >> 1;
        if (a[mid] >= bound)
        {
            right = mid - 1;
        }
        else
        {
            res = mid - left + 1;
            left = mid + 1;
        }
    }
    return res;
}

void solve(int[] a)
{
    XD xd = new XD(a.length);
    auto s = new long[a.length];
    s[0] = a[0];
    xd.insert(s[0], 0);
    foreach (i; 1 .. a.length)
    {
        s[i] = a[i] + s[i - 1];
        xd.insert(s[i], i);
    }
    long ans = 0;
    foreach (i; 2 .. a.length)
    {
        long sum = s[a.length - 1] - s[i - 1];
        if (s[i - 1] / 2 == sum)
        {
            auto arr = xd.find(sum);
            ans += search(arr, i - 1);
        }
    }
    writefln("%d", ans);
}

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


You are given a tree with each vertex coloured white, black or grey. You can remove elements from the tree by selecting a subset of vertices in a single connected component and removing them and their adjacent edges from the graph. The only restriction is that you are not allowed to select a subset containing a white and a black vertex at once.What is the minimum number of removals necessary to remove all vertices from the tree?

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100\,000$$$), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 200\,000$$$): the number of vertices in the tree. The second line of each test case contains $$$n$$$ integers $$$a_v$$$ ($$$0 \le a_v \le 2$$$): colours of vertices. Gray vertices have $$$a_v=0$$$, white have $$$a_v=1$$$, black have $$$a_v=2$$$. Each of the next $$$n-1$$$ lines contains two integers $$$u, v$$$ ($$$1 \le u, v \le n$$$): tree edges. The sum of all $$$n$$$ throughout the test is guaranteed to not exceed $$$200\,000$$$.

For each test case, print one integer: the minimum number of operations to solve the problem.

NoteIn the first test case, both vertices are white, so you can remove them at the same time.In the second test case, three operations are enough. First, we need to remove both black vertices (2 and 4), then separately remove vertices 1 and 3. We can't remove them together because they end up in different connectivity components after vertex 2 is removed.In the third test case, we can remove vertices 1, 2, 3, 4 at the same time, because three of them are white and one is grey. After that, we can remove vertex 5.In the fourth test case, three operations are enough. One of the ways to solve the problem is to remove all black vertices at once, then remove white vertex 7, and finally, remove connected white vertices 1 and 3.

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

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

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

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

int N;
int[] C;
int[] A, B;

int[][] G;
int[] par;
int[2][] dp, DP;

void dfs(int u, int p) {
  par[u] = p;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
    }
  }
  // init
  int[2] mx;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      // add dp[v]
      foreach (s; 0 .. 2) {
        chmax(mx[s], dp[v][s]);
      }
    }
  }
  // calc dp[u]
  dp[u] = mx;
  if (C[u] != -1) {
    chmax(dp[u][C[u]], mx[C[u] ^ 1] + 1);
  }
}

void DFS(int u, int p) {
  // init
  alias Entry = Tuple!(int, "val", int, "key");
  Entry[2][2] mxs;
  foreach (s; 0 .. 2) {
    mxs[s][] = Entry(0, -1);
  }
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      // add dp[v]
      foreach (s; 0 .. 2) {
        Entry tmp = Entry(dp[v][s], v);
        foreach (k; 0 .. 2) {
          if (mxs[s][k] < tmp) {
            swap(mxs[s][k], tmp);
          }
        }
      }
    }
  }
  if (p != -1) {
    // add DP[u]
    foreach (s; 0 .. 2) {
      Entry tmp = Entry(DP[u][s], u);
      foreach (k; 0 .. 2) {
        if (mxs[s][k] < tmp) {
          swap(mxs[s][k], tmp);
        }
      }
    }
  }
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      // calc DP[v], removing dp[v]
      int[2] mx;
      foreach (s; 0 .. 2) {
        foreach (k; 0 .. 2) {
          if (mxs[s][k].key != v) {
            chmax(mx[s], mxs[s][k].val);
          }
        }
      }
      DP[v] = mx;
      if (C[u] != -1) {
        chmax(DP[v][C[u]], mx[C[u] ^ 1] + 1);
      }
    }
  }
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      DFS(v, u);
    }
  }
}

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

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

        const rt = 0;
        par = new int[N];
        dp = new int[2][N];
        dfs(rt, -1);
        DP = new int[2][N];
        DFS(rt, -1);
        debug {
          writeln("rt = ", rt);
          writeln("dp = ", dp);
          writeln("DP = ", DP);
        }
        int ans;
        foreach (u; 0 .. N) {
          // init
          int[2] mx;
          foreach (i; G[u]) {
            const v = A[i] ^ B[i] ^ u;
            if (v != par[u]) {
              // add dp[v]
              foreach (s; 0 .. 2) {
                chmax(mx[s], dp[v][s]);
              }
            }
          }
          if (u != rt) {
            // add DP[u]
            foreach (s; 0 .. 2) {
              chmax(mx[s], DP[u][s]);
            }
          }
          // calc ans, rooted at u
          foreach (s; 0 .. 2) {
            chmax(ans, mx[s]);
          }
          if (C[u] != -1) {
            chmax(ans, mx[C[u] ^ 1] + 1);
          }
        }

        ans = ans / 2 + 1;
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


Grigory loves strings. Recently he found a metal strip on a loft. The strip had length n and consisted of letters "V" and "K". Unfortunately, rust has eaten some of the letters so that it's now impossible to understand which letter was written.Grigory couldn't understand for a long time what these letters remind him of, so he became interested in the following question: if we put a letter "V" or "K" on each unreadable position, which values can the period of the resulting string be equal to?A period of a string is such an integer d from 1 to the length of the string that if we put the string shifted by d positions to the right on itself, then all overlapping letters coincide. For example, 3 and 5 are periods of "VKKVK".

There are several (at least one) test cases in the input. The first line contains single integer — the number of test cases. There is an empty line before each test case. Each test case is described in two lines: the first line contains single integer n (1 ≤ n ≤ 5·105) — the length of the string, the second line contains the string of length n, consisting of letters "V", "K" and characters "?". The latter means the letter on its position is unreadable. It is guaranteed that the sum of lengths among all test cases doesn't exceed 5·105. For hacks you can only use tests with one test case.

For each test case print two lines. In the first line print the number of possible periods after we replace each unreadable letter with "V" or "K". In the next line print all these values in increasing order.

NoteIn the first test case from example we can obtain, for example, "VKKVK", which has periods 3 and 5.In the second test case we can obtain "VVVVVV" which has all periods from 1 to 6.In the third test case string "KVKV" has periods 2 and 4, and string "KVKK" has periods 3 and 4.

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

// M: prime, G: primitive root
class Fft(int M_, int G, int K) {
  import std.algorithm : reverse;
  import std.traits : isIntegral;
  alias M = M_;
  // 1, 1/4, 1/8, 3/8, 1/16, 5/16, 3/16, 7/16, ...
  int[] gs;
  this() {
    static assert(2 <= K && K <= 30, "Fft: 2 <= K <= 30 must hold");
    static assert(!((M - 1) & ((1 << K) - 1)), "Fft: 2^K | M - 1 must hold");
    gs = new int[1 << (K - 1)];
    gs[0] = 1;
    long g2 = G, gg = 1;
    for (int e = (M - 1) >> K; e; e >>= 1) {
      if (e & 1) gg = (gg * g2) % M;
      g2 = (g2 * g2) % M;
    }
    gs[1 << (K - 2)] = cast(int)(gg);
    for (int l = 1 << (K - 2); l >= 2; l >>= 1) {
      gs[l >> 1] = cast(int)((cast(long)(gs[l]) * gs[l]) % M);
    }
    assert((cast(long)(gs[1]) * gs[1]) % M == M - 1,
           "Fft: g^(2^(K-1)) == -1 (mod M) must hold");
    for (int l = 2; l <= 1 << (K - 2); l <<= 1) {
      foreach (i; 1 .. l) {
        gs[l + i] = cast(int)((cast(long)(gs[l]) * gs[i]) % M);
      }
    }
  }
  void fft(int[] xs) const {
    const n = cast(int)(xs.length);
    assert(!(n & (n - 1)), "Fft.fft: |xs| must be a power of two");
    assert(n <= 1 << K, "Fft.fft: |xs| <= 2^K must hold");
    for (int l = n; l >>= 1; ) {
      foreach (i; 0 .. (n >> 1) / l) {
        const(long) g = gs[i];
        foreach (j; (i << 1) * l .. (i << 1 | 1) * l) {
          const t = cast(int)((g * xs[j + l]) % M);
          if ((xs[j + l] = xs[j] - t) < 0) xs[j + l] += M;
          if ((xs[j] += t) >= M) xs[j] -= M;
        }
      }
    }
  }
  void invFft(int[] xs) const {
    const n = cast(int)(xs.length);
    assert(!(n & (n - 1)), "Fft.invFft: |xs| must be a power of two");
    assert(n <= 1 << K, "Fft.invFft: |xs| <= 2^K must hold");
    for (int l = 1; l < n; l <<= 1) reverse(xs[l .. l << 1]);
    for (int l = 1; l < n; l <<= 1) {
      foreach (i; 0 .. (n >> 1) / l) {
        const(long) g = gs[i];
        foreach (j; (i << 1) * l .. (i << 1 | 1) * l) {
          int t = cast(int)((g * (xs[j] - xs[j + l])) % M);
          if (t < 0) t += M;
          if ((xs[j] += xs[j + l]) >= M) xs[j] -= M;
          xs[j + l] = t;
        }
      }
    }
  }
  T[] convolute(T)(inout(T)[] as, inout(T)[] bs) const if (isIntegral!T) {
    const na = cast(int)(as.length), nb = cast(int)(bs.length);
    int n, invN = 1;
    for (n = 1; n < na + nb - 1; n <<= 1) {
      invN = ((invN & 1) ? (invN + M) : invN) >> 1;
    }
    auto xs = new int[n], ys = new int[n];
    foreach (i; 0 .. na) if ((xs[i] = cast(int)(as[i] % M)) < 0) xs[i] += M;
    foreach (i; 0 .. nb) if ((ys[i] = cast(int)(bs[i] % M)) < 0) ys[i] += M;
    fft(xs);
    fft(ys);
    foreach (i; 0 .. n) {
      xs[i] = cast(int)((((cast(long)(xs[i]) * ys[i]) % M) * invN) % M);
    }
    invFft(xs);
    auto cs = new T[na + nb - 1];
    foreach (i; 0 .. na + nb - 1) cs[i] = cast(T)(xs[i]);
    return cs;
  }
}

alias Fft0 = Fft!(998244353, 3, 20);

void main() {
  const FFT = new Fft0;

  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const N = readInt();
        const S = readToken();

        auto fs = new int[N + 1];
        auto gs = new int[N + 1];
        foreach (i; 0 .. N) {
          switch (S[i]) {
            case 'V': ++fs[i]; break;
            case 'K': ++gs[N - i]; break;
            default: {}
          }
        }
        const hs = FFT.convolute(fs, gs);
        debug {
          writeln("hs = ", hs);
        }

        auto has = new bool[N + 1];
        foreach (x; -N .. +N + 1) {
          if (hs[N + x]) {
            has[abs(x)] = true;
          }
        }

        int[] ans;
        foreach (k; 1 .. N + 1) {
          bool ok = true;
          for (int l = k; l <= N; l += k) {
            ok = ok && !has[l];
          }
          if (ok) {
            ans ~= k;
          }
        }
        writeln(ans.length);
        foreach (index, k; ans) {
          if (index > 0) write(" ");
          write(k);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.complex, std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int tt;
	read(tt);
	auto a = new Complex!double[1 << 20], b = new Complex!double[1 << 20];
	auto ca = a.dup, cb = b.dup;
	auto d = new int[1 << 20];
	auto r = new int[500_000];
	Fft f = new Fft(1 << 20);
	string s;
	foreach (ii; 0 .. tt)
	{
		s = readln;
		int n;
		read(n);
		s = readln.strip;
		int st = 1;
		while (st <= n)
			st *= 2;
		st *= 2;
		auto z = Complex!double(0, 0);
		a[0 .. st] = z;
		b[0 .. st] = z;
		ca[0 .. st] = z;
		cb[0 .. st] = z;
		foreach (i; 0 .. n)
		{
			if (s[i] == 'V')
				a[i] = 1;
			else if (s[i] == 'K')
				b[n - 1 - i] = 1;
		}
		f.fft(a[0 .. st], ca[0 .. st]);
		f.fft(b[0 .. st], cb[0 .. st]);
		ca[0 .. st] *= cb[0 .. st];
		cb[0 .. st] = z;
		debug writeln(ca[0 .. st]);
		f.inverseFft(ca[0 .. st], cb[0 .. st]);
		foreach (i; 0 .. st)
		{
			d[i] = roundTo!int(cb[i].re);
		}
		r[n - 1] = d[n - 1];
		foreach (i; 1 .. n)
		{
			r[i] = d[n - 1 - i] + d[n - 1 + i];
		}
		int[] ans;
		foreach (i; 1 .. n)
		{
			bool flag = true;
			foreach (j; 1 .. (n - 1) / i + 1)
			{
				if (r[i * j])
				{
					flag = false;
					break;
				}
			}
			if (flag)
			{
				ans ~= i;
			}
		}
		ans ~= n;
		writeln(ans.length);
		foreach (x; ans)
		{
			write(x, ' ');
		}
		writeln;
	}
}

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.complex, std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int tt;
	read(tt);
	auto a = new Complex!double[1 << 20], b = new Complex!double[1 << 20];
	auto ca = a.dup, cb = b.dup;
	auto d = new int[1 << 20];
	auto r = new int[500_000];
	Fft f = new Fft(1 << 20);
	string s;
	foreach (ii; 0 .. tt)
	{
		s = readln;
		int n;
		read(n);
		s = readln.strip;
		int st = 1;
		while (st <= n)
			st *= 2;
		st *= 2;
		auto z = Complex!double(0, 0);
		a[0 .. st] = z;
		b[0 .. st] = z;
		ca[0 .. st] = z;
		cb[0 .. st] = z;
		foreach (i; 0 .. n)
		{
			if (s[i] == 'V')
				a[i] = 1;
			else if (s[i] == 'K')
				b[n - 1 - i] = 1;
		}
		f.fft(a[0 .. st], ca[0 .. st]);
		f.fft(b[0 .. st], cb[0 .. st]);
		ca[0 .. st] *= cb[0 .. st];
		cb[0 .. st] = z;
		debug writeln(ca[0 .. st]);
		f.inverseFft(ca[0 .. st], cb[0 .. st]);
		foreach (i; 0 .. st)
		{
			d[i] = roundTo!int(cb[i].re);
		}
		r[n - 1] = d[n - 1];
		foreach (i; 1 .. n)
		{
			r[i] = d[n - 1 - i] + d[n - 1 + i];
		}
		int[] ans;
		foreach (i; 1 .. n)
		{
			bool flag = true;
			foreach (j; 1 .. (n - 1) / i + 1)
			{
				if (r[i * j])
				{
					flag = false;
					break;
				}
			}
			if (flag)
			{
				ans ~= i;
			}
		}
		ans ~= n;
		writeln(ans.length);
		foreach (x; ans)
		{
			write(x, ' ');
		}
	}
}

import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.complex, std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
// alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///read without format
		bool input(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			return s == ptrs.length;
		}
		///readln without format
		bool read(T...)(ref T ptrs) if (ptrs.length > 0)
		{
			size_t s;
			foreach (ref e; ptrs)
			{
				if (isSomeChar!(Unqual!(typeof(e))))
					s += readf(" %c", &e);
				else
					s += readf(" %s", &e);
			}
			readln;
			return s == ptrs.length;
		}
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------
void main()
{
	version (home)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	int tt;
	read(tt);
	auto a = new Complex!double[1 << 20], b = new Complex!double[1 << 20];
	auto ca = a.dup, cb = b.dup;
	auto d = new int[1 << 20];
	auto r = new int[500_000];
	Fft f = new Fft(1 << 20);
	foreach (ii; 0 .. tt)
	{
		auto s = readln;
		int n;
		read(n);
		s = readln.strip;
		int st = 1;
		while (st <= n)
			st *= 2;
		st *= 2;
		auto z = Complex!double(0, 0);
		a[0 .. st] = z;
		b[0 .. st] = z;
		ca[0 .. st] = z;
		cb[0 .. st] = z;
		foreach (i; 0 .. n)
		{
			if (s[i] == 'V')
				a[i] = 1;
			else if (s[i] == 'K')
				b[n - 1 - i] = 1;
		}
		f.fft(a[0 .. st], ca[0 .. st]);
		f.fft(b[0 .. st], cb[0 .. st]);
		ca[0 .. st] *= cb[0 .. st];
		cb[0 .. st] = z;
		debug writeln(ca[0 .. st]);
		f.inverseFft(ca[0 .. st], cb[0 .. st]);
		foreach (i; 0 .. st)
		{
			d[i] = roundTo!int(cb[i].re);
		}
		r[n - 1] = d[n - 1];
		foreach (i; 1 .. n)
		{
			r[i] = d[n - 1 - i] + d[n - 1 + i];
		}
		int[] ans;
		foreach (i; 1 .. n)
		{
			bool flag = true;
			foreach (j; 1 .. (n - 1) / i + 1)
			{
				if (r[i * j])
				{
					flag = false;
					break;
				}
			}
			if (flag)
			{
				ans ~= i;
			}
		}
		ans ~= n;
		writeln(ans.length);
		foreach (x; ans)
		{
			write(x, ' ');
		}
	}
}


You are given $$$n$$$ integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the $$$n$$$ numbers may not be chosen.A rectangle (rectangular matrix) is called beautiful if in each row and in each column all values are different.What is the largest (by the total number of cells) beautiful rectangle you can construct? Print the rectangle itself.

The first line contains $$$n$$$ ($$$1 \le n \le 4\cdot10^5$$$). The second line contains $$$n$$$ integers ($$$1 \le a_i \le 10^9$$$).

In the first line print $$$x$$$ ($$$1 \le x \le n$$$) — the total number of cells of the required maximum beautiful rectangle. In the second line print $$$p$$$ and $$$q$$$ ($$$p \cdot q=x$$$): its sizes. In the next $$$p$$$ lines print the required rectangle itself. If there are several answers, print any.

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

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

    int[int] cnt;
    foreach (a; A) cnt[a] += 1;

    auto cumsum = new int[](N+2);
    foreach (a; cnt.values) cumsum[a+1] += 1;
    foreach (i; 0..N+1) cumsum[i+1] += cumsum[i];

    int calc_maxh(int w, int n) {
        return n / w;
    }

    int[][] build(int h, int w) {
        int[] B;
        Tuple!(int, int)[] C;

        foreach (k, v; cnt) C ~= tuple(k, min(w, v));
        C.sort!"a[1] > b[1]";
        foreach (c; C) foreach (_; 0..c[1]) B ~= c[0];

        auto ans = new int[][](h, w);
        int idx = 0;

        for (int r = 0, c = 0; idx < h * w; ++idx) {
            while (ans[r][c] != 0) (c += 1) %= w;
            ans[r][c] = B[idx];
            (r += 1) %= h;
            (c += 1) %= w;
        }

        return ans;
    }

    int maxh = 0;
    int maxw = 0;
    int count = cnt.keys.length.to!int;

    foreach (i; 1..sqrt(N.to!real).to!int+10) {
        if (count < i * i) break;
        int h = calc_maxh(i, count);
        if (h * i >= maxh * maxw) {
            maxh = h;
            maxw = i;
        }
        count += (cumsum[N] - cumsum[i+1]);
    }

    auto ans = build(maxh, maxw);
    writeln(maxh * maxw);
    writeln(maxh, " ", maxw);
    ans.map!(a => a.map!(to!string).join(" ")).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)); }

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

      auto ds = new int[N + 1];
      ds[1 .. $] = 1;
      foreach (d; 1 .. N + 1) {
        for (int m = d; m <= N; m += d) {
          chmax(ds[m], min(d, m / d));
        }
      }
      debug {
        writeln("ds = ", ds);
      }

      BinaryHeap!(Array!(Tuple!(int, int))) que;
      foreach (grp; A.group) {
        que.insert(tuple(cast(int)(grp[1]), grp[0]));
      }
      for (int m = N; m > 0; --m) {
        if (que.front[0] <= ds[m]) {
          const d = ds[m], e = m / ds[m];
          auto ans = new int[][](d, e);
          int pos;
          for (; !que.empty; ) {
            auto t = que.front;
            que.removeFront;
            foreach (_; 0 .. t[0]) {
              ans[pos % d][(pos % d + pos / d) % e] = t[1];
              ++pos;
            }
          }
          writeln(m);
          writeln(d, " ", e);
          foreach (x; 0 .. d) {
            foreach (y; 0 .. e) {
              if (y > 0) write(" ");
              write(ans[x][y]);
            }
            writeln();
          }
          break;
        }
        auto t = que.front;
        que.removeFront;
        if (t[0] >= 2) {
          que.insert(tuple(t[0] - 1, t[1]));
        }
      }
    }
  } catch (EOFException e) {
  }
}

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

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

    int[int] cnt;
    foreach (a; A) cnt[a] += 1;

    bool check(int n) {
        int sq = sqrt(n.to!real).to!int;
        while (sq * sq > n) --sq;
        while ((sq + 1) * (sq + 1) <= n) ++sq;
        return cnt.values.map!(a => min(a, sq)).sum >= sq * sq;
    }

    int[][] build(int n) {
        int sq = sqrt(n.to!real).to!int;
        while (sq * sq > n) --sq;
        while ((sq + 1) * (sq + 1) <= n) ++sq;

        int[] B;
        Tuple!(int, int)[] C;

        foreach (k, v; cnt) C ~= tuple(k, v);
        C.sort!"a[1] > b[1]";
        foreach (c; C) foreach (_; 0..c[1]) B ~= c[0];

        auto sm = C.map!(a => a[1]).sum;

        int h = sq, w = sq;
        while ((h + 1) * w <= sm) ++h;

        auto ans = new int[][](h, w);
        int idx = 0;

        for (int r = 0, c = 0; idx < h * w; ++idx) {
            while (ans[r][c] != 0) (c += 1) %= w;
            ans[r][c] = B[idx];
            (r += 1) %= h;
            (c += 1) %= w;
        }

        return ans;
    }

    int hi = sqrt(N.to!real).to!int + 10;
    int lo = 1;

    while (hi - lo > 1) {
        auto mid = (hi + lo) / 2;
        (check(mid) ? lo : hi) = mid;
    }

    auto ans = build(lo);
    auto h = ans.length.to!int;
    auto w = ans.front.length.to!int;
    writeln(h * w);
    writeln(h, " ", w);
    ans.map!(a => a.map!(to!string).join(" ")).each!writeln;
}

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

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

    int[int] cnt;
    foreach (a; A) cnt[a] += 1;

    bool check(int n) {
        int sq = sqrt(n.to!real).to!int;
        while (sq * sq > n) --sq;
        while ((sq + 1) * (sq + 1) <= n) ++sq;
        return cnt.values.map!(a => min(a, sq)).sum >= sq * sq;
    }

    int[][] build(int n) {
        int sq = sqrt(n.to!real).to!int;
        while (sq * sq > n) --sq;
        while ((sq + 1) * (sq + 1) <= n) ++sq;

        int[] B;
        Tuple!(int, int)[] C;

        foreach (k, v; cnt) C ~= tuple(k, min(sq, v));
        C.sort!"a[1] > b[1]";
        foreach (c; C) foreach (_; 0..c[1]) B ~= c[0];

        auto sm = C.map!(a => a[1]).sum;

        int h = sq, w = sq;
        while ((h + 1) * w <= sm) ++h;

        auto ans = new int[][](h, w);
        int idx = 0;

        for (int r = 0, c = 0; idx < h * w; ++idx) {
            while (ans[r][c] != 0) (c += 1) %= w;
            ans[r][c] = B[idx];
            (r += 1) %= h;
            (c += 1) %= w;
        }

        return ans;
    }

    int hi = sqrt(N.to!real).to!int + 10;
    int lo = 1;

    while (hi - lo > 1) {
        auto mid = (hi + lo) / 2;
        (check(mid) ? lo : hi) = mid;
    }

    auto ans = build(lo);
    auto h = ans.length.to!int;
    auto w = ans.front.length.to!int;
    writeln(h * w);
    writeln(h, " ", w);
    ans.map!(a => a.map!(to!string).join(" ")).each!writeln;
}


You are given an array consisting of all integers from $$$[l, r]$$$ inclusive. For example, if $$$l = 2$$$ and $$$r = 5$$$, the array would be $$$[2, 3, 4, 5]$$$. What's the minimum number of elements you can delete to make the bitwise AND of the array non-zero?A bitwise AND is a binary operation that takes two equal-length binary representations and performs the AND operation on each pair of the corresponding bits.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq 2 \cdot 10^5$$$) — the description of the array.

For each test case, output a single integer — the answer to the problem.

NoteIn the first test case, the array is $$$[1, 2]$$$. Currently, the bitwise AND is $$$0$$$, as $$$1\ \& \ 2 = 0$$$. However, after deleting $$$1$$$ (or $$$2$$$), the array becomes $$$[2]$$$ (or $$$[1]$$$), and the bitwise AND becomes $$$2$$$ (or $$$1$$$). This can be proven to be the optimal, so the answer is $$$1$$$.In the second test case, the array is $$$[2, 3, 4, 5, 6, 7, 8]$$$. Currently, the bitwise AND is $$$0$$$. However, after deleting $$$4$$$, $$$5$$$, and $$$8$$$, the array becomes $$$[2, 3, 6, 7]$$$, and the bitwise AND becomes $$$2$$$. This can be proven to be the optimal, so the answer is $$$3$$$. Note that there may be other ways to delete $$$3$$$ elements.

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	auto cnt = new long[][](18, 2*(10^^5)+1);
	foreach (i; 0..18)
	{
		auto bit = 1L << i;
		foreach (j; 1..2*(10^^5)+1)
		{
			cnt[i][j] = cnt[i][j-1];
			if (j & bit)
				++cnt[i][j];
		}
	}
	foreach (ti; 0..t)
	{
		auto l = RD!int;
		auto r = RD!int;

		auto len = r - l + 1;
		ans[ti] = long.max;
		foreach (i; 0..18)
		{
			ans[ti].chmin(len - (cnt[i][r]-cnt[i][l-1]));
		}
	}

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

immutable multi = true;

void solve(int tc)
{
  auto l = readInt!uint;
  auto r = readInt!uint;
  int ans = int.max;
  int getOnes(int n, int b)
  {
    int blksize = (1 << b);
    int blk = n / blksize;
    int off = n % blksize;
    if (blk == 0) return 0;
    int pblk = blk;
    int blk1 = pblk / 2;
    if (blk&1) off++;
    else off = 0;
    return blk1 * blksize + off;
  }
  foreach(bit; 0 .. 32)
    {
      auto or = getOnes(r, bit);
      auto ol = getOnes(l-1, bit);
      debug writeln(bit, " ", or, " ", ol);
      ans = min(ans, r - l + 1 - (or - ol));
    }
  ans.writeln;
}

// main {{{
void main()
{
	auto t = multi? readInt!int : 1;
	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;
// }}}

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

void cnt_set_bit(ref int[32] bitcnt, int n)
{
  if (n == 0)
    return;

  int p = -1;
  while (1 << (p + 1) <= n)
    p++;

  foreach (i ; 0 .. p)
    bitcnt[i] += (1 << p) / 2;

  bitcnt[p] += n - (1 << p) + 1;

  cnt_set_bit(bitcnt, n - (1 << p));
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int l, r;
    int[32] bitcnt;
    readf!" %d %d "(l, r);
    int[32] bitcnt1;
    int[32] bitcnt2;
    cnt_set_bit(bitcnt1, l - 1);
    cnt_set_bit(bitcnt2, r);
    foreach (i ; 0 .. 30) {
      bitcnt[i] = bitcnt2[i] - bitcnt1[i];
    }
    int ans = int.max;
    foreach (bt ; 0 .. 30) {
      if (bitcnt[bt] != 0)
        ans = min(ans, r - l + 1 - bitcnt[bt]);
    }
    writeln(ans);
  }
}

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

int num (int limit, int bit)
{
	auto half = 1 << bit;
	auto full = half << 1;
	auto pieces = limit / full;
	auto tail = limit % full;
	auto res = pieces * half + min (tail, half);
	return res;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int lo, hi;
		readf !(" %s %s") (lo, hi);
		int res = int.max;
		foreach (i; 0..30)
		{
			res = min (res, num (hi + 1, i) - num (lo, i));
		}
		writeln (res);
	}
}

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

enum E = 20;
enum LIM = 2 * 10^^5 + 10;

void main() {
  auto sums = new int[][](E, LIM + 1);
  foreach (e; 0 .. E) {
    foreach (i; 0 .. LIM) {
      sums[e][i + 1] = sums[e][i] + (i >> e & 1);
    }
  }

  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        const L = readInt();
        const R = readInt() + 1;

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto l = RD!int;
		auto r = RD!int;

		auto len = r - l + 1;
		ans[ti] = len - len / 2 - (len % 2 ? l % 2 : 0);
		foreach (i; 0..18)
		{
			auto bit = 1L << i;
			if (bit < l)
			{
				if (l & bit)
					ans[ti].chmin(len - min(r - l + 1, bit));
				else
				{
					auto x = l | bit;
					x >>= i;
					x <<= i;
					ans[ti].chmin(len - min(r - x + 1, bit));
				}
			}
			else
				ans[ti].chmin(len - min(r - bit + 1, bit));
		}
	}

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto l = RD!int;
		auto r = RD!int;

		auto len = r - l + 1;
		ans[ti] = len - len / 2 - (len % 2 ? l % 2 : 0);
		foreach (i; 0..18)
		{
			auto bit = 1L << i;
			if (bit < l) continue;
			ans[ti].chmin(len - min(r - bit + 1, bit));
		}
	}

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto l = RD!int;
		auto r = RD!int;

		auto len = r - l + 1;
		ans[ti] = len - (len+1) / 2;
		foreach (i; 0..18)
		{
			auto bit = 1L << i;
			if (bit < l) continue;
			ans[ti].chmin(len - min(r - bit + 1, bit-1));
		}
	}

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