Kostya is a progamer specializing in the discipline of Dota 2. Valve Corporation, the developer of this game, has recently released a new patch which turned the balance of the game upside down. Kostya, as the captain of the team, realizes that the greatest responsibility lies on him, so he wants to resort to the analysis of innovations patch from the mathematical point of view to choose the best heroes for his team in every game.A Dota 2 match involves two teams, each of them must choose some heroes that the players of the team are going to play for, and it is forbidden to choose the same hero several times, even in different teams. In large electronic sports competitions where Kostya's team is going to participate, the matches are held in the Captains Mode. In this mode the captains select the heroes by making one of two possible actions in a certain, predetermined order: pick or ban.  To pick a hero for the team. After the captain picks, the picked hero goes to his team (later one of a team members will play it) and can no longer be selected by any of the teams.  To ban a hero. After the ban the hero is not sent to any of the teams, but it still can no longer be selected by any of the teams. The team captain may miss a pick or a ban. If he misses a pick, a random hero is added to his team from those that were available at that moment, and if he misses a ban, no hero is banned, as if there was no ban.Kostya has already identified the strength of all the heroes based on the new patch fixes. Of course, Kostya knows the order of picks and bans. The strength of a team is the sum of the strengths of the team's heroes and both teams that participate in the match seek to maximize the difference in strengths in their favor. Help Kostya determine what team, the first one or the second one, has advantage in the match, and how large the advantage is.

The first line contains a single integer n (2 ≤ n ≤ 100) — the number of heroes in Dota 2. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 106) — the strengths of all the heroes. The third line contains a single integer m (2 ≤ m ≤ min(n, 20)) — the number of actions the captains of the team must perform. Next m lines look like "action team", where action is the needed action: a pick (represented as a "p") or a ban (represented as a "b"), and team is the number of the team that needs to perform the action (number 1 or 2). It is guaranteed that each team makes at least one pick. Besides, each team has the same number of picks and the same number of bans.

Print a single integer — the difference between the strength of the first team and the strength of the second team if the captains of both teams will act optimally well.

import std.algorithm,std.stdio,core.bitop;void main(){int n,m,w,k;scanf("%d",&n);auto s=new int[n];foreach(ref x;s)scanf("%d",&x);sort!"a>b"(s);scanf("%d ",&m);int[]t;foreach(i;0..m){auto r=readln;t~=(r[0]=='p')*2+(r[2]=='2');}w=1<<m;auto f=new int[w];foreach(u;1..w){k=m-u.popcnt;f[u]=(t[k]&1)?int.max:int.min;foreach(j;0..m)if(u&(1<<j)){int v=u^(1<<j);switch(t[k]){case 0:f[u]=max(f[u],f[v]);break;case 1:f[u]=min(f[u],f[v]);break;case 2:f[u]=max(f[u],f[v]+s[j]);break;case 3:f[u]=min(f[u],f[v]-s[j]);break;default:}}}f[w-1].writeln;}

import std.algorithm;
import std.stdio;
import std.string;
import core.bitop;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto s = new int [n];
		foreach (ref x; s)
		{
			readf (" %s", &x);
		}
		sort !("a > b") (s);

		int m;
		readf (" %s ", &m);
		int [] t;
		foreach (i; 0..m)
		{
			auto r = readln.strip;
			t ~= (r[0] == 'p') * 2 + (r[2] == '2');
		}
		s = s[0..m];

		int m2 = 1 << m;
		auto f = new int [m2];
		f[m2 - 1] = 0;

		foreach_reverse (u; 0..m2 - 1)
		{
			int i = popcnt (u);
			f[u] = (t[i] & 1) ? int.max : int.min;
			foreach (j; 0..m)
			{
				if (!(u & (1 << j)))
				{
					int v = u ^ (1 << j);
					switch (t[i])
					{
						case 0: // b 1
							f[u] = max (f[u],
							    f[v]);
							break;
						case 1: // b 2
							f[u] = min (f[u],
							    f[v]);
							break;
						case 2: // p 1
							f[u] = max (f[u],
							    f[v] + s[j]);
							break;
						case 3: // p 2
							f[u] = min (f[u],
							    f[v] - s[j]);
						        break;
					        default:
							assert (false);
					}
				}
			}
		}

		writeln (f[0]);
	}
}

import std.algorithm, std.stdio, std.string, core.bitop;
void main ()
{
	int n;
	readf (" %s", &n);
	auto s = new int [n];
	foreach (ref x; s) readf (" %s", &x);
	sort !("a > b") (s);
	int m;
	readf (" %s ", &m);
	int [] t;
	foreach (i; 0..m)
	{
		auto r = readln.strip;
		t ~= (r[0] == 'p') * 2 + (r[2] == '2');
	}
	int m2 = 1 << m;
	auto f = new int [m2];
	foreach (u; 1..m2)
	{
		int i = m - popcnt (u);
		f[u] = (t[i] & 1) ? int.max : int.min;
		foreach (j; 0..m) if (u & (1 << j))
		{
			int v = u ^ (1 << j);
			switch (t[i])
			{
				case 0: f[u] = max (f[u], f[v]); break;
				case 1: f[u] = min (f[u], f[v]); break;
				case 2: f[u] = max (f[u], f[v] + s[j]); break;
				case 3: f[u] = min (f[u], f[v] - s[j]); break;
				default: assert (false);
			}
		}
	}
	writeln (f[$ - 1]);
}

import std.algorithm, std.stdio, std.string, core.bitop;
void main ()
{
	int n;
	scanf (" %d", &n);
	auto s = new int [n];
	foreach (ref x; s) scanf (" %d", &x);
	sort !("a > b") (s);
	int m;
	scanf (" %d ", &m);
	int [] t;
	foreach (i; 0..m)
	{
		auto r = readln.strip;
		t ~= (r[0] == 'p') * 2 + (r[2] == '2');
	}
	int m2 = 1 << m;
	auto f = new int [m2];
	foreach_reverse (u; 0..m2 - 1)
	{
		int i = popcnt (u);
		f[u] = (t[i] & 1) ? int.max : int.min;
		foreach (j; 0..m)
		{
			if (u & (1 << j)) continue;
			int v = u ^ (1 << j);
			switch (t[i])
			{
				case 0: f[u] = max (f[u], f[v]); break;
				case 1: f[u] = min (f[u], f[v]); break;
				case 2: f[u] = max (f[u], f[v] + s[j]); break;
				case 3: f[u] = min (f[u], f[v] - s[j]); break;
				default: assert (false);
			}
		}
	}
	writeln (f[0]);
}

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

immutable int INF = int.max / 2;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto s = new int [n];
		foreach (ref x; s)
		{
			readf (" %s", &x);
		}
		sort !("a > b") (s);

		int m;
		readf (" %s ", &m);
		int [] t;
		foreach (i; 0..m)
		{
			auto r = readln.strip;
			t ~= (r[0] == 'p') * 2 + (r[2] == '2');
			debug {writeln (r, ' ', t[i]);}
		}
		s = s[0..m];

		int m2 = 1 << m;
		auto f = new int [] [] (m + 1, m2);
		foreach (ref g; f)
		{
			g[] = int.max;
		}

		int fun (int i, int u)
		{
			if (i == m)
			{
				return 0;
			}
			if (f[i][u] != int.max)
			{
				return f[i][u];
			}
			int res = (t[i] & 1) ? +INF : -INF;
			foreach (j; 0..m)
			{
				if (!(u & (1 << j)))
				{
					int v = u ^ (1 << j);
					switch (t[i])
					{
						case 0: // b 1
							res = max (res,
							    fun (i + 1, v));
							break;
						case 1: // b 2
							res = min (res,
							    fun (i + 1, v));
							break;
						case 2: // p 1
							res = max (res,
							    fun (i + 1, v) + s[j]);
							break;
						case 3: // p 2
							res = min (res,
							    fun (i + 1, v) - s[j]);
						        break;
					        default:
							assert (false);
					}
				}
			}
			debug {writeln (i, ' ', u, ' ', res);}
			f[i][u] = res;
			return res;
		}

		writeln (fun (0, 0));
	}
}

