You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.Let instability of the array be the following value: $$$\max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i$$$.You have to remove exactly one element from this array to minimize instability of the resulting $$$(n-1)$$$-elements array. Your task is to calculate the minimum possible instability.

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

Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array $$$a$$$.

NoteIn the first example you can remove $$$7$$$ then instability of the remaining array will be $$$3 - 1 = 2$$$.In the second example you can remove either $$$1$$$ or $$$100000$$$ then instability of the remaining array will be $$$100000 - 100000 = 0$$$ and $$$1 - 1 = 0$$$ correspondingly.

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int n;
    readf!"%d"(n);
    readln;
    auto a=readln.splitter
                 .map!(to!int)
                 .array;
    sort(a);
    writeln(min(a[$-2]-a[0],a[$-1]-a[1]));
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int n;
    readf!"%d"(n);
    readln;
    auto a=readln.splitter
                 .map!(to!int)
                 .array;
    sort(a);
    writeln(min(a[$-2]-a[0],a[$-1]-a[2]));
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int n;
    readf!"%d"(n);
    readln;
    auto a=readln.splitter
                 .map!(to!int)
                 .array;
    sort(a);
    writeln(a[$-2]-a[0]);
}


You are given an array $$$a_{1}, a_{2}, \ldots, a_{n}$$$. You can remove at most one subsegment from it. The remaining elements should be pairwise distinct.In other words, at most one time you can choose two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) and delete integers $$$a_l, a_{l+1}, \ldots, a_r$$$ from the array. Remaining elements should be pairwise distinct. Find the minimum size of the subsegment you need to remove to make all remaining elements distinct.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$) — the number of elements in the given array. The next line contains $$$n$$$ spaced integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$1 \le a_{i} \le 10^{9}$$$) — the elements of the array.

Print a single integer — the minimum size of the subsegment you need to remove to make all elements of the array pairwise distinct. If no subsegment needs to be removed, print $$$0$$$.

NoteIn the first example all the elements are already distinct, therefore no subsegment needs to be removed.In the second example you can remove the subsegment from index $$$2$$$ to $$$3$$$.In the third example you can remove the subsegments from index $$$1$$$ to $$$2$$$, or from index $$$2$$$ to $$$3$$$, or from index $$$3$$$ to $$$4$$$.

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	int n = read.to!int;
	long[] as;
	foreach(i; 0 .. n) as ~= read.to!long;

	int[][long] am;
	foreach(int i, a; as){
		if(a !in am) am[a] = [];
		am[a] ~= i;
	}

	long[] amks = am.keys;

	foreach(a; amks) am[a].sort();
	log("am:", am);

	bool f(int x){
		foreach(l; 0 .. n - x + 1){
			int r = l + x - 1;
			bool isOK = 1;
			foreach(a; amks){
				if(am[a].length <= 1) continue;
				if(am[a][0] < l && am[a][$ - 1] > r) isOK = 0;
				if(am[a][1] < l || am[a][$ - 2] > r) isOK = 0;
			}
			if(isOK) return 0;
		}
		return 1;
	}

	int d = uplimit(0, n - 1, &f);

	(d + 1).writeln;
	return;

}

// a <= x <=  c の中でfをみたす最大(二分探索; binary search) ※テンプレート版
T uplimit(T)(T a, T c, bool delegate(T) f){
	if(f(c)) return c;
	if(! f(a)) return a - 1;
	while(a + 1 < c){
		T b = (a + c) / 2;
		if(f(b)) a = b;
		else c = b;
	}
	return a;
}

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

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

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

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

int N;
int[] A;

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

      int ans = N - 1;
      foreach (l; 0 .. N + 1) {
        auto set = new RedBlackTree!int;
        bool ok = true;
        foreach (i; 0 .. l) {
          ok = ok && set.insert(A[i]);
        }
        if (ok) {
          chmin(ans, N - l);
          foreach_reverse (i; l .. N) {
            if (set.insert(A[i])) {
              chmin(ans, i - l);
            } else {
              break;
            }
          }
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	int n = read.to!int;
	long[] as;
	foreach(i; 0 .. n) as ~= read.to!long;

	int[][long] am;
	foreach(int i, a; as){
		if(a !in am) am[a] = [];
		am[a] ~= i;
	}

	long[] amks = am.keys;

	foreach(a; amks) am[a].sort();
	log("am:", am);

	bool f(int x){
		foreach(l; 0 .. n - x){
			int r = l + x - 1;
			bool isOK = 1;
			foreach(a; amks){
				if(am[a].length <= 1) continue;
				if(am[a][0] < l && am[a][$ - 1] > r) isOK = 0;
				if(am[a][1] < l || am[a][$ - 2] > r) isOK = 0;
			}
			if(isOK) return 0;
		}
		return 1;
	}

	int d = uplimit(0, n - 1, &f);

	(d + 1).writeln;
	return;

}

// a <= x <=  c の中でfをみたす最大(二分探索; binary search) ※テンプレート版
T uplimit(T)(T a, T c, bool delegate(T) f){
	if(f(c)) return c;
	if(! f(a)) return a - 1;
	while(a + 1 < c){
		T b = (a + c) / 2;
		if(f(b)) a = b;
		else c = b;
	}
	return a;
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	int n = read.to!int;
	long[] as;
	foreach(i; 0 .. n) as ~= read.to!long;

	int[][long] am;
	foreach(int i, a; as){
		if(a !in am) am[a] = [];
		am[a] ~= i;
	}

	long[] amks = am.keys;
	if(amks.length == 0){
		"0".writeln;
		return;
	}
	if(amks.length == 1){
		"1".writeln;
		return;
	}

	foreach(a; amks) am[a].sort();

	bool f(int x){
		foreach(l; 0 .. n - x){
			int r = l + x - 1;
			bool isOK = 1;
			foreach(a; amks){
				if(am[a].length <= 1) continue;
				if(am[a][0] < l && am[a][$ - 1] > r) isOK = 0;
				if(am[a][1] < l || am[a][$ - 2] > r) isOK = 0;
			}
			if(isOK) return 0;
		}
		return 1;
	}

	int d = uplimit(0, n - 1, &f);

	(d + 1).writeln;
	return;

}

// a <= x <=  c の中でfをみたす最大(二分探索; binary search) ※テンプレート版
T uplimit(T)(T a, T c, bool delegate(T) f){
	if(f(c)) return c;
	if(! f(a)) return a - 1;
	while(a + 1 < c){
		T b = (a + c) / 2;
		if(f(b)) a = b;
		else c = b;
	}
	return a;
}


There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.

The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i.

Print the maximum number of teams of three people the coach can form.

NoteIn the first example the coach can form one team. For example, he can take students from the first, second and fourth groups.In the second example he can't make a single team.In the third example the coach can form three teams. For example, he can do this in the following way:  The first group (of two people) and the seventh group (of one person),  The second group (of two people) and the sixth group (of one person),  The third group (of two people) and the fourth group (of one person).

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() {
    int n;
    scan(n);
    auto a = readln.split.to!(int[]);

    int o, t;
    foreach (ai ; a) {
        if (ai == 1) o++;
        else t++;
    }

    int ans;

    if (t <= o) {
        ans += t;
        o -= t;

        ans += o / 3;
    }
    else {
        ans += o;
    }

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


In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position i + 1) if the type of this bumper is '>', or one position to the left (to i - 1) if the type of the bumper at position i is '<'. If there is no such position, in other words if i - 1 < 1 or i + 1 > n, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper.

Print one integer — the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position.

NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = readln.strip;
		long res = 0;
		while (!s.empty && s[0] == '<')
		{
			s = s[1..$];
			res += 1;
		}
		while (!s.empty && s[$ - 1] == '>')
		{
			s = s[0..$ - 1];
			res += 1;
		}
		writeln (res);
	}
}