import std.algorithm, std.stdio, std.string, core.bitop;
void main ()
{
	int n;
	readf (" %s", &n);
	auto s = new int [n];
	foreach (ref x; s) readf (" %s", &x);
	sort !("a > b") (s);
	int m;
	readf (" %s ", &m);
	int [] t;
	foreach (i; 0..m)
	{
		auto r = readln.strip;
		t ~= (r[0] == 'p') * 2 + (r[2] == '2');
	}
	int m2 = 1 << m;
	auto f = new int [m2];
	foreach_reverse (u; 0..m2 - 1)
	{
		int i = popcnt (u);
		f[u] = (t[i] & 1) ? int.max : int.min;
		foreach (j; 0..m) if (!(u & (1 << j)))
		{
			int v = u ^ (1 << j);
			switch (t[i])
			{
				case 0: f[u] = max (f[u], f[v]); break;
				case 1: f[u] = min (f[u], f[v]); break;
				case 2: f[u] = max (f[u], f[v] + s[j]); break;
				case 3: f[u] = min (f[u], f[v] - s[j]); break;
				default: assert (false);
			}
		}
	}
	writeln (f[0]);
}

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

immutable int INF = int.max / 2;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto s = new int [n];
		foreach (ref x; s)
		{
			readf (" %s", &x);
		}
		sort !("a > b") (s);

		int m;
		readf (" %s ", &m);
		int [] t;
		foreach (i; 0..m)
		{
			auto r = readln.strip;
			t ~= (r[0] == 'p') * 2 + (r[2] == '2');
			debug {writeln (r, ' ', t[i]);}
		}
		s = s[0..m];

		int m2 = 1 << m;
		auto f = new int [m2];
		f[] = int.max;

		int fun (int u)
		{
			int i = popcnt (u);
			if (i == m)
			{
				return 0;
			}
			if (f[u] != int.max)
			{
				return f[u];
			}
			int res = (t[i] & 1) ? +INF : -INF;
			foreach (j; 0..m)
			{
				if (!(u & (1 << j)))
				{
					int v = u ^ (1 << j);
					switch (t[i])
					{
						case 0: // b 1
							res = max (res,
							    fun (v));
							break;
						case 1: // b 2
							res = min (res,
							    fun (v));
							break;
						case 2: // p 1
							res = max (res,
							    fun (v) + s[j]);
							break;
						case 3: // p 2
							res = min (res,
							    fun (v) - s[j]);
						        break;
					        default:
							assert (false);
					}
				}
			}
			f[u] = res;
			return res;
		}

		writeln (fun (0));
	}
}

import std.algorithm, std.stdio, std.string, core.bitop;
void main () {
	int n;
	readf (" %s", &n);
	auto s = new int [n];
	foreach (ref x; s) readf (" %s", &x);
	sort !("a > b") (s);
	int m;
	readf (" %s ", &m);
	int [] t;
	foreach (i; 0..m) {
		auto r = readln.strip;
		t ~= (r[0] == 'p') * 2 + (r[2] == '2');
	}
	int m2 = 1 << m;
	auto f = new int [m2];
	foreach (u; 1..m2) {
		int i = m - u.popcnt;
		f[u] = (t[i] & 1) ? int.max : int.min;
		foreach (j; 0..m) if (u & (1 << j)) {
			int v = u ^ (1 << j);
			switch (t[i]) {
				case 0: f[u] = max (f[u], f[v]); break;
				case 1: f[u] = min (f[u], f[v]); break;
				case 2: f[u] = max (f[u], f[v] + s[j]); break;
				case 3: f[u] = min (f[u], f[v] - s[j]); break;
				default: assert (false);
	}	}	}
	f[$ - 1].writeln;
}

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

immutable int INF = int.max / 2;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto s = new int [n];
		foreach (ref x; s)
		{
			readf (" %s", &x);
		}
		sort !("a > b") (s);

		int m;
		readf (" %s ", &m);
		int [] t;
		foreach (i; 0..m)
		{
			auto r = readln.strip;
			t ~= (r[0] == 'p') * 2 + (r[2] == '2');
			debug {writeln (r, ' ', t[i]);}
		}
		s = s[0..m];

		int m2 = 1 << m;
		auto f = new int [] [] (m + 1, m2);
		f[0][0] = 0;
		foreach (i; 1..m + 1)
		{
			foreach (u; 0..m2)
			{
				if (popcnt (u) != i)
				{
					continue;
				}
				f[i][u] = (t[i - 1] & 1) ? -INF : +INF;
				foreach (j; 0..m)
				{
					if (u & (1 << j))
					{
						int v = u ^ (1 << j);
						switch (t[i - 1])
						{
							case 0: // b 1
								f[i][u] = min (f[i][u],
								    f[i - 1][v]);
								break;
							case 1: // b 2
								f[i][u] = max (f[i][u],
								    f[i - 1][v]);
								break;
							case 2: // p 1
								f[i][u] = min (f[i][u],
								    f[i - 1][v] + s[j]);
								break;
							case 3: // p 2
								f[i][u] = max (f[i][u],
								    f[i - 1][v] - s[j]);
							        break;
						        default:
								assert (false);
						}
					}
				}
				debug {writeln (i, ' ', u, ' ', f[i][u]);}
			}
		}
		writeln (f[m][m2 - 1]);
	}
}

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

immutable int INF = int.max / 2;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto s = new int [n];
		foreach (ref x; s)
		{
			readf (" %s", &x);
		}
		sort !("a > b") (s);

		int m;
		readf (" %s ", &m);
		int [] t;
		foreach (i; 0..m)
		{
			auto r = readln.strip;
			t ~= (r[0] == 'p') * 2 + (r[2] == '2');
		}
		s = s[0..m];

		int m2 = 1 << m;
		auto f = new int [] [] (m + 1, m2);
		f[0][0] = 0;
		foreach (i; 1..m + 1)
		{
			foreach (u; 0..m2)
			{
				if (popcnt (u) != i)
				{
					continue;
				}
				f[i][u] = (t[i - 1] & 1) ? +INF : -INF;
				foreach (j; 0..m)
				{
					if (u & (1 << j))
					{
						int v = u ^ (1 << j);
						switch (t[i - 1])
						{
							case 0:
								f[i][u] = max (f[i][u],
								    f[i - 1][v]);
								break;
							case 1:
								f[i][u] = min (f[i][u],
								    f[i - 1][v]);
								break;
							case 2:
								f[i][u] = max (f[i][u],
								    f[i - 1][v] - s[j]);
								break;
							case 3:
								f[i][u] = min (f[i][u],
								    f[i - 1][v] + s[j]);
							        break;
						        default:
								assert (false);
						}
					}
				}
			}
		}
		writeln (-f[m][m2 - 1]);
	}
}


Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!'The head of the company decided to choose two suspects and invite them to his office. Naturally, he should consider the coders' opinions. That's why the head wants to make such a choice that at least p of n coders agreed with it. A coder agrees with the choice of two suspects if at least one of the two people that he named at the meeting was chosen as a suspect. In how many ways can the head of F choose two suspects?Note that even if some coder was chosen as a suspect, he can agree with the head's choice if he named the other chosen coder at the meeting.

The first line contains integers n and p (3 ≤ n ≤ 3·105; 0 ≤ p ≤ n) — the number of coders in the F company and the minimum number of agreed people. Each of the next n lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the numbers of coders named by the i-th coder. It is guaranteed that xi ≠ i,  yi ≠ i,  xi ≠ yi.

Print a single integer — the number of possible two-suspect sets. Note that the order of the suspects doesn't matter, that is, sets (1, 2) and (2, 1) are considered identical.

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

immutable int NA = -1;

void main ()
{
	int n, p;
	while (readf (" %s %s", &n, &p) > 0)
	{
		auto a = new int [int] [n];
		auto d = new int [n];
		foreach (w; 0..n)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u--;
			v--;
			a[u][v]++;
			a[v][u]++;
			d[u]++;
			d[v]++;
		}

		auto s = new int [n + 1];
		foreach (u; 0..n)
		{
			s[d[u]]++;
		}
		foreach (i; 0..n)
		{
			s[i + 1] += s[i];
		}
		debug {writeln (d);}
		debug {writeln (s);}

		long res = 0L;
		foreach (u; 0..n)
		{
			int more = p - d[u];
			res += n - 1;
			int less = 0;
			if (more > 0)
			{
				less = s[more - 1];
				if (d[u] <= more - 1)
				{
					less--;
				}
			}
			res -= less;
			debug {writefln ("u = %s, more = %s, less = %s",
			                 u, more, less);}
			foreach (v, x; a[u])
			{
				if (d[v] >= more)
				{
					if (d[v] - x < more)
					{
						res--;
						debug {writefln ("(%s, %s): " ~
						    "minus %s edges",
						    u, v, x);}
					}
				}
			}
		}
		res /= 2;
		writeln (res);
	}
}


Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table.Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 ≠ r2 and c1 ≠ c2, then we can produce element (r2, c2).  Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.Innopolis University scientists already have samples of q elements. They want to obtain samples of all n·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase.

The first line contains three integers n, m, q (1 ≤ n, m ≤ 200 000; 0 ≤ q ≤ min(n·m, 200 000)), the chemical table dimensions and the number of elements scientists already have. The following q lines contain two integers ri, ci (1 ≤ ri ≤ n, 1 ≤ ci ≤ m), each describes an element that scientists already have. All elements in the input are different.

Print the minimal number of elements to be purchased.

NoteFor each example you have a picture which illustrates it.The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially.The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced.Test 1We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything.  Test 2We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements.  Test 3There are several possible solutions. One of them is illustrated below.Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions.

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

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

    Tuple!(int, int)[] prs;

    foreach (_; 0 .. q) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        prs ~= tuple(x, y);
    }

    struct uf {
        int[] p;
        int[] r;
        int sets;

        this(int sz) {
            p = new int[] (sz+1);
            foreach (i; 0 .. sz+1) { p[i] = i; }
            r = new int[] (sz+1);
            r[] = 0;
            sets = sz;
        }

        int fnd(int x) {
            if (p[x] != x) { p[x] = fnd(p[x]); }

            return p[x];
        }

        void uni(int a, int b) {
            a = fnd(a);
            b = fnd(b);

            if (a == b) { return; }

            if (r[a] > r[b]) { swap(a, b); }

            p[a] = b;
            if (r[a] == r[b]) { r[b] += 1; }

            --sets;
        }
    }

    uf u = uf(m);

    prs.sort();

    foreach (i; 1 .. q) {
        if (prs[i-1][0] == prs[i][0]) {
            u.uni(prs[i-1][1], prs[i][1]);
        }
    }

    int groups = u.sets;

    debug { groups.writeln; }

    int emptyRows = n - prs.map!(t => t[0]).array.uniq.array.length.to!int;

    auto ans = groups - 1 + emptyRows;

    ans.writeln;
}

import std.range;
import std.stdio;