In BerSoft $$$n$$$ programmers work, the programmer $$$i$$$ is characterized by a skill $$$r_i$$$.A programmer $$$a$$$ can be a mentor of a programmer $$$b$$$ if and only if the skill of the programmer $$$a$$$ is strictly greater than the skill of the programmer $$$b$$$ $$$(r_a > r_b)$$$ and programmers $$$a$$$ and $$$b$$$ are not in a quarrel.You are given the skills of each programmers and a list of $$$k$$$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $$$i$$$, find the number of programmers, for which the programmer $$$i$$$ can be a mentor.

The first line contains two integers $$$n$$$ and $$$k$$$ $$$(2 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le \min(2 \cdot 10^5, \frac{n \cdot (n - 1)}{2}))$$$ — total number of programmers and number of pairs of programmers which are in a quarrel. The second line contains a sequence of integers $$$r_1, r_2, \dots, r_n$$$ $$$(1 \le r_i \le 10^{9})$$$, where $$$r_i$$$ equals to the skill of the $$$i$$$-th programmer. Each of the following $$$k$$$ lines contains two distinct integers $$$x$$$, $$$y$$$ $$$(1 \le x, y \le n$$$, $$$x \ne y)$$$ — pair of programmers in a quarrel. The pairs are unordered, it means that if $$$x$$$ is in a quarrel with $$$y$$$ then $$$y$$$ is in a quarrel with $$$x$$$. Guaranteed, that for each pair $$$(x, y)$$$ there are no other pairs $$$(x, y)$$$ and $$$(y, x)$$$ in the input.

Print $$$n$$$ integers, the $$$i$$$-th number should be equal to the number of programmers, for which the $$$i$$$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.

NoteIn the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel.

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

void main ()
{
	int n, k;
	while (readf (" %s %s", &n, &k) > 0)
	{
		readln;
		auto r = readln.splitter.map !(to !(int)).array;
		auto p = n.iota.array;
		p.schwartzSort !(i => r[i]);
		auto q = new int [n];
		foreach (i; 0..n)
		{
			q[p[i]] = i;
		}

		auto a = new int [] [n];
		foreach (j; 0..k)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u -= 1;
			v -= 1;
			a[u] ~= v;
			a[v] ~= u;
		}

		auto ans = new int [n];
		int x = 0;
		foreach (i; 0..n)
		{
			int v = p[i];
			while (r[p[x]] < r[v])
			{
				x += 1;
			}
			debug {writeln (i, " ", x);}
			int res = x;
			foreach (u; a[v])
			{
				if (q[u] < x)
				{
					res -= 1;
				}
			}
			ans[v] = res;
		}
		writefln ("%(%s %)", ans);
	}
}

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

  int n, m; rd(n, m);
  auto a=readln.split.to!(int[]);
  auto g=new int[][](n);
  foreach(_; 0..m){
    int u, v; rd(u, v);
    g[u-1]~=(v-1);
    g[v-1]~=(u-1);
  }

  int[long] freq;

  struct T{int val, idx;}
  auto data=new T[](n);
  foreach(i; 0..n) data[i]=T(a[i], i);
  sort!"a.val<b.val"(data);
  auto num=new int[](n);
  foreach(int all, e; data){
    // writeln(all, " ", e.idx, " ", e.val);
    int del=0, i=e.idx;
    foreach(j; g[i]){
      if(a[j]<a[i]) del++;
    }
    // writeln("del: ", del);
    if((a[i] in freq)==null) freq[a[i]]=0;
    num[i]=all-del-(freq[a[i]]++);
    // writeln("freq: ", freq[a[i]]);
  }

  writefln("%(%s %)", num);
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}


We are given a rooted tree consisting of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. The root of the tree is the vertex $$$1$$$ and the parent of the vertex $$$v$$$ is $$$p_v$$$.There is a number written on each vertex, initially all numbers are equal to $$$0$$$. Let's denote the number written on the vertex $$$v$$$ as $$$a_v$$$.For each $$$v$$$, we want $$$a_v$$$ to be between $$$l_v$$$ and $$$r_v$$$ $$$(l_v \leq a_v \leq r_v)$$$.In a single operation we do the following:   Choose some vertex $$$v$$$. Let $$$b_1, b_2, \ldots, b_k$$$ be vertices on the path from the vertex $$$1$$$ to vertex $$$v$$$ (meaning $$$b_1 = 1$$$, $$$b_k = v$$$ and $$$b_i = p_{b_{i + 1}}$$$). Choose a non-decreasing array $$$c$$$ of length $$$k$$$ of nonnegative integers: $$$0 \leq c_1 \leq c_2 \leq \ldots \leq c_k$$$. For each $$$i$$$ $$$(1 \leq i \leq k)$$$, increase $$$a_{b_i}$$$ by $$$c_i$$$. What's the minimum number of operations needed to achieve our goal?

The first line contains an integer $$$t$$$ $$$(1\le t\le 1000)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 2 \cdot 10^5)$$$  — the number of the vertices in the tree. The second line of each test case contains $$$n - 1$$$ integers, $$$p_2, p_3, \ldots, p_n$$$ $$$(1 \leq p_i < i)$$$, where $$$p_i$$$ denotes the parent of the vertex $$$i$$$. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case output the minimum number of operations needed.

NoteIn the first test case, we can achieve the goal with a single operation: choose $$$v = 2$$$ and $$$c = [1, 2]$$$, resulting in $$$a_1 = 1, a_2 = 2$$$.In the second test case, we can achieve the goal with two operations: first, choose $$$v = 2$$$ and $$$c = [3, 3]$$$, resulting in $$$a_1 = 3, a_2 = 3, a_3 = 0$$$. Then, choose $$$v = 3, c = [2, 7]$$$, resulting in $$$a_1 = 5, a_2 = 3, a_3 = 7$$$.

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;

alias T = Tuple!(long, int);

void solve() {
    int N = readln.chomp.to!int;
    auto P = [-1] ~ readln.chomp.split(" ").map!(s => s.to!int - 1).array;
    auto L = new long[N], R = new long[N];
    foreach (i; 0 .. N) {
        readf("%d %d\n", &L[i], &R[i]);
    }

    auto G = new int[][N];
    for (int i = 0; i < N; i++) {
        if (P[i] >= 0) {
            G[P[i]] ~= i;
        }
    }

    T f(int v) {
        if (G[v].empty) {
            return T(R[v], 1);
        } else {
            T s = T(0, 0);
            foreach (c; G[v]) {
                auto r = f(c);
                s[0] += r[0];
                s[1] += r[1];
            }
            if (s[0] >= L[v]) {
                s[0] = min(R[v], s[0]);
            } else {
                s[0] = R[v];
                s[1] += 1;
            }
            return s;
        }
    }

    writeln(f(0)[1]);
}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto p = readln.splitter.map !(to !(int)).array;
		auto lo = new int [n];
		auto hi = new int [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s") (lo[i], hi[i]);
		}
		readln;

		auto adj = new int [] [n];
		foreach (j; 0..n - 1)
		{
			adj[p[j] - 1] ~= j + 1;
		}

		auto sat = new long [n];
		int res = 0;

		void recur (int v)
		{
			foreach (u; adj[v])
			{
				recur (u);
				sat[v] += sat[u];
			}
			sat[v] = min (sat[v], hi[v]);
			if (sat[v] < lo[v])
			{
				sat[v] = hi[v];
				res += 1;
			}
		}

		recur (0);
		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 N;
int[] P;
long[] L, R;

int[][] graph;

alias Result = Tuple!(long, "val", int, "cost");

Result solve(int u) {
  long sum;
  int cost;
  foreach (v; graph[u]) {
    const res = solve(v);
    sum += res.val;
    cost += res.cost;
  }
  Result ret;
  if (L[u] <= sum) {
    ret.val = min(sum, R[u]);
    ret.cost = cost;
  } else {
    ret.val = R[u];
    ret.cost = cost + 1;
  }
  debug {
    writeln(u, ": ", ret);
  }
  return ret;
}

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        N = readInt;
        P = new int[N];
        P[0] = -1;
        foreach (u; 1 .. N) {
          P[u] = readInt - 1;
        }
        L = new long[N];
        R = new long[N];
        foreach (u; 0 .. N) {
          L[u] = readLong;
          R[u] = readLong;
        }

        graph = new int[][N];
        foreach (u; 1 .. N) {
          graph[P[u]] ~= u;
        }

        const ans = solve(0);
        writeln(ans.cost);
      }
    }
  } catch (EOFException e) {
  }
}

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;

alias T = Tuple!(long, int);

void solve() {
    int N = readln.chomp.to!int;
    auto P = [-1] ~ readln.chomp.split(" ").map!(s => s.to!int - 1).array;
    auto L = new long[N], R = new long[N];
    foreach (i; 0 .. N) {
        readf("%d %d\n", &L[i], &R[i]);
    }

    auto G = new int[][N];
    for (int i = 0; i < N; i++) {
        if (P[i] >= 0) {
            G[P[i]] ~= i;
        }
    }

    T f(int v) {
        if (G[v].empty) {
            return T(R[v], 1);
        } else {
            T s = T(0, 0);
            foreach (c; G[v]) {
                auto r = f(c);
                s[0] += r[0];
                s[1] += r[1];
            }
            if (s[0] >= L[v]) {
                s[0] = max(R[v], s[0]);
            } else {
                s[0] = R[v];
                s[1] += 1;
            }
            return s;
        }
    }

    writeln(f(0)[1]);
}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto p = readln.splitter.map !(to !(int)).array;
		auto lo = new int [n];
		auto hi = new int [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s") (lo[i], hi[i]);
		}
		readln;

		auto adj = new int [] [n];
		foreach (j; 0..n - 1)
		{
			adj[p[j] - 1] ~= j + 1;
		}

		auto sat = new long [n];
		int res = 0;

		void recur (int v)
		{
			foreach (u; adj[v])
			{
				recur (u);
				sat[v] += sat[u];
			}
			if (sat[v] < lo[v])
			{
				sat[v] = hi[v];
				res += 1;
			}
		}

		recur (0);
		writeln (res);
	}
}


This is the harder version of the problem. In this version, $$$1 \le n, m \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.You are given a sequence of integers $$$a=[a_1,a_2,\dots,a_n]$$$ of length $$$n$$$. Its subsequence is obtained by removing zero or more elements from the sequence $$$a$$$ (they do not necessarily go consecutively). For example, for the sequence $$$a=[11,20,11,33,11,20,11]$$$:  $$$[11,20,11,33,11,20,11]$$$, $$$[11,20,11,33,11,20]$$$, $$$[11,11,11,11]$$$, $$$[20]$$$, $$$[33,20]$$$ are subsequences (these are just some of the long list);  $$$[40]$$$, $$$[33,33]$$$, $$$[33,20,20]$$$, $$$[20,20,11,11]$$$ are not subsequences. Suppose that an additional non-negative integer $$$k$$$ ($$$1 \le k \le n$$$) is given, then the subsequence is called optimal if:  it has a length of $$$k$$$ and the sum of its elements is the maximum possible among all subsequences of length $$$k$$$;  and among all subsequences of length $$$k$$$ that satisfy the previous item, it is lexicographically minimal. Recall that the sequence $$$b=[b_1, b_2, \dots, b_k]$$$ is lexicographically smaller than the sequence $$$c=[c_1, c_2, \dots, c_k]$$$ if the first element (from the left) in which they differ less in the sequence $$$b$$$ than in $$$c$$$. Formally: there exists $$$t$$$ ($$$1 \le t \le k$$$) such that $$$b_1=c_1$$$, $$$b_2=c_2$$$, ..., $$$b_{t-1}=c_{t-1}$$$ and at the same time $$$b_t<c_t$$$. For example:  $$$[10, 20, 20]$$$ lexicographically less than $$$[10, 21, 1]$$$,  $$$[7, 99, 99]$$$ is lexicographically less than $$$[10, 21, 1]$$$,  $$$[10, 21, 0]$$$ is lexicographically less than $$$[10, 21, 1]$$$. You are given a sequence of $$$a=[a_1,a_2,\dots,a_n]$$$ and $$$m$$$ requests, each consisting of two numbers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$). For each query, print the value that is in the index $$$pos_j$$$ of the optimal subsequence of the given sequence $$$a$$$ for $$$k=k_j$$$.For example, if $$$n=4$$$, $$$a=[10,20,30,20]$$$, $$$k_j=2$$$, then the optimal subsequence is $$$[20,30]$$$ — it is the minimum lexicographically among all subsequences of length $$$2$$$ with the maximum total sum of items. Thus, the answer to the request $$$k_j=2$$$, $$$pos_j=1$$$ is the number $$$20$$$, and the answer to the request $$$k_j=2$$$, $$$pos_j=2$$$ is the number $$$30$$$.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the sequence $$$a$$$. The second line contains elements of the sequence $$$a$$$: integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). The third line contains an integer $$$m$$$ ($$$1 \le m \le 2\cdot10^5$$$) — the number of requests. The following $$$m$$$ lines contain pairs of integers $$$k_j$$$ and $$$pos_j$$$ ($$$1 \le k \le n$$$, $$$1 \le pos_j \le k_j$$$) — the requests.