void main ()
{
	int n, m, q;
	while (readf (" %s %s %s", &n, &m, &q) > 0)
	{
		int res = n + m - 1;
		auto p = (n + m).iota.array;

		int root (int w)
		{
			if (p[w] != w)
			{
				p[w] = root (p[w]);
			}
			return p[w];
		}

		bool unite (int u, int v)
		{
			u = root (u);
			v = root (v);
			if (u == v)
			{
				return false;
			}
			p[u] = v;
			return true;
		}

		foreach (i; 0..q)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u -= 1;
			v -= 1;
			v += n;
			if (unite (u, v))
			{
				res -= 1;
			}
		}
		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)); }

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

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

      auto uf = new int[M + N];
      uf[] = -1;
      foreach (q; 0 .. Q) {
        uf.connect(R[q], M + C[q]);
      }
      int num, isoRow, isoCol;
      foreach (u; 0 .. M + N) {
        if (uf[u] < 0) {
          if (-uf[u] >= 2) {
            ++num;
          } else {
            (u < M) ? ++isoRow : ++isoCol;
          }
        }
      }
      debug {
        writeln(num, " ", isoRow, " ", isoCol);
      }
      int ans;
      if (num == 0) {
        ans = M + N - 1;
      } else {
        ans += num - 1;
        ans += isoRow;
        ans += isoCol;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;
import std.traits;

void main(string[] args)
{
  auto n = next!int;
  auto m = next!int;
  auto adjr = new int[][](n);
  auto visr = new bool[](n);
  auto adjc = new int[][](m);
  auto visc = new bool[](m);
  auto q = next!int;
  foreach(qi; 0 .. q)
    {
      auto r = next!int - 1;
      auto c = next!int - 1;
      adjr[r] ~= c;
      adjc[c] ~= r;
    }
  void dfs(int i, int roc)
  {
    if (roc)
      {
	visr[i] = true;
	foreach(nei; adjr[i])
	  if (!visc[nei])
	    dfs(nei, 0);
      }
    else
      {
	visc[i] = true;
	foreach(nei; adjc[i])
	  if (!visr[nei])
	    dfs(nei, 1);
      }
  }
  int cmps = 0;
  foreach(i; 0 .. n)
    {
      if (!visr[i])
	{
	  dfs(i, 1);
	  cmps++;
	}
    }

  foreach(i; 0 .. m)
    {
      if (!visc[i])
	{
	  dfs(i, 0);
	  cmps++;
	}
    }
  (cmps - 1).writeln;
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}

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

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

      auto uf = new int[M + N];
      uf[] = -1;
      foreach (q; 0 .. Q) {
        uf.connect(R[q], M + C[q]);
      }
      int num, isoRow, isoCol;
      foreach (u; 0 .. M + N) {
        if (uf[u] < 0) {
          if (-uf[u] >= 2) {
            ++num;
          } else {
            (u < M) ? ++isoRow : ++isoCol;
          }
        }
      }
      debug {
        writeln(num, " ", isoRow, " ", isoCol);
      }
      int ans = num - 1;
      ans += max(isoRow, isoCol);
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.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 root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

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

      auto uf = new int[M + N];
      uf[] = -1;
      foreach (q; 0 .. Q) {
        uf.connect(R[q], M + C[q]);
      }
      int num, isoRow, isoCol;
      foreach (u; 0 .. M + N) {
        if (uf[u] < 0) {
          if (-uf[u] >= 2) {
            ++num;
          } else {
            (u < M) ? ++isoRow : ++isoCol;
          }
        }
      }
      debug {
        writeln(num, " ", isoRow, " ", isoCol);
      }
      int ans;
      if (num == 0) {
        ans = M + N - 1;
      } else {
        ans += num - 1;
        ans += max(isoRow, isoCol);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Tokitsukaze is arranging a meeting. There are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall.There are exactly $$$n \cdot m$$$ students attending the meeting, including several naughty students and several serious students. The students are numerated from $$$1$$$ to $$$n\cdot m$$$. The students will enter the meeting hall in order. When the $$$i$$$-th student enters the meeting hall, he will sit in the $$$1$$$-st column of the $$$1$$$-st row, and the students who are already seated will move back one seat. Specifically, the student sitting in the $$$j$$$-th ($$$1\leq j \leq m-1$$$) column of the $$$i$$$-th row will move to the $$$(j+1)$$$-th column of the $$$i$$$-th row, and the student sitting in $$$m$$$-th column of the $$$i$$$-th row will move to the $$$1$$$-st column of the $$$(i+1)$$$-th row.For example, there is a meeting hall with $$$2$$$ rows and $$$2$$$ columns of seats shown as below:  There will be $$$4$$$ students entering the meeting hall in order, represented as a binary string "1100", of which '0' represents naughty students and '1' represents serious students. The changes of seats in the meeting hall are as follows:  Denote a row or a column good if and only if there is at least one serious student in this row or column. Please predict the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall, for all $$$i$$$.

The first contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — the number of test cases. For each test case, the first line contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 10^6$$$; $$$1 \leq n \cdot m \leq 10^6$$$), denoting there are $$$n$$$ rows and $$$m$$$ columns of seats in the meeting hall. The second line contains a binary string $$$s$$$ of length $$$n \cdot m$$$, consisting only of zeros and ones. If $$$s_i$$$ equal to '0' represents the $$$i$$$-th student is a naughty student, and $$$s_i$$$ equal to '1' represents the $$$i$$$-th student is a serious student. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$.

For each test case, print a single line with $$$n \cdot m$$$ integers — the number of good rows and columns just after the $$$i$$$-th student enters the meeting hall.

NoteThe first test case is shown in the statement.After the $$$1$$$-st student enters the meeting hall, there are $$$2$$$ good rows and columns: the $$$1$$$-st row and the $$$1$$$-st column.After the $$$2$$$-nd student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$1$$$-st row, the $$$1$$$-st column and the $$$2$$$-nd column.After the $$$3$$$-rd student enters the meeting hall, the $$$4$$$ rows and columns are all good.After the $$$4$$$-th student enters the meeting hall, there are $$$3$$$ good rows and columns: the $$$2$$$-nd row, the $$$1$$$-st column and the $$$2$$$-nd column.

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 a = readln.strip.map !(q{a == '1'}).array;
		auto total = n * m;

		auto resCols = new int [total];
		auto mark = new bool [m];
		int curCols = 0;
		foreach (i; 0..total)
		{
			if (a[i])
			{
				curCols += !mark[i % m];
				mark[i % m] = true;
			}
			resCols[i] = curCols;
		}

		auto resRows = new int [total];
		auto s = new int [total + 1];
		foreach (i; 0..total)
		{
			s[i + 1] = s[i] + a[i];
		}
		foreach_reverse (i; m..total + 1)
		{
			s[i] -= s[i - m];
		}
		foreach (i; 0..total)
		{
			resRows[i] = (s[i + 1] != 0);
		}
		foreach (i; m..total)
		{
			resRows[i] += resRows[i - m];
		}

		auto res = new int [total];
		res[] = resCols[] + resRows[];
		debug {writefln !("cols: %(%s %)") (resCols);}
		debug {writefln !("rows: %(%s %)") (resRows);}
		writefln !("%(%s %)") (res);
	}
}


oolimry has an array $$$a$$$ of length $$$n$$$ which he really likes. Today, you have changed his array to $$$b$$$, a permutation of $$$a$$$, to make him sad.Because oolimry is only a duck, he can only perform the following operation to restore his array:   Choose two integers $$$i,j$$$ such that $$$1 \leq i,j \leq n$$$.  Swap $$$b_i$$$ and $$$b_j$$$. The sadness of the array $$$b$$$ is the minimum number of operations needed to transform $$$b$$$ into $$$a$$$.Given the array $$$a$$$, find any array $$$b$$$ which is a permutation of $$$a$$$ that has the maximum sadness over all permutations of the array $$$a$$$.

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

For each test case, print $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ — describing the array $$$b$$$. If there are multiple answers, you may print any.

NoteIn the first test case, the array $$$[1,2]$$$ has sadness $$$1$$$. We can transform $$$[1,2]$$$ into $$$[2,1]$$$ using one operation with $$$(i,j)=(1,2)$$$.In the second test case, the array $$$[3,3,2,1]$$$ has sadness $$$2$$$. We can transform $$$[3,3,2,1]$$$ into $$$[1,2,3,3]$$$ with two operations with $$$(i,j)=(1,4)$$$ and $$$(i,j)=(2,3)$$$ respectively.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto p = n.iota.array;
		p.schwartzSort !(i => a[i], SwapStrategy.stable);
		auto s = p.map !(i => a[i]).group.map !(i => i[1]).maxElement;
		debug {writeln ("s = ", s);}
		auto q = p[s..$] ~ p[0..s];
		auto b = new int [n];
		foreach (i; 0..n)
		{
			b[q[i]] = a[p[i]];
		}
		writefln !("%(%s %)") (b);
	}
}

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

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

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

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

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

        auto xss = new int[][N + 1];
        foreach (i; 0 .. N) {
          xss[A[i]] ~= i;
        }
        auto lens = new int[N + 1];
        foreach (a; 1 .. N + 1) {
          lens[a] = cast(int)(xss[a].length);
        }

        auto as = iota(1, N + 1).array;
        as.sort!((a, b) => (lens[a] > lens[b]));
        debug {
          writeln("xss = ", xss);
          writeln("lens = ", lens);
          writeln("as = ", as);
        }

        auto ans = new int[N];
        for (; lens[as[0]] >= 1; ) {
          int[] ys;
          foreach (a; as) {
            if (lens[a] == 0) {
              break;
            }
            ys ~= xss[a][--lens[a]];
          }
          debug {
            writeln("ys = ", ys);
          }
          const ysLen = cast(int)(ys.length);
          foreach (j; 0 .. ysLen - 1) {
            ans[ys[j]] = A[ys[j + 1]];
          }
          ans[ys[ysLen - 1]] = A[ys[0]];
        }

        foreach (i; 0 .. N) {
          if (i) write(" ");
          write(ans[i]);
        }
        writeln;
      }
    }
  } catch (EOFException e) {
  }
}


Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into $$$n$$$ sub-tracks. You are given an array $$$a$$$ where $$$a_i$$$ represents the number of traffic cars in the $$$i$$$-th sub-track. You define the inconvenience of the track as $$$\sum\limits_{i=1}^{n} \sum\limits_{j=i+1}^{n} \lvert a_i-a_j\rvert$$$, where $$$|x|$$$ is the absolute value of $$$x$$$. You can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track.Find the minimum inconvenience you can achieve.

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

For each test case, print a single line containing a single integer: the minimum inconvenience you can achieve by applying the given operation any (possibly zero) number of times.

NoteFor the first test case, you can move a car from the $$$3$$$-rd sub-track to the $$$1$$$-st sub-track to obtain $$$0$$$ inconvenience.For the second test case, moving any car won't decrease the inconvenience of the track.

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

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