Print $$$m$$$ integers $$$r_1, r_2, \dots, r_m$$$ ($$$1 \le r_j \le 10^9$$$) one per line: answers to the requests in the order they appear in the input. The value of $$$r_j$$$ should be equal to the value contained in the position $$$pos_j$$$ of the optimal subsequence for $$$k=k_j$$$.

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

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

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

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

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

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

// min pos s.t. pred(sum of [0, pos))
//   assume pred(sum of [0, pos)) is non-decreasing
int bBinarySearch(alias pred, T)(T[] bit) {
  import core.bitop : bsr;
  import std.functional : unaryFun;
  alias predFun = unaryFun!pred;
  if (predFun(0)) return 0;
  int pos = 0;
  T sum = 0;
  foreach_reverse (e; 0 .. bsr(bit.length) + 1) {
    const x = (pos | 1 << e) - 1;
    if (x < bit.length && !predFun(sum + bit[x])) {
      pos |= 1 << e;
      sum += bit[x];
    }
  }
  return pos + 1;
}

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

      auto queries = new int[][N + 1];
      foreach (m; 0 .. M) {
        queries[K[m]] ~= m;
      }
      auto ans = new int[M];

      auto as = new Tuple!(int, int)[N];
      foreach (i; 0 .. N) {
        as[i] = tuple(A[i], i);
      }
      as.sort!((a, b) => ((a[0] != b[0]) ? (a[0] > b[0]) : (a[1] < b[1])));

      auto bit = new int[N];
      foreach (i; 0 .. N) {
        bit.bAdd(as[i][1], 1);
        foreach (m; queries[i + 1]) {
          const res = bit.bBinarySearch!(s => (s >= P[m]));
          ans[m] = A[res - 1];
        }
      }

      foreach (m; 0 .. M) {
        writeln(ans[m]);
      }
    }
  } catch (EOFException e) {
  }
}


Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.

The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).  Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.

Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.

import core.bitop;
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;

immutable int MOD = 1_000_000_007;

int powmod (int a, int b)
{
	int res = 1;
	for ( ; b; b >>= 1)
	{
		if (b & 1)
		{
			res = (res * 1L * a) % MOD;
		}
		a = (a * 1L * a) % MOD;
	}
	return res;
}

void main ()
{
	immutable int MAX_N = 200_009;

	auto fact = new int [MAX_N];
	fact[0] = 1;
	foreach (i; 1..MAX_N)
	{
		fact[i] = (fact[i - 1] * 1L * i) % MOD;
	}

	auto invf = new int [MAX_N];
	foreach (i; 0..MAX_N)
	{
		invf[i] = powmod (fact[i], MOD - 2);
	}

	int ways (int r, int c)
	{
		int res = fact[r + c];
		res = (res * 1L * invf[r]) % MOD;
		res = (res * 1L * invf[c]) % MOD;
		return res;
	}

	int h, w, n;
	while (readf (" %s %s %s", &h, &w, &n) > 0)
	{
		alias Cell = Tuple !(int, "r", int, "c");
		auto a = new Cell [n];
		foreach (ref e; a)
		{
			readf (" %s %s", &e.r, &e.c);
		}
		a ~= Cell (1, 1);
		a ~= Cell (h, w);
		sort !(q{a < b}, SwapStrategy.stable) (a);
		assert (a[0] == Cell (1, 1));
		assert (a[n + 1] == Cell (h, w));

		auto f = new int [2] [n + 2];
		f[0][1] = 1;
		foreach (i; 1..n + 2)
		{
			foreach (j; 0..i)
			{
				int dr = a[i].r - a[j].r;
				int dc = a[i].c - a[j].c;
				if (dr < 0 || dc < 0)
				{
					continue;
				}
				foreach (k; 0..2)
				{
					f[i][k] = (f[i][k] + f[j][!k] * 1L *
					    ways (dr, dc)) % MOD;
				}
			}
		}

		writeln ((f[n + 1][0] - f[n + 1][1] + MOD) % MOD);
	}
}


You are given an array $$$A$$$ of length $$$N$$$ weights of masses $$$A_1$$$, $$$A_2$$$...$$$A_N$$$. No two weights have the same mass. You can put every weight on one side of the balance (left or right). You don't have to put weights in order $$$A_1$$$,...,$$$A_N$$$. There is also a string $$$S$$$ consisting of characters "L" and "R", meaning that after putting the $$$i-th$$$ weight (not $$$A_i$$$, but $$$i-th$$$ weight of your choice) left or right side of the balance should be heavier. Find the order of putting the weights on the balance such that rules of string $$$S$$$ are satisfied.

The first line contains one integer $$$N$$$ ($$$1 \leq N \leq 2*10^5$$$) - the length of the array $$$A$$$ The second line contains $$$N$$$ distinct integers: $$$A_1$$$, $$$A_2$$$,...,$$$A_N$$$ ($$$1 \leq A_i \leq 10^9$$$) - the weights given The third line contains string $$$S$$$ of length $$$N$$$ consisting only of letters "L" and "R" - string determining which side of the balance should be heavier after putting the $$$i-th$$$ weight of your choice

The output contains $$$N$$$ lines. In every line, you should print one integer and one letter - integer representing the weight you are putting on the balance in that move and the letter representing the side of the balance where you are putting the weight. If there is no solution, print $$$-1$$$.

NoteExplanation for the test case:  after the 1st weight: 3 L (left side is heavier)after the 2nd weight: 2 R (left side is heavier)after the 3rd weight: 8 R (right side is heavier)after the 4th weight: 13 L (left side is heavier)after the 5th weight: 7 L (left side is heavier)So, the rules given by string $$$S$$$ are fulfilled and our order of putting the weights is correct.

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 long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
      }
      A.sort;
      const S = readToken();

      auto cs = new char[N];
      cs[N - 1] = S[N - 1];
      foreach_reverse (i; 0 .. N - 1) {
        cs[i] = 'L' ^ 'R' ^ cs[i + 1];
      }

      int cnt;
      char last = '@';
      foreach (s; S) {
        if (last != s) {
          ++cnt;
        }
        last = s;
      }

      int l = N - cnt, r = N - cnt;
      last = '@';
      foreach (s; S) {
        int i;
        if (last != s) {
          i = r++;
        } else {
          i = --l;
        }
        writeln(A[i], " ", cs[i]);
        last = s;
      }
    }
  } catch (EOFException e) {
  }
}


You have a set of $$$n$$$ discs, the $$$i$$$-th disc has radius $$$i$$$. Initially, these discs are split among $$$m$$$ towers: each tower contains at least one disc, and the discs in each tower are sorted in descending order of their radii from bottom to top.You would like to assemble one tower containing all of those discs. To do so, you may choose two different towers $$$i$$$ and $$$j$$$ (each containing at least one disc), take several (possibly all) top discs from the tower $$$i$$$ and put them on top of the tower $$$j$$$ in the same order, as long as the top disc of tower $$$j$$$ is bigger than each of the discs you move. You may perform this operation any number of times.For example, if you have two towers containing discs $$$[6, 4, 2, 1]$$$ and $$$[8, 7, 5, 3]$$$ (in order from bottom to top), there are only two possible operations:  move disc $$$1$$$ from the first tower to the second tower, so the towers are $$$[6, 4, 2]$$$ and $$$[8, 7, 5, 3, 1]$$$;  move discs $$$[2, 1]$$$ from the first tower to the second tower, so the towers are $$$[6, 4]$$$ and $$$[8, 7, 5, 3, 2, 1]$$$. Let the difficulty of some set of towers be the minimum number of operations required to assemble one tower containing all of the discs. For example, the difficulty of the set of towers $$$[[3, 1], [2]]$$$ is $$$2$$$: you may move the disc $$$1$$$ to the second tower, and then move both discs from the second tower to the first tower.You are given $$$m - 1$$$ queries. Each query is denoted by two numbers $$$a_i$$$ and $$$b_i$$$, and means "merge the towers $$$a_i$$$ and $$$b_i$$$" (that is, take all discs from these two towers and assemble a new tower containing all of them in descending order of their radii from top to bottom). The resulting tower gets index $$$a_i$$$.For each $$$k \in [0, m - 1]$$$, calculate the difficulty of the set of towers after the first $$$k$$$ queries are performed.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le m \le n \le 2 \cdot 10^5$$$) — the number of discs and the number of towers, respectively. The second line contains $$$n$$$ integers $$$t_1$$$, $$$t_2$$$, ..., $$$t_n$$$ ($$$1 \le t_i \le m$$$), where $$$t_i$$$ is the index of the tower disc $$$i$$$ belongs to. Each value from $$$1$$$ to $$$m$$$ appears in this sequence at least once. Then $$$m - 1$$$ lines follow, denoting the queries. Each query is represented by two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le m$$$, $$$a_i \ne b_i$$$), meaning that, during the $$$i$$$-th query, the towers with indices $$$a_i$$$ and $$$b_i$$$ are merged ($$$a_i$$$ and $$$b_i$$$ are chosen in such a way that these towers exist before the $$$i$$$-th query).

Print $$$m$$$ integers. The $$$k$$$-th integer ($$$0$$$-indexed) should be equal to the difficulty of the set of towers after the first $$$k$$$ queries are performed.

NoteThe towers in the example are:  before the queries: $$$[[5, 1], [2], [7, 4, 3], [6]]$$$;  after the first query: $$$[[2], [7, 5, 4, 3, 1], [6]]$$$;  after the second query: $$$[[7, 5, 4, 3, 2, 1], [6]]$$$;  after the third query, there is only one tower: $$$[7, 6, 5, 4, 3, 2, 1]$$$.

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

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		readln;
		auto a = 0 ~ readln.splitter.map !(to !(int)).array ~ 0;
		auto p = new int [] [m + 1];
		foreach (i; 0..n)
		{
			p[a[i + 1]] ~= i + 1;
		}
		int total = 0;
		foreach (i; 1..n)
		{
			if (a[i] != a[i + 1])
			{
				total += 1;
			}
		}
		writeln (total);
		foreach (j; 1..m)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			if (p[u].length < p[v].length)
			{
				swap (u, v);
			}
			auto w = a[p[u][0]];
			foreach (c; p[v])
			{
				if (a[c] != a[c - 1])
				{
					total -= 1;
				}
				if (a[c] != a[c + 1])
				{
					total -= 1;
				}
				a[c] = w;
				if (a[c] != a[c - 1])
				{
					total += 1;
				}
				if (a[c] != a[c + 1])
				{
					total += 1;
				}
				p[u] ~= c;
			}
			p[v] = p[u];
			writeln (total);
			debug {writeln (a);}
		}
	}
}


Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.

The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.

Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.

NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and  for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.

import std.stdio;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		int [int] cx;
		int [int] cy;
		int [int [2]] cz;
		foreach (i; 0..n)
		{
			int x, y;
			readf (" %s %s", &x, &y);
			cx[x]++;
			cy[y]++;
			cz[[x, y]]++;
		}
		long res = 0;
		foreach (v; cx)
		{
			res += (v * 1L * (v - 1)) / 2;
		}
		foreach (v; cy)
		{
			res += (v * 1L * (v - 1)) / 2;
		}
		foreach (v; cz)
		{
			res -= (v * 1L * (v - 1)) / 2;
		}
		writeln (res);
	}
}


This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format:  $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$  $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$).

After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower).

NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.

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

immutable int limit = 9;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		int [int] num;
		int [limit] good;

		void account (int v, int delta)
		{
			num[v] += 0;
			foreach (i; 0..min (limit, num[v] + 1))
			{
				good[i] += delta;
			}
		}

		void change (int v, int delta)
		{
			account (v, -1);
			num[v] += delta;
			account (v, +1);
		}

		foreach (ref c; a)
		{
			change (c, +1);
		}
		int q;
		readf !(" %s") (q);
		readln;

		bool can ()
		{
			if (good[8] >= 1)
			{
				return true;
			}
			if (good[6] >= 1 && good[2] >= 2)
			{
				return true;
			}
			if (good[4] >= 2)
			{
				return true;
			}
			if (good[4] >= 1 && good[2] >= 3)
			{
				return true;
			}
			return false;
		}

		foreach (j; 0..q)
		{
			auto t = readln.split;
			change (t[1].to !(int), (t[0] == "+" ? +1 : -1));
			writeln (can () ? "YES" : "NO");
		}
	}
}

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