while(t--) {
    int n = readln.chomp.to!int;
    long[] a = readln.split.map!(to!long).array;
    long A = a.sum % n;
    writefln("%s", A * (n - A));
}
}

// code by cutx64

module main;

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

void main() {

  int tests; readf!"%s\n"(tests);
  while(tests--) {
    int n; readf!"%s\n"(n);
    auto a = readln.splitter.map!(to!long).array;
    long s = a.sum;
    long r = s % n;
    (r * (n - r)).writeln;
  }

} // main

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

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

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

		auto tot = a.sum;
		auto rem = tot % n;
		ans[ti] = rem * (n-rem);
	}

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

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

void theCode(){
    int n = scan!int;
    auto arr = scanArray;
    arr.sort;
    ll summ = arr.sum;
    ll av = summ / n;
    ll rem = summ % n;
    writeln(rem * (n - rem));
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) theCode();
}

/*********  That's All Folks!  *********/
import std.stdio, std.random, std.functional, std.container, std.algorithm;
import std.numeric, std.range, std.typecons, std.string, std.math, std.conv;
string[] tk; T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long, tup = Tuple!(long, "x",  long, "y");

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

void main()
{
  long t;
  readf!" %d "(t);
  while (t--) {
    long n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!long).array.sort.array;
    auto sum = a.sum;
    if (sum % n == 0) {
      writeln(0);
      continue;
    }
    auto avgru = (sum + n - 1) / n;
    auto avgrd = (sum) / n;
    auto rem = sum - avgrd * n;
//    writefln("n=%d rem=%d", n, rem);
    long result = rem * abs(n - rem);
    writeln(result);
  }
}


You are given some text $$$t$$$ and a set of $$$n$$$ strings $$$s_1, s_2, \dots, s_n$$$. In one step, you can choose any occurrence of any string $$$s_i$$$ in the text $$$t$$$ and color the corresponding characters of the text in red. For example, if $$$t=\texttt{bababa}$$$ and $$$s_1=\texttt{ba}$$$, $$$s_2=\texttt{aba}$$$, you can get $$$t=\color{red}{\texttt{ba}}\texttt{baba}$$$, $$$t=\texttt{b}\color{red}{\texttt{aba}}\texttt{ba}$$$ or $$$t=\texttt{bab}\color{red}{\texttt{aba}}$$$ in one step.You want to color all the letters of the text $$$t$$$ in red. When you color a letter in red again, it stays red.In the example above, three steps are enough:  Let's color $$$t[2 \dots 4]=s_2=\texttt{aba}$$$ in red, we get $$$t=\texttt{b}\color{red}{\texttt{aba}}\texttt{ba}$$$;  Let's color $$$t[1 \dots 2]=s_1=\texttt{ba}$$$ in red, we get $$$t=\color{red}{\texttt{baba}}\texttt{ba}$$$;  Let's color $$$t[4 \dots 6]=s_2=\texttt{aba}$$$ in red, we get $$$t=\color{red}{\texttt{bababa}}$$$. Each string $$$s_i$$$ can be applied any number of times (or not at all). Occurrences for coloring can intersect arbitrarily.Determine the minimum number of steps needed to color all letters $$$t$$$ in red and how to do it. If it is impossible to color all letters of the text $$$t$$$ in red, output -1.

The first line of the input contains an integer $$$q$$$ ($$$1 \le q \le 100$$$) —the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains the text $$$t$$$ ($$$1 \le |t| \le 100$$$), consisting only of lowercase Latin letters, where $$$|t|$$$ is the length of the text $$$t$$$. The second line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10$$$) — the number of strings in the set. This is followed by $$$n$$$ lines, each containing a string $$$s_i$$$ ($$$1 \le |s_i| \le 10$$$) consisting only of lowercase Latin letters, where $$$|s_i|$$$ — the length of string $$$s_i$$$.

For each test case, print the answer on a separate line. If it is impossible to color all the letters of the text in red, print a single line containing the number -1. Otherwise, on the first line, print the number $$$m$$$ — the minimum number of steps it will take to turn all the letters $$$t$$$ red. Then in the next $$$m$$$ lines print pairs of indices: $$$w_j$$$ and $$$p_j$$$ ($$$1 \le j \le m$$$), which denote that the string with index $$$w_j$$$ was used as a substring to cover the occurrences starting in the text $$$t$$$ from position $$$p_j$$$. The pairs can be output in any order. If there are several answers, output any of them.

6

bababa

2

ba

aba

caba

2

bac

acab

abacabaca

3

aba

bac

aca

baca

3

a

c

b

codeforces

4

def

code

efo

forces

aaaabbbbcccceeee

4

eeee

cccc

aaaa

bbbb

NoteThe first test case is explained in the problem statement.In the second test case, it is impossible to color all the letters of the text in red.

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

enum int INF = 1<<29;

void solve() {
    string T = readln.chomp;
    int L = cast(int)T.length;
    int N = readln.chomp.to!int;
    auto S = iota(0, N, 1).map!((i) => readln.chomp).array;
    int[] f = new int[L + 1]; f[] = INF;
    int[] g = new int[L + 1]; g[] = -1;
    int[] s = new int[L + 1]; s[] = -1;
    f[0] = 0;
    for (int k = 0; k < L; k++) {
        for (int i = 0; i < N; i++) {
            int l = cast(int)S[i].length;
            if (k + l > L) continue;
            if (T[k .. k + l] == S[i]) {
                for (int j = k + 1; j <= k + l; j++) {
                    if (f[j] > f[k] + 1) {
                        f[j] = f[k] + 1;
                        g[j] = i;
                        s[j] = k;
                    }
                }
            }
        }
    }
    if (f[L] == INF) {
        writeln(-1);
    } else {
        writeln(f[L]);
        int x = L;
        while (x > 0) {
            writefln("%s %s", g[x] + 1, s[x] + 1);
            x = s[x];
        }
    }
}

void main() {
    int Q = readln.chomp.to!int;
    foreach (q; 0 .. Q) solve();
}


The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:  The players move in turns; In one move the player can remove an arbitrary letter from string s.  If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.

The input contains a single line, containing string s (1 ≤ |s|  ≤  103). String s consists of lowercase English letters.

In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.

module cf_276B;

import std.stdio;

void main() {
    immutable MAX_LETTER_COUNT = 26;
    immutable FIRST_LETTER = 'a';

    string text;
    int[MAX_LETTER_COUNT] counters;

    readf("%s\n", &text);
    for (int i = 0; i < text.length; ++i) {
        ++counters[text[i] - FIRST_LETTER];
    }

    int odds = 0;
    for (int i = 0; i < MAX_LETTER_COUNT; ++i) {
        if (counters[i] % 2 != 0) {
            ++odds;
        }
    }

    if (odds == 0 || odds % 2 != 0) {
        writeln("First");
    } else {
        writeln("Second");
    }
}