alias type = single;
struct TestCase
{
  mixin prettyPrinting;

  long n;
  @Dim("n") long[] a;
  long q;
  @Dim("q") Tuple!(string, long)[] events;

  void solve(long tc = -1)
  {
    long[long] store;
    foreach(ai; a)
      {
        store.require(ai, 0)++;
      }
    auto mostUnits = redBlackTree!((a, b) {
        if (a[0] > b[0])
          return true;
        if (a[0] < b[0])
          return false;
        return a[1] < b[1];
      }, Tuple!(long, long))();
    foreach(t, c; store)
      {
        mostUnits.insert(tuple(c, t));
      }

  nextEvent:foreach(event; events)
      {
        string type = event[0];
        long x = event[1];
        store.require(x, 0);
        mostUnits.removeKey(tuple(store[x], x));
        store[x] += type == "+"? 1 : -1;
        mostUnits.insert(tuple(store[x], x));
        auto arr = mostUnits[].take(3).map!(t => t[0]).array;
        if (arr[0] >= 4)
          {
            arr[0] -= 4;
            foreach(v; arr)
              {
                if (v >= 4)
                  {
                    writeln("YES");
                    continue nextEvent;
                  }
              }
            foreach(i; 0 .. arr.length - 1)
              {
                if (arr[i] >= 2 && arr[i + 1] >= 2)
                  {
                    writeln("YES");
                    continue nextEvent;
                  }
              }
            writeln("NO");
          }
        else
          {
            writeln("NO");
          }
      }
  }
}

struct Interval
{
  long l, h;

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

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

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

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

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

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

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

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

DList!string _words;

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

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

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

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

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

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto n = RD!int;
	auto a = RDA!int;
	auto q = RD!int;

	auto cnt = new int[](10^^5+1);
	long a2, a4, a6, a8;
	void update1(int x)
	{
		if (cnt[x] == 8)
		{
			++a8;
			--a6;
		}
		else if (cnt[x] == 6)
		{
			++a6;
			--a4;
		}
		else if (cnt[x] == 4)
		{
			++a4;
			--a2;
		}
		else if (cnt[x] == 2)
		{
			++a2;
		}
	}
	void update2(int x)
	{
		if (cnt[x] == 7)
		{
			--a8;
			++a6;
		}
		else if (cnt[x] == 5)
		{
			--a6;
			++a4;
		}
		else if (cnt[x] == 3)
		{
			--a4;
			++a2;
		}
		else if (cnt[x] == 1)
		{
			--a2;
		}
	}
	foreach (i; 0..n)
	{
		++cnt[a[i]];
		update1(a[i]);
	}
	foreach (i; 0..q)
	{
		auto s = RD!string;
		auto x = RD!int;
		if (s == "+")
		{
			++cnt[x];
			update1(x);
		}
		else
		{
			--cnt[x];
			update2(x);
		}
		auto ans = a4 >= 1 || a6 >= 1 || a8 >= 1;
		ans &= a2 + a4*2 + a6*3 + a8*4 >= 4;
		writeln(ans ? "YES" : "NO");
	}

	stdout.flush;
	debug readln;
}


Ela loves reading a lot, just like her new co-workers in DTL! On her first day after becoming an engineer in DTL, she is challenged by a co-worker to sort a heap of books into different compartments on the shelf.$$$n$$$ books must be split into $$$k$$$ compartments on the bookshelf ($$$n$$$ is divisible by $$$k$$$). Each book is represented by a lowercase Latin letter from 'a' to 'y' inclusively, which is the beginning letter in the title of the book.Ela must stack exactly $$$\frac{n}{k}$$$ books in each compartment. After the books are stacked, for each compartment indexed from $$$1$$$ to $$$k$$$, she takes the minimum excluded (MEX) letter of the multiset of letters formed by letters representing all books in that compartment, then combines the resulting letters into a string. The first letter of the resulting string is the MEX letter of the multiset of letters formed by the first compartment, the second letter of the resulting string is the MEX letter of the multiset of letters formed by the second compartment, ... and so on. Please note, under the constraint of this problem, MEX letter can always be determined for any multiset found in this problem because 'z' is not used.What is the lexicographically greatest resulting string possible that Ela can create?A string $$$a$$$ is lexicographically greater than a string $$$b$$$ if and only if one of the following holds:  $$$b$$$ is a prefix of $$$a$$$, but $$$b \ne a$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears later in the alphabet than the corresponding letter in $$$b$$$. The minimum excluded (MEX) letter of a multiset of letters is the letter that appears earliest in the alphabet and is not contained in the multiset. For example, if a multiset of letters contains $$$7$$$ letters 'b', 'a', 'b', 'c', 'e', 'c', 'f' respectively, then the MEX letter of this compartment is 'd', because 'd' is not included in the multiset, and all letters comes before 'd' in the alphabet, namely 'a', 'b' and 'c', are included in the multiset.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 200$$$; $$$1 \le k \le n$$$). It is guaranteed that $$$n$$$ is divisible by $$$k$$$. The second line of each test case contains a string of $$$n$$$ lowercase Latin letters from 'a' to 'y' inclusively. Each letter represents the starting letter of the title of a book in the initial heap. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.

For each test case, output a string of $$$k$$$ letters which is the most optimal string that Ela can find.

5

12 3

cabccadabaac

12 6

cabccadabaac

12 12

cabccadabaac

25 1

abcdefghijklmnopqrstuvwxy

10 5

bcdxedbcfg

NoteIn the first test case, the books can be divided into $$$3$$$ compartments as below:  the first compartment contains the books with indices $$$1, 2, 3, 7$$$: $$$multiset_1 = \{$$$'c', 'a', 'b', 'd'$$$\}$$$ $$$\rightarrow$$$ $$$MEX(multiset_1) =$$$ 'e'  the second compartment contains the books with indices $$$4, 5, 6, 9$$$ : $$$multiset_2 = \{$$$'c', 'c', 'a', 'b'$$$\}$$$ $$$\rightarrow$$$ $$$MEX(multiset_2) =$$$ 'd'  the third compartment contains the remaining books $$$8, 10, 11, 12$$$ : $$$multiset_3 = \{$$$ 'a', 'a', 'a', 'c'$$$\}$$$ $$$\rightarrow$$$ $$$MEX(multiset_3) =$$$ 'b' Therefore, the answer is 'edb'. It can be proven that there is no way that Ela can arrange the books so that it results in a lexicographically greater string.

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

void solve() {
    int N, K; readf("%d %d\n", &N, &K);
    auto S = readln.chomp;

    int[char] s;
    foreach (c; S) {
        s[c] = s.get(c, 0) + 1;
    }

    char[] ans = new char[K];
    for (int i = 0; i < K; i++) {
        char x = '?';
        int n = 0;
        for (char c = 'a'; c <= 'z'; c++, n++) {
            if (n == N/K) {
                x = c;
                break;
            } else if (c !in s || s[c] == 0) {
                x = c;
                break;
            } else {
                s[c]--;
            }
        }
        ans[i] = x;
    }
    writeln(ans);
}

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

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

immutable int letters = 26;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto s = readln.strip;
		auto c = new int [letters];
		foreach (ref x; s)
		{
			c[x - 'a'] += 1;
		}
		string res;
		foreach (i; 0..k)
		{
			int x = 0;
			while (x < n / k && c[x] > 0)
			{
				c[x] -= 1;
				x += 1;
			}
			res ~= cast (char) (x + 'a');
		}
		writeln (res);
	}
}


To satisfy his love of matching socks, Phoenix has brought his $$$n$$$ socks ($$$n$$$ is even) to the sock store. Each of his socks has a color $$$c_i$$$ and is either a left sock or right sock. Phoenix can pay one dollar to the sock store to either:   recolor a sock to any color $$$c'$$$ $$$(1 \le c' \le n)$$$  turn a left sock into a right sock  turn a right sock into a left sock  The sock store may perform each of these changes any number of times. Note that the color of a left sock doesn't change when it turns into a right sock, and vice versa. A matching pair of socks is a left and right sock with the same color. What is the minimum cost for Phoenix to make $$$n/2$$$ matching pairs? Each sock must be included in exactly one matching pair.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$l$$$, and $$$r$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$n$$$ is even; $$$0 \le l, r \le n$$$; $$$l+r=n$$$) — the total number of socks, and the number of left and right socks, respectively. The next line contains $$$n$$$ integers $$$c_i$$$ ($$$1 \le c_i \le n$$$) — the colors of the socks. The first $$$l$$$ socks are left socks, while the next $$$r$$$ socks are right socks. It is guaranteed that the sum of $$$n$$$ across all the test cases will not exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer — the minimum cost for Phoenix to make $$$n/2$$$ matching pairs. Each sock must be included in exactly one matching pair.

NoteIn the first test case, Phoenix can pay $$$2$$$ dollars to:   recolor sock $$$1$$$ to color $$$2$$$  recolor sock $$$3$$$ to color $$$2$$$  There are now $$$3$$$ matching pairs. For example, pairs $$$(1, 4)$$$, $$$(2, 5)$$$, and $$$(3, 6)$$$ are matching.In the second test case, Phoenix can pay $$$3$$$ dollars to:   turn sock $$$6$$$ from a right sock to a left sock  recolor sock $$$3$$$ to color $$$1$$$  recolor sock $$$4$$$ to color $$$1$$$  There are now $$$3$$$ matching pairs. For example, pairs $$$(1, 3)$$$, $$$(2, 4)$$$, and $$$(5, 6)$$$ are matching.

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

		auto cnt = new int[](n);
		foreach (i; 0..l)
			++cnt[c[i]];
		foreach (i; l..n)
			--cnt[c[i]];

		long[] ls, rs;
		long odd_l, odd_r;
		long cnt_l, cnt_r;
		foreach (i; 0..n)
		{
			if (cnt[i] > 0)
			{
				ls ~= cnt[i];
				cnt_l += cnt[i];
				if (cnt[i] % 2)
					++odd_l;
			}
			else if (cnt[i] < 0)
			{
				rs ~= -cnt[i];
				cnt_r += -cnt[i];
				if ((-cnt[i]) % 2)
					++odd_r;
			}
		}
		{
			auto x = min(odd_l, odd_r);
			odd_l -= x;
			odd_r -= x;
			cnt_l -= x;
			cnt_r -= x;
			ans[ti] += x;

			if (odd_l != 0)
			{
				auto y = min(odd_l, cnt_r);
				odd_l -= y;
				cnt_l -= y;
				cnt_r -= y;
				ans[ti] += y;
			}
			else if (odd_r != 0)
			{
				auto y = min(odd_r, cnt_l);
				odd_r -= y;
				cnt_l -= y;
				cnt_r -= y;
				ans[ti] += y;
			}

			if (odd_l != 0)
			{
				cnt_l -= odd_l;
				ans[ti] += odd_l;
			}
			else if (odd_r != 0)
			{
				cnt_r -= odd_r;
				ans[ti] += odd_r;
			}

			ans[ti] += (cnt_l + cnt_r) / 2;
		}
	}

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

import std.algorithm, std.range, std.stdio, std.numeric, std.array,
       std.container, std.typecons, std.conv, std.random, std.bigint;

void read(S...)(ref S args) {
  auto input = readln.split;
  assert(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T); }

void main() {
  int t;
  read(t);

  while (t--) {
    int n, l, r;
    read(n, l, r);

    auto data = list!int;
    auto count = new int[n + 1];
    foreach (i; 0 .. l) {
      count[data[i]]--;
    }
    foreach (i; l .. n) {
      count[data[i]]++;
    }

    alias Sock = Tuple!(bool, "odd", int, "count");
    auto left = count.filter!(a => a < 0).map!(a => Sock(-a % 2 == 1, -a)).array.heapify;
    auto right = count.filter!(a => a > 0).map!(a => Sock(a % 2 == 1, a)).array.heapify;

    int cost = 0;

    while (!left.empty && !right.empty && (left.front.odd || right.front.odd)) {
      auto x = left.removeAny;
      auto y = right.removeAny;
      if (x.count > 1) left.insert(Sock(!x.odd, x.count - 1));
      if (y.count > 1) right.insert(Sock(!y.odd, y.count - 1));
      cost++;
    }

    foreach (h; [left, right]) {
      while (!h.empty) {
        auto x = h.removeAny;
        if (x.odd) {
          h.insert(Sock(!x.odd, x.count - 1));
          cost++;
        } else {
          cost += x.count / 2;
        }
      }
    }

    writeln(cost);
  }
}

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 n, l, r;
		readf !(" %s %s %s") (n, l, r);
		readln;
		auto c = readln.splitter.map !(to !(int)).array;
		c[] -= 1;

		auto b = new int [n];
		foreach (i; 0..l)
		{
			b[c[i]] += 1;
		}
		foreach (i; l..n)
		{
			b[c[i]] -= 1;
		}
		debug {writeln (b);}

		int lo = 0;
		int hi = 0;
		foreach (j; 0..n)
		{
			if (b[j] & 1)
			{
				if (b[j] > 0)
				{
					hi += 1;
					b[j] -= 1;
				}
				else
				{
					lo += 1;
					b[j] += 1;
				}
			}
		}

		int res = min (lo, hi);
		lo -= res;
		hi -= res;
		debug {writeln (res, " ", lo, " ", hi);}
		debug {writeln (b);}

		foreach (j; 0..n)
		{
			if (lo > 0 && b[j] > 0)
			{
				int cur = min (+b[j], lo);
				res += cur;
				b[j] -= cur;
				lo -= cur;
			}
			if (hi > 0 && b[j] < 0)
			{
				int cur = min (-b[j], hi);
				res += cur;
				b[j] += cur;
				hi -= cur;
			}
		}
		res += lo;
		res += hi;

		foreach (j; 0..n)
		{
			res += abs (b[j]) / 2;
			b[j] %= 2;
		}

		res += b.map !(abs).sum;
		writeln (res);
	}
}