During their New Year holidays, Alice and Bob play the following game using an array $$$a$$$ of $$$n$$$ integers:   Players take turns, Alice moves first.  Each turn a player chooses any element and removes it from the array.  If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change.  Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared.For example, if $$$n = 4$$$ and $$$a = [5, 2, 7, 3]$$$, then the game could go as follows (there are other options):   On the first move, Alice chooses $$$2$$$ and get two points. Her score is now $$$2$$$. The array $$$a$$$ is now $$$[5, 7, 3]$$$.  On the second move, Bob chooses $$$5$$$ and get five points. His score is now $$$5$$$. The array $$$a$$$ is now $$$[7, 3]$$$.  On the third move, Alice chooses $$$7$$$ and get no points. Her score is now $$$2$$$. The array $$$a$$$ is now $$$[3]$$$.  On the last move, Bob chooses $$$3$$$ and get three points. His score is now $$$8$$$. The array $$$a$$$ is empty now.  Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$ used to play the game. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output on a separate line:    "Alice" if Alice wins with the optimal play;  "Bob" if Bob wins with the optimal play;  "Tie", if a tie is declared during the optimal play.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		sort !(q{a > b}) (a);
		long balance = 0;
		foreach (i; 0..n)
		{
			if (a[i] % 2 == 0 && i % 2 == 0)
			{
				balance += a[i];
			}
			if (a[i] % 2 == 1 && i % 2 == 1)
			{
				balance -= a[i];
			}
		}
		writeln (balance == 0 ? "Tie" : balance > 0 ? "Alice" : "Bob");
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		long x, y;
		foreach (i; 0..n)
		{
			if (i % 2 == a[i] % 2)
			{
				if (i % 2)
					y += a[i];
				else
					x += a[i];
			}
		}
		ans[ti] = x > y ? -1 : x < y ? 1 : 0;
	}

	foreach (e; ans)
		writeln(e == -1 ? "Alice" : e == 1 ? "Bob" : "Tie");
	stdout.flush;
	debug readln;
}


You are given a rooted tree. Each vertex contains $$$a_i$$$ tons of gold, which costs $$$c_i$$$ per one ton. Initially, the tree consists only a root numbered $$$0$$$ with $$$a_0$$$ tons of gold and price $$$c_0$$$ per ton.There are $$$q$$$ queries. Each query has one of two types:   Add vertex $$$i$$$ (where $$$i$$$ is an index of query) as a son to some vertex $$$p_i$$$; vertex $$$i$$$ will have $$$a_i$$$ tons of gold with $$$c_i$$$ per ton. It's guaranteed that $$$c_i > c_{p_i}$$$.  For a given vertex $$$v_i$$$ consider the simple path from $$$v_i$$$ to the root. We need to purchase $$$w_i$$$ tons of gold from vertices on this path, spending the minimum amount of money. If there isn't enough gold on the path, we buy all we can. If we buy $$$x$$$ tons of gold in some vertex $$$v$$$ the remaining amount of gold in it decreases by $$$x$$$ (of course, we can't buy more gold that vertex has at the moment). For each query of the second type, calculate the resulting amount of gold we bought and the amount of money we should spend.Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query, so don't forget to flush output after printing answers. You can use functions like fflush(stdout) in C++ and BufferedWriter.flush in Java or similar after each writing in your program. In standard (if you don't tweak I/O), endl flushes cout in C++ and System.out.println in Java (or println in Kotlin) makes automatic flush as well.

The first line contains three integers $$$q$$$, $$$a_0$$$ and $$$c_0$$$ ($$$1 \le q \le 3 \cdot 10^5$$$; $$$1 \le a_0, c_0 < 10^6$$$) — the number of queries, the amount of gold in the root and its price. Next $$$q$$$ lines contain descriptions of queries; The $$$i$$$-th query has one of two types:    "$$$1$$$ $$$p_i$$$ $$$a_i$$$ $$$c_i$$$" ($$$0 \le p_i < i$$$; $$$1 \le a_i, c_i < 10^6$$$): add vertex $$$i$$$ as a son to vertex $$$p_i$$$. The vertex $$$i$$$ will have $$$a_i$$$ tons of gold with price $$$c_i$$$ per one ton. It's guaranteed that $$$p_i$$$ exists and $$$c_i > c_{p_i}$$$. "$$$2$$$ $$$v_i$$$ $$$w_i$$$" ($$$0 \le v_i < i$$$; $$$1 \le w_i < 10^6$$$): buy $$$w_i$$$ tons of gold from vertices on path from $$$v_i$$$ to $$$0$$$ spending the minimum amount of money. If there isn't enough gold, we buy as much as we can. It's guaranteed that vertex $$$v_i$$$ exist.  It's guaranteed that there is at least one query of the second type.

For each query of the second type, print the resulting amount of gold we bought and the minimum amount of money we should spend.

NoteExplanation of the sample:At the first query, the tree consist of root, so we purchase $$$2$$$ tons of gold and pay $$$2 \cdot 2 = 4$$$. $$$3$$$ tons remain in the root.At the second query, we add vertex $$$2$$$ as a son of vertex $$$0$$$. Vertex $$$2$$$ now has $$$3$$$ tons of gold with price $$$4$$$ per one ton.At the third query, a path from $$$2$$$ to $$$0$$$ consists of only vertices $$$0$$$ and $$$2$$$ and since $$$c_0 < c_2$$$ we buy $$$3$$$ remaining tons of gold in vertex $$$0$$$ and $$$1$$$ ton in vertex $$$2$$$. So we bought $$$3 + 1 = 4$$$ tons and paid $$$3 \cdot 2 + 1 \cdot 4 = 10$$$. Now, in vertex $$$0$$$ no gold left and $$$2$$$ tons of gold remain in vertex $$$2$$$.At the fourth query, we add vertex $$$4$$$ as a son of vertex $$$0$$$. Vertex $$$4$$$ now has $$$1$$$ ton of gold with price $$$3$$$.At the fifth query, a path from $$$4$$$ to $$$0$$$ consists of only vertices $$$0$$$ and $$$4$$$. But since no gold left in vertex $$$0$$$ and only $$$1$$$ ton is in vertex $$$4$$$, we buy $$$1$$$ ton of gold in vertex $$$4$$$ and spend $$$1 \cdot 3 = 3$$$. Now, in vertex $$$4$$$ no gold left.

import std.stdio;
import std.ascii;
import std.algorithm;
static import core.stdc.stdio;

long[300_000+2] a;
long[300_000+2] c;

int main()
{
    int[][] parent = new int[][](300_000+2, 20);
    int q = readInt!int;
    a[0] = readInt!long;
    c[0] = readInt!long;
    parent[0][] = -1;
    int getNthParent(int v, int n)
    {
        int i = 0;
        while (n)
        {
            if (n & 1)
                v = parent[v][i];
            n >>= 1;
            i++;
        }
        return v;
    }
    foreach(i; 1 .. q + 1)
    {
        int type = readInt!int;
        if (type == 1)
        {
            int pi = readInt!int;
            long ai = readInt!long;
            long ci = readInt!long;
            parent[i][0] = pi;
            foreach(j; 1 .. 20)
            {
                if (parent[i][j - 1] > 0)
                    parent[i][j] = parent[parent[i][j - 1]][j - 1];
                else parent[i][j] = -1;
            }
            a[i] = ai;
            c[i] = ci;
        }
        else
        {
            int vi = readInt!int;
            long wi = readInt!long;
            int root = vi;
            int no = 0;
            long spent = 0;
            long bought = 0;
            foreach_reverse(j; 0 .. 20)
            {
                int possibleParent = parent[root][j];
                if (possibleParent < 0) continue;
                if (a[possibleParent] > 0)
                {
                    root = possibleParent;
                    no += (long(1) << j);
                }
            }
            debug writeln("for node ", vi, " root is ", root, " depth = ", no);
            while (wi > 0 && no >= 0)
            {
                int p = getNthParent(vi, no);
                debug writeln("Now is ", no, " ", p, " ap = ", a[p], " wi = ", wi);
                long taken = min(wi, a[p]);
                wi -= taken;
                bought += taken;
                spent += taken * c[p];
                a[p] -= taken;
                no--;
            }
            writeln(bought, " ", spent);
            stdout.flush;
        }
    }
    return 0;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
    currChar = core.stdc.stdio.getchar();
}
char topChar()
{
    return cast(char) currChar;
}
void popChar()
{
    currChar = core.stdc.stdio.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;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
    long rep;
    this(long num)
    {
        rep = num;
    }
    Z!m opBinary(string operator)(Z!m rhs)
    {
        static if (operator == "+")
        {
            long result = rhs.rep + this.rep;
            if (result >= m) result -= m;
            return Z!m(result);
        }
        else static if (operator == "-")
        {
            long result = this.rep - rhs.rep;
            if (result < 0) result += m;
            return Z!m(result);
        }
        else static if (operator == "*")
        {
            long result = this.rep * rhs.rep;
            if (result >= m) result %= m;
            return Z!m(result);
        } else static assert(text("Operator ", operator, " not supported"));
    }
    Z!m opBinary(string operator)(long exponent) if (operator == "^^")
    {
        assert(exponent >= 0);
        Z!m base = this;
        Z!m result = 1;
        while (exponent)
        {
            if (exponent & 1)
                result = result * base;
            base = base * base;
            exponent >>= 1;
        }
        return result;
    }
    invariant
    {
        assert(rep >= 0 && rep < m);
    }
}

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

immutable int maxLog = 18;

struct Node
{
	int a;
	int c;
	int [maxLog] p;
}

void main ()
{
	int q, a0, c0;
	while (readf !(" %s %s %s") (q, a0, c0) > 0)
	{
		readln;
		auto t = new Node [q + 2];
		t[0].a = a0;
		t[0].c = c0;
		t[0].p[] = q + 1;
		t[q + 1].p[] = q + 1;
		foreach (i; 1..q + 1)
		{
			auto z = readln.split;
			if (z[0] == "1")
			{
				auto p = z[1].to !(int);
				auto a = z[2].to !(int);
				auto c = z[3].to !(int);
				t[i].a = a;
				t[i].c = c;
				t[i].p[0] = p;
				foreach (d; 1..maxLog)
				{
					t[i].p[d] = t[t[i].p[d - 1]].p[d - 1];
				}
				debug {writeln (t[i].p);}
			}
			else if (z[0] == "2")
			{
				auto v = z[1].to !(int);
				auto w = z[2].to !(int);
				int step = 0;
				int r = v;
				foreach_reverse (d; 0..maxLog)
				{
					int u = t[r].p[d];
					if (t[u].a > 0)
					{
						r = u;
						step += 1 << d;
					}
				}
				int gold = 0;
				long cost = 0;
				foreach_reverse (x; 0..step + 1)
				{
					if (gold == w)
					{
						break;
					}
					int y = x;
					int u = v;
					foreach_reverse (d; 0..maxLog)
					{
						if (y >= 1 << d)
						{
							u = t[u].p[d];
							y -= 1 << d;
						}
					}
					int cur = min (w - gold, t[u].a);
					debug {writefln !("step %s, " ~
					    "take %s from %s") (x, cur, u);}
					t[u].a -= cur;
					gold += cur;
					cost += cur * 1L * t[u].c;
				}
				writeln (gold, " ", cost);
				stdout.flush ();
			}
			else
			{
				assert (false);
			}
		}
	}
}


Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)

The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.

In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.


There is an infinite 2-dimensional grid. The robot stands in cell $$$(0, 0)$$$ and wants to reach cell $$$(x, y)$$$. Here is a list of possible commands the robot can execute:  move north from cell $$$(i, j)$$$ to $$$(i, j + 1)$$$;  move east from cell $$$(i, j)$$$ to $$$(i + 1, j)$$$;  move south from cell $$$(i, j)$$$ to $$$(i, j - 1)$$$;  move west from cell $$$(i, j)$$$ to $$$(i - 1, j)$$$;  stay in cell $$$(i, j)$$$. The robot wants to reach cell $$$(x, y)$$$ in as few commands as possible. However, he can't execute the same command two or more times in a row.What is the minimum number of commands required to reach $$$(x, y)$$$ from $$$(0, 0)$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. Each of the next $$$t$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 10^4$$$) — the destination coordinates of the robot.

For each testcase print a single integer — the minimum number of commands required for the robot to reach $$$(x, y)$$$ from $$$(0, 0)$$$ if no command is allowed to be executed two or more times in a row.

NoteThe explanations for the example test:We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.In the first test case, the robot can use the following sequence: NENENENENE.In the second test case, the robot can use the following sequence: NENENEN.In the third test case, the robot can use the following sequence: ESENENE0ENESE.In the fourth test case, the robot doesn't need to go anywhere at all.In the fifth test case, the robot can use the following sequence: E0E.

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

// Main Logic Here
void play(){
    int x, y;
    x = rd!int;
    y = rd!int;
    ll tim = 2*max(x, y) - (x != y);
    writeln(tim);
}

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

/**********That's All Folks!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;    // Read input
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
alias ll = long;
alias tup = Tuple!(long, "x",  long, "y");
void show(A...)(A a) { debug{ foreach(t; a){ stderr.write(t, "| "); } stderr.writeln; } } // Debug
/* Add if TLE, T max(T = long)(T a, T b){ return (a > b) ? a : b; } */

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int x, y;
		readf !(" %s %s") (x, y);
		x = abs (x);
		y = abs (y);
		if (x < y)
		{
			swap (x, y);
		}
		string s = "***";
		int res = 0;
		while (x || y)
		{
			if (x == y)
			{
				res += x + y;
				break;
			}
			if (s[$ - 1..$] != "a")
			{
				s ~= 'a';
				x -= 1;
				res += 1;
			}
			else
			{
				s ~= 'b';
				y = max (0, y - 1);
				res += 1;
			}
		}
		debug {writeln (s);}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti] += min(x.abs, y.abs) * 2;
		auto d = max(x.abs, y.abs) - min(x.abs, y.abs);
		if (d == 0) continue;
		ans[ti] += (d-1) * 2 + 1;
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int x, y;
		readf !(" %s %s") (x, y);
		x = abs (x);
		y = abs (y);
		if (x < y)
		{
			swap (x, y);
		}
		string s = "***";
		int res = 0;
		while (x || y)
		{
			if (x == y)
			{
				res += x + y;
				break;
			}
			if (s[$ - 1..$] != "a")
			{
				s ~= 'a';
				x -= 1;
				res += 1;
			}
			else
			{
				s ~= 'b';
				y = max (0, y - 1);
				res += 1;
			}
		}
		writeln (s);
		writeln (res);
	}
}


Slastyona likes to watch life of nearby grove's dwellers. This time she watches a strange red-black spider sitting at the center of a huge cobweb.The cobweb is a set of n nodes connected by threads, each of the treads is either red of black. Using these threads, the spider can move between nodes. No thread connects a node to itself, and between any two nodes there is a unique sequence of threads connecting them.Slastyona decided to study some special qualities of the cobweb. She noticed that each of the threads has a value of clamminess x.However, Slastyona is mostly interested in jelliness of the cobweb. Consider those of the shortest paths between each pair of nodes on which the numbers of red and black threads differ at most twice. For each such path compute the product of the clamminess of threads on the path.The jelliness of the cobweb is the product of all obtained values among all paths. Those paths that differ by direction only are counted only once.Of course, this number can be huge, so Slastyona asks you to compute the jelliness of the given cobweb and print the answer modulo 109 + 7.

The first line contains the number of nodes n (2 ≤ n ≤ 105). The next n - 1 lines contain four integers each, denoting the i-th thread of the cobweb: the nodes it connects ui, vi (1 ≤ ui ≤ n, 1 ≤ vi ≤ n), the clamminess of the thread xi (1 ≤ x ≤ 109 + 6), and the color of the thread ci (). The red color is denoted by 0, and the black color is denoted by 1.