One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile:    By the pieces lay a large square wooden board. The board is divided into $$$n^2$$$ cells arranged into $$$n$$$ rows and $$$n$$$ columns. Some of the cells are already occupied by single tiles stuck to it. The remaining cells are free.Alice started wondering whether she could fill the board completely using the pieces she had found. Of course, each piece has to cover exactly five distinct cells of the board, no two pieces can overlap and every piece should fit in the board entirely, without some parts laying outside the board borders. The board however was too large for Alice to do the tiling by hand. Can you help determine if it's possible to fully tile the board?

The first line of the input contains a single integer $$$n$$$ ($$$3 \leq n \leq 50$$$) — the size of the board. The following $$$n$$$ lines describe the board. The $$$i$$$-th line ($$$1 \leq i \leq n$$$) contains a single string of length $$$n$$$. Its $$$j$$$-th character ($$$1 \leq j \leq n$$$) is equal to "." if the cell in the $$$i$$$-th row and the $$$j$$$-th column is free; it is equal to "#" if it's occupied. You can assume that the board contains at least one free cell.

Output YES if the board can be tiled by Alice's pieces, or NO otherwise. You can print each letter in any case (upper or lower).

NoteThe following sketches show the example boards and their tilings if such tilings exist:

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T read(T)(){ return read.to!T; }
T[] read(T)(long n){ return n.iota.map!(_ => read!T).array; }
T[][] read(T)(long m, long n){ return m.iota.map!(_ => read!T(n)).array; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){
	int n = read.to!int;

	bool[][] as;
	foreach(i; 0 .. n){
		as ~= readln.to!(char[]).map!(x => x == '#').array;
	}

	string ans = "YES";

	foreach(i; 0 .. n) foreach(j; 0 .. n){
		if(as[i][j]) continue;
		if(j - 1 < 0 || i + 2 >= n || j + 1 >= n){
			"NO".writeln;
			return;
		}
		if(as[i + 1][j - 1] || as[i + 1][j] || as[i + 1][j + 1] || as[i + 2][j]){
			"NO".writeln;
			return;
		}
		as[i][j] = 1;
		as[i + 1][j - 1] = 1;
		as[i + 1][j] = 1;
		as[i + 1][j + 1]  = 1;
		as[i + 2][j] = 1;
	}

	"YES".writeln;
	return;

}

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

  int n;
  rd(n);
  auto a = new char[][](n);
  foreach (i; 0 .. n) {
    a[i] = readln.chomp.to!(char[]);
  }
  if (a[0][0] == '.' || a[0][n - 1] == '.' || a[n - 1][0] == '.' || a[n - 1][n - 1] == '.') {
    writeln("NO");
    return;
  }
  for (int i = 1; i + 1 < n; i++) {
    for (int j = 1; j + 1 < n; j++) {
      if (a[i][j] == '.') {
        if (a[i - 1][j] == '#' || a[i][j - 1] == '#' || a[i + 1][j] == '#' || a[i][j + 1] == '#') {
          continue;
        }
        a[i][j] = a[i - 1][j] = a[i][j - 1] = a[i + 1][j] = a[i][j + 1] = '#';
      }
    }
  }
  foreach (i; 0 .. n) {
    foreach (j; 0 .. n) {
      if (a[i][j] == '.') {
        writeln("NO");
        return;
      }
    }
  }
  writeln("YES");
}

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

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

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison : equal;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;

alias Tree = RBT!int;

void main()
{
    GC.disable();

    uint n;
    readf(" %s\n", n);

    char[][] s;
    foreach (i; 0 .. n)
    {
        auto ss = readln();
        s ~= ss.strip.dup;
    }

    foreach (i; 0 .. n)
    {
        foreach (j; 0 .. n)
        {
            if (s[i][j] == '.')
            {
                foreach (delta; [[0, 0], [1, -1], [1, 0], [1, 1], [2, 0]])
                {
                    auto ni = i + delta[0];
                    auto nj = j + delta[1];
                    if (ni >= n || nj >= n || s[ni][nj] != '.')
                    {
                        writeln("NO");
                        return;
                    }
                    else
                    {
                        s[ni][nj] = '#';
                    }

                }

            }

        }

    }

    writeln("YES");

}

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; }
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; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

long mod = 10^^9 + 7;
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 N = RD!uint;
	auto s = new char[][](N);
	foreach (i; 0..N)
	{
		s[i] = RD!(char[]);
	}

	bool visit(uint y, uint x)
	{
		if (s[y+1][x] == '#' ||
			s[y+1][x-1] == '#' ||
			s[y+1][x+1] == '#' ||
			s[y+2][x] == '#')
			return false;

		s[y][x] = '#';
		s[y+1][x] = '#';
		s[y+1][x-1] = '#';
		s[y+1][x+1] = '#';
		s[y+2][x] = '#';
		return true;
	}

	bool ans = true;
	(){
	foreach (y; 0..N)
	{
		foreach (x; 0..N)
		{
			if (s[y][x] == '#') continue;

			debug writeln(y, ":", x);
			if (x == 0 || x == N-1)
			{
				ans = false;
				return;
			}
			else if (y >= N-2)
			{
				ans = false;
				return;
			}

			auto r = visit(y, x);
			if (!r)
			{
				ans = false;
				return;
			}
		}
	}}();

	writeln(ans ? "YES" : "NO");
	stdout.flush();
	debug readln();
}