Print single integer the jelliness of the cobweb modulo 109 + 7. If there are no paths such that the numbers of red and black threads differ at most twice, print 1.

NoteIn the first example there are 4 pairs of nodes such that the numbers of threads of both colors on them differ at most twice. There pairs are (1, 3) with product of clamminess equal to 45, (1, 5) with product of clamminess equal to 45, (3, 4) with product of clamminess equal to 25 and (4, 5) with product of clamminess equal to 25. The jelliness of the cobweb is equal to 1265625.

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

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

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

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

int[][] G;
Mint ans;

void solveCentroidDecomp() {
  auto sz = new int[N];
  auto del = new bool[N];
  void dfsSz(int u, int p) {
    sz[u] = 1;
    foreach (i; G[u]) {
      const v = A[i] ^ B[i] ^ u;
      if (v != p) {
        dfsSz(v, u);
        sz[u] += sz[v];
      }
    }
  }
  dfsSz(0, -1);

  // r: centroid
  void solveSubtree(int r) {
    debug {
      string dfsDebug(int u, int p) {
        string ret = u.to!string;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v] && v != p) {
            ret ~= "(" ~ dfsDebug(v, u) ~ ")";
          }
        }
        return ret;
      }
      writeln("solveSubtree ", dfsDebug(r, -1));
    }

    int[] Is;
    foreach (i; G[r]) {
      const v = A[i] ^ B[i] ^ r;
      if (!del[v]) {
        Is ~= i;
      }
    }
    const len = cast(int)(Is.length);

    /*
      y + y' <= 2 (x + x')
      x + x' <= 2 (y + y')
    */
    alias Entry = Tuple!(int, "a", int, "b", Mint, "z");
    Entry[] es;
    auto ess = new Entry[][len];
    void dfs(int j, int u, int p, int x, int y, Mint z) {
      const e = Entry(x - 2 * y, y - 2 * x, z);
      es ~= e;
      ess[j] ~= e;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v] && v != p) {
          dfs(j, v, u, x + ((C[i] == 0) ? 1 : 0), y + ((C[i] != 0) ? 1 : 0), z * X[i]);
        }
      }
    }
    es ~= Entry(0, 0, Mint(1));
    foreach (j; 0 .. len) {
      const i = Is[j];
      const v = A[i] ^ B[i] ^ r;
      dfs(j, v, r, 0 + ((C[i] == 0) ? 1 : 0), 0 + ((C[i] != 0) ? 1 : 0), X[i]);
    }

    auto doIt(bool inv)(Entry[] fs) {
      const fsLen = cast(int)(fs.length);
      const as = fs.map!(f => f.a).array.sort.array;
      const bs = fs.map!(f => f.b).array.sort.array;
      foreach (ref f; fs) {
        int num = fsLen;
        num -= fsLen - as.upperBound(-f.a);
        num -= fsLen - bs.upperBound(-f.b);
        debug {
          writeln("  ", inv, " ", f, " ", num);
        }
        ans *= f.z^^(inv ? -num : num);
      }
    }

    doIt!false(es);
    foreach (j; 0 .. len) {
      doIt!true(ess[j]);
    }
  }

  void solveRec(int u) {
    for (; ; ) {
      int vm = -1;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v]) {
          if (vm == -1 || sz[vm] < sz[v]) {
            vm = v;
          }
        }
      }
      if (vm == -1 || sz[u] >= 2 * sz[vm]) {
        solveSubtree(u);
        del[u] = true;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            solveRec(v);
          }
        }
        break;
      } else {
        sz[u] -= sz[vm];
        sz[vm] += sz[u];
        u = vm;
      }
    }
  }
  solveRec(0);
}

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

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

      ans = 1;
      solveCentroidDecomp;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You are given a string s consisting of lowercase Latin letters. Character c is called k-dominant iff each substring of s with length at least k contains this character c.You have to find minimum k such that there exists at least one k-dominant character.

The first line contains string s consisting of lowercase Latin letters (1 ≤ |s| ≤ 100000).

Print one number — the minimum value of k such that there exists at least one k-dominant character.

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

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

    bool check(int k, char ch) {
        int v = s[0 .. k].count!(a => a == ch);

        if (!v) return false;

        foreach (i ; k .. n) {
            v += (s[i] == ch);
            v -= (s[i - k] == ch);

            if (!v) return false;
        }

        return true;
    }

    int ans = n;

    foreach (char ch ; 'a' .. 'z' + 1) {
        if (!s.canFind(ch)) continue;

        int btm = 0, top = n;

        while (top - btm > 1) {
            int mid = (btm + top) / 2;

            if (check(mid, ch)) {
                top = mid;
            }
            else {
                btm = mid;
            }
        }

        ans = min(ans, top);
    }

    writeln(ans);
}

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

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

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

void main() {
    string s;
    scan(s);

    int n = s.length.to!int;

    int ans = n;

    foreach (char ch ; 'a' .. 'z' + 1) {
        int p = -1;
        int span;

        foreach (i ; 0 .. n) {
            if (s[i] == ch) {
                span = max(span, i - p);
                p = i;
            }
        }

        span = max(span, n - p);

        ans = min(span, ans);
    }

    writeln(ans);
}

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

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


For a given sequence of distinct non-negative integers $$$(b_1, b_2, \dots, b_k)$$$ we determine if it is good in the following way:  Consider a graph on $$$k$$$ nodes, with numbers from $$$b_1$$$ to $$$b_k$$$ written on them. For every $$$i$$$ from $$$1$$$ to $$$k$$$: find such $$$j$$$ ($$$1 \le j \le k$$$, $$$j\neq i$$$), for which $$$(b_i \oplus b_j)$$$ is the smallest among all such $$$j$$$, where $$$\oplus$$$ denotes the operation of bitwise XOR (https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Next, draw an undirected edge between vertices with numbers $$$b_i$$$ and $$$b_j$$$ in this graph. We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles). It is possible that for some numbers $$$b_i$$$ and $$$b_j$$$, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.You can find an example below (the picture corresponding to the first test case). Sequence $$$(0, 1, 5, 2, 6)$$$ is not good as we cannot reach $$$1$$$ from $$$5$$$.However, sequence $$$(0, 1, 5, 2)$$$ is good.   You are given a sequence $$$(a_1, a_2, \dots, a_n)$$$ of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?It can be shown that for any sequence, we can remove some number of elements, leaving at least $$$2$$$, so that the remaining sequence is good.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 200,000$$$) — length of the sequence. The second line contains $$$n$$$ distinct non-negative integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the elements of the sequence.

You should output exactly one integer — the minimum possible number of elements to remove in order to make the remaining sequence good.

NoteNote that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.It is possible that for some numbers $$$b_i$$$ and $$$b_j$$$, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.

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

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

		int fun (R) (R a, int lo, int hi)
		{
			if (a.length < 3)
			{
				return a.length.to !(int);
			}
			auto me = (lo + hi) / 2;
			auto len = a.lowerBound (me).length.to !(int);
			auto b = a[0..len];
			auto c = a[len..$];
			if (b.empty)
			{
				return fun (c, me, hi);
			}
			else if (c.empty)
			{
				return fun (b, lo, me);
			}
			else
			{
				return 1 + max (fun (b, lo, me),
				    fun (c, me, hi));
			}
		}
		long res = 0;

		auto a = sort (z);
		writeln (n - fun (a, 0, 1 << 30));
	}
}