William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $$$c_1, c_2, \dots, c_n$$$ where $$$c_i$$$ is the number of consecutive brackets "(" if $$$i$$$ is an odd number or the number of consecutive brackets ")" if $$$i$$$ is an even number.For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $$$[3, 2, 1, 3]$$$.You need to find the total number of continuous subsequences (subsegments) $$$[l, r]$$$ ($$$l \le r$$$) of the original bracket sequence, which are regular bracket sequences.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1000)$$$, the size of the compressed sequence. The second line contains a sequence of integers $$$c_1, c_2, \dots, c_n$$$ $$$(1 \le c_i \le 10^9)$$$, the compressed sequence.

Output a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences. It can be proved that the answer fits in the signed 64-bit integer data type.

NoteIn the first example a sequence (((()(()))( is described. This bracket sequence contains $$$5$$$ subsegments which form regular bracket sequences:  Subsequence from the $$$3$$$rd to $$$10$$$th character: (()(()))  Subsequence from the $$$4$$$th to $$$5$$$th character: ()  Subsequence from the $$$4$$$th to $$$9$$$th character: ()(())  Subsequence from the $$$6$$$th to $$$9$$$th character: (())  Subsequence from the $$$7$$$th to $$$8$$$th character: () In the second example a sequence ()))(()(()))) is described.In the third example a sequence ()()(()) is described.

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 c = readln.splitter.map !(to !(long)).array;

		int [long] pos;
		long balance = 0;
		pos[balance] = 0;
		foreach (int i, num; c)
		{
			balance += num * ((i & 1) ? -1 : +1);
			pos[balance] = int.max;
		}
		auto posToSort = pos.byKey.array;
		sort (posToSort);
		foreach (int k, long v; posToSort)
		{
			pos[v] = k;
		}
		debug {writeln (posToSort);}

		auto value = new long [pos.length];
		long res = 0;
		balance = 0;
		foreach (int i, num; c)
		{
			auto oldBalance = balance;
			balance += num * ((i & 1) ? -1 : +1);
			auto oldPos = pos[oldBalance];
			auto newPos = pos[balance];
			while (oldPos < newPos)
			{
				value[oldPos] += 1;
				oldPos += 1;
			}
			while (oldPos > newPos)
			{
				auto len = (posToSort[oldPos] -
				   posToSort[oldPos - 1]);
				value[oldPos] = 0;
				oldPos -= 1;
				res += value[oldPos] +
				    ((value[oldPos] > 0) ? (len - 1) : 0);
			}
			debug {writeln (value, " ", res, " ", balance);}
		}

		writeln (res);
	}
}

immutable multi = false;

void solve(int tc)
{
	auto n = readInt!int;
	auto c = ma(n, readInt!long);
	foreach(i, ref ci; c)
	{
		if (i % 2 == 0)
		{
			ci = ci;
		}
		else
		{
			ci = -ci;
		}
	}
	auto psum = new long[](n + 1);
	psum[0] = 0;
	foreach(i, ci; c)
	{
		psum[i+1] = psum[i] + ci;
	}
	auto psumMin = Sparse!(long, min, "min")(psum);
	long ways = 0;
	void countFor(int i, int j)
	{
		assert(i < j);
		assert(i % 2 == 0 && j % 2 == 1);
		if (j == i + 1)
		{
			assert(c[i] > 0 && -c[j] > 0);
			ways += min(c[i], -c[j]);
			return;
		}
		auto pi = psum[i+1];
		auto mr = psumMin[i+2..j+1].min - pi;
		auto rqOpen = max(0, -mr);
		if (rqOpen > c[i]) return;
		auto rqClose = psum[j] - psum[i+1] + rqOpen;
		assert(rqClose >= 0);
		// open >= rqOpen
		// open <= c[i]
		// open + psum[j] - psum[i+1] <= -c[j]
		// rqOpen <= open <= min(c[i], -c[j] - psum[j] + psum[i+1])
		auto low = rqOpen;
		auto high = min(c[i], -c[j]-psum[j]+psum[i+1]);
		if (low > high) return;
		ways += high - low + 1;
	}
	foreach(i; 0 .. n)
	{
		foreach(j; i + 1 .. n)
		{
			if (i % 2 == 0 && j % 2 == 1)
				countFor(i, j);
		}
	}
	ways.writeln;
}

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

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

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

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

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

// sparse table V, f, fName {{{
struct Sparse(V, alias f, string fName = "value")
{
	import std.math : log2;
	V[][] _table;
	int[] maxPow;
	this(V[] values)
	{
		auto n = values.length;
		maxPow = new int[](n + 1);
		maxPow[0] = int.min;
		maxPow[1] = 0;
		foreach(i; 2 .. n + 1)
		{
			int prev = maxPow[i - 1];
			maxPow[i] = prev;
			prev = (1 << prev);
			if (prev * 2 <= i) maxPow[i]++;
		}
		_table = new V[][](maxPow[n] + 1, n);
		_table[0][] = values[];

		foreach(p; 1 .. maxPow[n] + 1)
		foreach(i; 0 .. n - (1<<p) + 1)
			_table[p][i] = f(_table[p-1][i], _table[p-1][i+(1<<(p-1))]);
	}
	int[2] opSlice(size_t i)(size_t start, size_t end) if (i == 0)
	{
		return [cast(int)start, cast(int)end];
	}
	auto opIndex(int[2] slice)
	{
		int sliceLen = slice[1] - slice[0];
		auto x = maxPow[sliceLen];
		auto twoX = (1 << x);
		auto p1 = _table[x][slice[0]];
		auto p2 = _table[x][slice[1] - twoX];
		struct Ans
		{
			mixin(q{V }, fName, q{;});
		}
		return Ans(f(p1, p2));
	}
}

unittest
{
	import std.algorithm;
	import std.stdio;
	alias MinQ = Sparse!(int, min, "min");
	writeln("testing");
	int[] array = [1, 2, 3, 4, -2, -2, -3, 0, 10];
	auto minQ = MinQ(array);
	foreach(i; 0 .. array.length)
	{
		foreach(j; i + 1 .. array.length + 1)
		{
			assert(minQ[i .. j].min == array[i .. j].fold!min);
		}
	}
}
// }}}

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 c = readln.splitter.map !(to !(long)).array;

		int [long] pos;
		long balance = 0;
		pos[balance] = 0;
		foreach (int i, num; c)
		{
			balance += num * ((i & 1) ? -1 : +1);
			pos[balance] = int.max;
		}
		auto posToSort = pos.byKey.array;
		sort (posToSort);
		foreach (int k, long v; posToSort)
		{
			pos[v] = k;
		}
		debug {writeln (posToSort);}

		auto value = new long [pos.length];
		long res = 0;
		balance = 0;
		foreach (int i, num; c)
		{
			auto oldBalance = balance;
			balance += num * ((i & 1) ? -1 : +1);
			auto oldPos = pos[oldBalance];
			auto newPos = pos[balance];
			while (oldPos < newPos)
			{
				value[oldPos] += 1;
				oldPos += 1;
			}
			while (oldPos > newPos)
			{
				auto len = (posToSort[oldPos] -
				   posToSort[oldPos - 1]);
				value[oldPos] = 0;
				oldPos -= 1;
				res += value[oldPos] +
				    (value[oldPos > 0] ? (len - 1) : 0);
			}
			debug {writeln (value, " ", res, " ", balance);}
		}

		writeln (res);
	}
}

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 c = readln.splitter.map !(to !(long)).array;

		int [long] pos;
		long balance = 0;
		pos[balance] = 0;
		foreach (int i, num; c)
		{
			balance += num * ((i & 1) ? -1 : +1);
			pos[balance] = int.max;
		}
		auto posToSort = pos.byKey.array;
		sort (posToSort);
		foreach (int k, long v; posToSort)
		{
			pos[v] = k;
		}
		debug {writeln (posToSort);}

		auto value = new long [pos.length];
		long res = 0;
		balance = 0;
		foreach (int i, num; c)
		{
			auto oldBalance = balance;
			balance += num * ((i & 1) ? -1 : +1);
			auto oldPos = pos[oldBalance];
			auto newPos = pos[balance];
			while (oldPos < newPos)
			{
				value[oldPos] += 1;
				oldPos += 1;
			}
			while (oldPos > newPos)
			{
				auto len = (posToSort[oldPos] -
				   posToSort[oldPos - 1]);
				value[oldPos] = 0;
				oldPos -= 1;
				res += value[oldPos] + len - 1;
			}
			debug {writeln (value, " ", res, " ", balance);}
		}

		writeln (res);
	}
}

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 c = readln.splitter.map !(to !(long)).array;

		int [long] pos;
		long balance = 0;
		pos[balance] = 0;
		foreach (int i, num; c)
		{
			balance += num * ((i & 1) ? -1 : +1);
			pos[balance] = int.max;
		}
		auto posToSort = pos.byKey.array;
		sort (posToSort);
		foreach (int k, long v; posToSort)
		{
			pos[v] = k;
		}
		debug {writeln (posToSort);}

		auto value = new long [pos.length];
		long res = 0;
		balance = 0;
		foreach (int i, num; c)
		{
			auto oldBalance = balance;
			balance += num * ((i & 1) ? -1 : +1);
			auto oldPos = pos[oldBalance];
			auto newPos = pos[balance];
			while (oldPos < newPos)
			{
				value[oldPos] += 1;
				oldPos += 1;
			}
			while (oldPos > newPos)
			{
				auto len = (posToSort[oldPos] -
				   posToSort[oldPos - 1]);
				value[oldPos] = 0;
				oldPos -= 1;
				res += value[oldPos] * len;
			}
			debug {writeln (value, " ", res, " ", balance);}
		}

		writeln (res);
	}
}


You are given a tree with $$$n$$$ vertices. You are allowed to modify the structure of the tree through the following multi-step operation:  Choose three vertices $$$a$$$, $$$b$$$, and $$$c$$$ such that $$$b$$$ is adjacent to both $$$a$$$ and $$$c$$$.  For every vertex $$$d$$$ other than $$$b$$$ that is adjacent to $$$a$$$, remove the edge connecting $$$d$$$ and $$$a$$$ and add the edge connecting $$$d$$$ and $$$c$$$.  Delete the edge connecting $$$a$$$ and $$$b$$$ and add the edge connecting $$$a$$$ and $$$c$$$. As an example, consider the following tree:  The following diagram illustrates the sequence of steps that happen when we apply an operation to vertices $$$2$$$, $$$4$$$, and $$$5$$$:  It can be proven that after each operation, the resulting graph is still a tree.Find the minimum number of operations that must be performed to transform the tree into a star. A star is a tree with one vertex of degree $$$n - 1$$$, called its center, and $$$n - 1$$$ vertices of degree $$$1$$$.

The first line contains an integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$)  — the number of vertices in the tree. The $$$i$$$-th of the following $$$n - 1$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \neq v_i$$$) denoting that there exists an edge connecting vertices $$$u_i$$$ and $$$v_i$$$. It is guaranteed that the given edges form a tree.

Print a single integer  — the minimum number of operations needed to transform the tree into a star. It can be proven that under the given constraints, it is always possible to transform the tree into a star using at most $$$10^{18}$$$ operations.

NoteThe first test case corresponds to the tree shown in the statement. As we have seen before, we can transform the tree into a star with center at vertex $$$5$$$ by applying a single operation to vertices $$$2$$$, $$$4$$$, and $$$5$$$.In the second test case, the given tree is already a star with the center at vertex $$$4$$$, so no operations have to be performed.

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[] A, B;

int[][] G;
int[] dep;

void dfs(int u, int p) {
  dep[u] = (p == -1) ? 0 : (dep[p] + 1);
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfs(v, u);
    }
  }
}

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

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

      int[2] freq;
      foreach (u; 0 .. N) {
        ++freq[dep[u] % 2];
      }
      const ans = min(freq[0] - 1, freq[1] - 1);
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.Ahcl wants to construct a beautiful string. He has a string $$$s$$$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!More formally, after replacing all characters '?', the condition $$$s_i \neq s_{i+1}$$$ should be satisfied for all $$$1 \leq i \leq |s| - 1$$$, where $$$|s|$$$ is the length of the string $$$s$$$.

The first line contains positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contain the descriptions of test cases. Each line contains a non-empty string $$$s$$$ consisting of only characters 'a', 'b', 'c' and '?'.  It is guaranteed that in each test case a string $$$s$$$ has at least one character '?'. The sum of lengths of strings $$$s$$$ in all test cases does not exceed $$$10^5$$$.

For each test case given in the input print the answer in the following format:   If it is impossible to create a beautiful string, print "-1" (without quotes);  Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.

NoteIn the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.In the second test case, it is impossible to create a beautiful string, because the $$$4$$$-th and $$$5$$$-th characters will be always equal.In the third test case, the only answer is "acbac".

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; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

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

void main()
{
	auto t = RD!int;
	auto ans = new string[](t);
	foreach (i; 0..t)
	{
		auto s = RD!string;
		foreach (j; 0..s.length)
		{
			if (s[j] == '?')
			{
				int num1 = -1, num2 = -1;
				if (j != 0)
					num1 = ans[i][$-1] - 'a';
				if (j != s.length-1)
					if (s[j+1] != '?')
						num2 = s[j+1] - 'a';

				int num3;
				if (num1 != -1)
				{
					num3 = (num1+1) % 3;
				}
				if (num3 == num2)
				{
					num3 = (num2+1) % 3;
				}
				ans[i] ~= cast(char)('a' + num3);
			}
			else
				ans[i] ~= s[j];
		}
		bool ok = true;
		foreach (j; 1..ans[i].length)
		{
			if (ans[i][j] == ans[i][j-1])
			{
				ok = false;
				break;
			}
		}
		debug writeln(ans[i]);
		if (!ok)
			ans[i].length = 0;
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln(-1);
		else
			writeln(e);
	}
	stdout.flush;
	debug readln;
}


One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as n measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had made his friend Petya redo the experiment because the largest and the smallest results differed by more than two times. Vasya is lazy, and he does not want to redo the experiment. He wants to do the task and go home play computer games. So he decided to cheat: before Vasya shows the measurements to the teacher, he will erase some of them, so as to make the largest and the smallest results of the remaining measurements differ in no more than two times. In other words, if the remaining measurements have the smallest result x, and the largest result y, then the inequality y ≤ 2·x must fulfill. Of course, to avoid the teacher's suspicion, Vasya wants to remove as few measurement results as possible from his notes.Help Vasya, find what minimum number of measurement results he will have to erase from his notes so that the largest and the smallest of the remaining results of the measurements differed in no more than two times.

The first line contains integer n (2 ≤ n ≤ 105) — the number of measurements Vasya made. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 5000) — the results of the measurements. The numbers on the second line are separated by single spaces.

Print a single integer — the minimum number of results Vasya will have to remove.

NoteIn the first sample you can remove the fourth and the sixth measurement results (values 8 and 7). Then the maximum of the remaining values will be 5, and the minimum one will be 3. Or else, you can remove the third and fifth results (both equal 3). After that the largest remaining result will be 8, and the smallest one will be 4.

import std.stdio : File, writeln, writefln;
import std.array;
import std.range;
import std.algorithm :min, filter;

const INF = 1<<28;

int n;
int[] arr;

void swap(T)(ref T a, ref T b){
	T tmp = a;
	a = b;
	b = tmp;
}

File ifp;
File ofp;

void main(){
	ifp = File("input.txt", "r");
	ofp = File("output.txt", "w");

	int n = next!int();
	int[int] list;
	int[][int] list_;
	int[] c = new int[n];
	int max_ = -1, min_ = INF, max_idx, min_idx;
	for(int i=0; i<n; ++i){
		c[i] = next!int();
		list[c[i]] = i;
		list_[c[i]] ~= i;
	}

	int[] values;
	foreach(i, v; list){
		values ~= i;
	}
	values.sort;

	int ans = INF;

	LOOP:
	for(int i=0; 0<values.length; ++i){
		if(i>0){
			values.popFront;
		}
		auto v_ = values.clone;
		for(int j=0; 0<values.length; ++j){
			if(j>0){
				values.popBack;
			}
			int x = values.front;
			int y = values.back;
			if(y<=x*2){
				int count;
				foreach(v; values){
					count += list_[v].length;
				}
				int ans_ = n - count;

				ans = min(ans, ans_);
				if(j==0){
					break LOOP;
				}
				break;
			}
		}

		values = v_.clone;
	}

	ofp.writeln = ans;
}

import std.stdio : readln, chomp;
import std.conv : to;
import std.string : split;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

//	string str = readln;
	string str = ifp.readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}


This is the second subtask of problem F. The only differences between this and the first subtask are the constraints on the value of $$$m$$$ and the time limit. It is sufficient to solve this subtask in order to hack it, but you need to solve both subtasks in order to hack the first one.There are $$$n+1$$$ distinct colours in the universe, numbered $$$0$$$ through $$$n$$$. There is a strip of paper $$$m$$$ centimetres long initially painted with colour $$$0$$$. Alice took a brush and painted the strip using the following process. For each $$$i$$$ from $$$1$$$ to $$$n$$$, in this order, she picks two integers $$$0 \leq a_i < b_i \leq m$$$, such that the segment $$$[a_i, b_i]$$$ is currently painted with a single colour, and repaints it with colour $$$i$$$. Alice chose the segments in such a way that each centimetre is now painted in some colour other than $$$0$$$. Formally, the segment $$$[i-1, i]$$$ is painted with colour $$$c_i$$$ ($$$c_i \neq 0$$$). Every colour other than $$$0$$$ is visible on the strip.Count the number of different pairs of sequences $$$\{a_i\}_{i=1}^n$$$, $$$\{b_i\}_{i=1}^n$$$ that result in this configuration. Since this number may be large, output it modulo $$$998244353$$$.

The first line contains a two integers $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 500$$$, $$$n \leq m \leq 10^6$$$) — the number of colours excluding the colour $$$0$$$ and the length of the paper, respectively. The second line contains $$$m$$$ space separated integers $$$c_1, c_2, \ldots, c_m$$$ ($$$1 \leq c_i \leq n$$$) — the colour visible on the segment $$$[i-1, i]$$$ after the process ends. It is guaranteed that for all $$$j$$$ between $$$1$$$ and $$$n$$$ there is an index $$$k$$$ such that $$$c_k = j$$$.

Output a single integer — the number of ways Alice can perform the painting, modulo $$$998244353$$$.

NoteIn the first example, there are $$$5$$$ ways, all depicted in the figure below. Here, $$$0$$$ is white, $$$1$$$ is red, $$$2$$$ is green and $$$3$$$ is blue.Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour $$$2$$$.In the second example, Alice must first paint segment 0 3 with colour $$$1$$$ and then segment 1 2 with colour $$$2$$$.

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

struct ModInt(long M) {
  long x;
  this(in ModInt a) { x = a.x; }
  this(in long a) { x = a % M; if (x < 0) x += M; }
  ModInt opUnary(string op)() if (op == "-") { return ModInt(-x); }
  ref ModInt opOpAssign(string op)(in 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 *= a.x; x %= M; }
    else static assert(false);
    return this;
  }
  ModInt opOpAssign(string op)(in long a) { return mixin("this " ~ op ~ "= ModInt(a)"); }
  ModInt opBinary(string op, T)(in T a) const { return mixin("ModInt(this) " ~ op ~ "= a"); }
  ModInt opBinaryRight(string op)(in long a) const { return mixin("ModInt(a) " ~ op ~ "= this"); }
  string toString() const { return x.to!string; }
}

enum long MO = 998244353;
alias Mint = ModInt!MO;

int N, M;
int[] C;

int segN;
int[] seg;
void segInit() {
  for (segN = 1; segN < M; segN <<= 1) {}
  seg = new int[2 * segN];
  foreach (i; 0 .. M) {
    seg[segN + i] = C[i];
  }
  foreach_reverse (a; 1 .. segN) {
    seg[a] = min(seg[a << 1], seg[a << 1 | 1]);
  }
}
int segRangeMin(int a, int b) {
  int ret = N;
  for (a += segN, b += segN; a < b; a >>= 1, b >>= 1) {
    if (a & 1) chmin(ret, seg[a++]);
    if (b & 1) chmin(ret, seg[--b]);
  }
  return ret;
}

int[][] poss;
int[] as, bs;

int xsLen;
int[] xs;

bool[][] mem0;
bool[] mem1;
bool[][] mem2;
Mint[][] dp0;
Mint[] dp1;
Mint[][] dp2;

Mint calc0(int e, int f) {
  if (!mem0[e][f]) {
    if (e == f) {
      dp0[e][f] = Mint(1);
    } else {
      const u = segRangeMin(xs[e], xs[f]);
      const g = xs.lowerBound(as[u]);
      const h = xs.lowerBound(bs[u]);
      debug {
        // writeln("  calc0 ", e, " ", f, ": ", u, " ", g, " ", h);
      }
      dp0[e][f] = calc2(e, g) * calc1(u) * calc2(h, f);
    }
    debug {
      writeln("calc0 ", e, " ", f, " = ", dp0[e][f]);
    }
    mem0[e][f] = true;
  }
  return dp0[e][f];
}
Mint calc1(int u) {
  if (!mem1[u]) {
    dp1[u] = Mint(1);
    foreach (k; 0 .. cast(int)(poss[u].length) - 1) {
      if (poss[u][k] + 1 < poss[u][k + 1]) {
        const e = xs.lowerBound(poss[u][k] + 1);
        const f = xs.lowerBound(poss[u][k + 1]);
        dp1[u] *= calc0(e, f);
      }
    }
    debug {
      writeln("calc1 ", u, " = ", dp1[u]);
    }
    mem1[u] = true;
  }
  return dp1[u];
}
Mint calc2(int e, int f) {
  if (!mem2[e][f]) {
    for (int g = e; ; ) {
      debug {
        // writeln("  calc2 ", e, " ", f, ": ", g);
      }
      dp2[e][f] += calc0(e, g) * calc0(g, f);
      if (g == f) {
        break;
      }
      g = xs.lowerBound(bs[C[xs[g]]]);
    }
    debug {
      writeln("calc2 ", e, " ", f, " = ", dp2[e][f]);
    }
    mem2[e][f] = true;
  }
  return dp2[e][f];
}

void main() {
  try {
    for (; ; ) {
      N = readInt();
      M = readInt();
      C = new int[M];
      foreach (i; 0 .. M) {
        C[i] = readInt() - 1;
      }
      debug {
        writeln("C = ", C);
      }

      segInit();

      poss = new int[][N];
      foreach (i; 0 .. M) {
        poss[C[i]] ~= i;
      }
      as = new int[N];
      bs = new int[N];
      foreach (u; 0 .. N) {
        assert(!poss[u].empty);
        as[u] = poss[u][0];
        bs[u] = poss[u][$ - 1] + 1;
      }
      bool ok = true;
      foreach (u; 0 .. N) foreach (v; u + 1 .. N) {
        if (max(as[u], as[v]) < min(bs[u], bs[v])) {
          debug {
            writeln("intersecting ", u, " ", v);
          }
          // ok = ok && (as[u] <= as[v] && bs[v] <= bs[u]);
          const k = poss[u].lowerBound(as[v]) - 1;
          ok = ok && (k >= 0 && poss[u][k] + 1 <= as[v] && bs[v] <= poss[u][k + 1]);
        }
      }

      if (ok) {
        xs = (as.dup ~ bs.dup).sort.uniq.array;
        xsLen = cast(int)(xs.length);
        debug {
          writeln("xs = ", xs);
        }

        debug {
          foreach (u; 0 .. N) {
            writeln(u, ": ", poss[u]);
            foreach (k; 0 .. cast(int)(poss[u].length) - 1) {
              if (poss[u][k] + 1 < poss[u][k + 1]) {
                const e = xs.lowerBound(poss[u][k] + 1);
                const f = xs.lowerBound(poss[u][k + 1]);
                assert(xs[e] == poss[u][k] + 1);
                assert(xs[f] == poss[u][k + 1]);
              }
            }
          }
        }

        dp0 = new Mint[][](xsLen, xsLen);
        dp1 = new Mint[N];
        dp2 = new Mint[][](xsLen, xsLen);
        mem0 = new bool[][](xsLen, xsLen);
        mem1 = new bool[N];
        mem2 = new bool[][](xsLen, xsLen);
        const ans = calc0(0, xsLen - 1);
        writeln(ans);
      } else {
        writeln(0);
      }
    }
  } catch (EOFException e) {
  }
}


Timur has a stairway with $$$n$$$ steps. The $$$i$$$-th step is $$$a_i$$$ meters higher than its predecessor. The first step is $$$a_1$$$ meters higher than the ground, and the ground starts at $$$0$$$ meters.   The stairs for the first test case. Timur has $$$q$$$ questions, each denoted by an integer $$$k_1, \dots, k_q$$$. For each question $$$k_i$$$, you have to print the maximum possible height Timur can achieve by climbing the steps if his legs are of length $$$k_i$$$. Timur can only climb the $$$j$$$-th step if his legs are of length at least $$$a_j$$$. In other words, $$$k_i \geq a_j$$$ for each step $$$j$$$ climbed.Note that you should answer each question independently.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n, q$$$ ($$$1 \leq n, q \leq 2\cdot10^5$$$) — the number of steps and the number of questions, respectively. The second line of each test case contains $$$n$$$ integers ($$$1 \leq a_i \leq 10^9$$$) — the height of the steps. The third line of each test case contains $$$q$$$ integers ($$$0 \leq k_i \leq 10^9$$$) — the numbers for each question. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2\cdot10^5$$$, and the sum of $$$q$$$ does not exceed $$$2\cdot10^5$$$.

For each test case, output a single line containing $$$q$$$ integers, the answer for each question. Please note, that the answer for some questions won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

NoteConsider the first test case, pictured in the statement.   If Timur's legs have length $$$1$$$, then he can only climb stair $$$1$$$, so the highest he can reach is $$$1$$$ meter.  If Timur's legs have length $$$2$$$ or $$$4$$$, then he can only climb stairs $$$1$$$, $$$2$$$, and $$$3$$$, so the highest he can reach is $$$1+2+1=4$$$ meters.  If Timur's legs have length $$$9$$$ or $$$10$$$, then he can climb the whole staircase, so the highest he can reach is $$$1+2+1+5=9$$$ meters.  In the first question of the second test case, Timur has no legs, so he cannot go up even a single step. :(

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n, q;
    readf!" %d %d "(n, q);
    auto a = readln.splitter.map!(to!long).array;
    auto qarr = readln.splitter.map!(to!long).array;
    long[] maxa;
    long[] suma;
    long m = 0;
    long sum = 0;
    suma ~= 0;
    foreach (x ; a) {
      m = max(m, x);
      maxa ~= m;
      sum += x;
      suma ~= sum;
    }
    writefln("%(%s %)", qarr.map!(k => suma[maxa.assumeSorted.lowerBound(k + 1).length]));
  }
}

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

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

void solve() {
    int N, Q; readf("%d %d\n", &N, &Q);
    auto A = readarray!int;
    auto K = readarray!int;

    auto S = new int[N + 1];
    auto AS = new long[N + 1];
    for (int i = 0; i < N; i++) {
        S[i + 1] = max(S[i], A[i]);
        AS[i + 1] = AS[i] + A[i];
    }

    int[] ans;
    foreach (q; 0 .. Q) {
        int k = K[q];
        int lb = 0, ub = N;
        bool C(int x) {
            return S[x] <= k;
        }
        if (C(ub)) {
            ans ~= ub;
        } else {
            while (lb + 1 < ub) {
                int mid = (lb + ub) / 2;
                (C(mid) ? lb : ub) = mid;
            }
            ans ~= lb;
        }
    }
    writefln("%(%s %)", ans.map!(i => AS[i]).array);
}

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


A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.

The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≤ xi, yi, zi ≤ 100).

Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not.

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

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

    int[3] total;
    foreach(_; 0..n)
        total[] += to!(int[])(readln.split)[];

    if(any(total[]))
        writeln("NO");
    else
        writeln("YES");
}

import std.stdio;
import std.string;
import core.stdc.stdio;
import std.math;
import std.algorithm;

class Vec3
{
	public int x, y, z;
	public this()
	{
	}

	public this(int x, int y, int z)
	{
		this.x = x;
		this.y = y;
		this.z = z;
	}

	public Vec3 opBinary(string op)(Vec3 rhs)
	{
		static if (op == "+") return new Vec3(x + rhs.x, y + rhs.y, z + rhs.z);
		else static assert(0, "Operator "~op~" not implemented");
	}
}

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	Vec3 sum = new Vec3();
	foreach (int i; 0..n)
	{
		Vec3 v = new Vec3();
		scanf("%d %d %d", &(v.x), &(v.y), &(v.z));
		sum = sum + v;
	}
	bool condition = (sum.x == 0 && sum.y == 0 && sum.z == 0);
	printf(condition ? "YES" : "NO");
	return 0;
}

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

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

	int[] coord = [ 0, 0, 0 ];
	for (int i = 0; i < n; i++) {
		int[] row = readln.chomp.split.map!(to!int).array;
		coord[] += row[];
	}

	if (coord.all!("a == 0")) {
		"YES".writeln;
	} else {
		"NO".writeln;
	}
}

//prewritten code: https://github.com/antma/algo
module Solution;
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader ();
  const n = r.next!uint;
  auto a = new int[3];
  foreach (tid; 0 .. n) {
    auto b = r.nextA!int (3);
    a[] += b[];
  }
  writeln (a.all!(i => i == 0) ? "YES" : "NO");
}


Vitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer 54 42, but an increasing integer sequence $$$a_1, \ldots, a_n$$$. In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence $$$b_1, \ldots, b_n$$$ using the following rules:  $$$b_1 = a_1$$$; $$$b_i = a_i \oplus a_{i - 1}$$$ for all $$$i$$$ from 2 to $$$n$$$, where $$$x \oplus y$$$ is the bitwise XOR of $$$x$$$ and $$$y$$$. It is easy to see that the original sequence can be obtained using the rule $$$a_i = b_1 \oplus \ldots \oplus b_i$$$.However, some time later Vitya discovered that the integers $$$b_i$$$ in the cypher got shuffled, and it can happen that when decrypted using the rule mentioned above, it can produce a sequence that is not increasing. In order to save his reputation in the scientific community, Vasya decided to find some permutation of integers $$$b_i$$$ so that the sequence $$$a_i = b_1 \oplus \ldots \oplus b_i$$$ is strictly increasing. Help him find such a permutation or determine that it is impossible.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). The second line contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$ ($$$1 \leq b_i < 2^{60}$$$).

If there are no valid permutations, print a single line containing "No". Otherwise in the first line print the word "Yes", and in the second line print integers $$$b'_1, \ldots, b'_n$$$ — a valid permutation of integers $$$b_i$$$. The unordered multisets $$$\{b_1, \ldots, b_n\}$$$ and $$$\{b'_1, \ldots, b'_n\}$$$ should be equal, i. e. for each integer $$$x$$$ the number of occurrences of $$$x$$$ in the first multiset should be equal to the number of occurrences of $$$x$$$ in the second multiset. Apart from this, the sequence $$$a_i = b'_1 \oplus \ldots \oplus b'_i$$$ should be strictly increasing. If there are multiple answers, print any of them.

NoteIn the first example no permutation is valid.In the second example the given answer lead to the sequence $$$a_1 = 4$$$, $$$a_2 = 8$$$, $$$a_3 = 15$$$, $$$a_4 = 16$$$, $$$a_5 = 23$$$, $$$a_6 = 42$$$.

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

void main() {
    immutable int MAX = 61;

    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    auto B = new long[][](MAX);
    foreach (a; A) B[a.bsr] ~= a;
    foreach (i; 0..MAX) B[i].sort();

    int M = 0;
    foreach (i; 0..MAX) if (B[i].length > 0) M = i;

    long X = 0;
    foreach (a; A) X ^= a;
    long[] ans;

    while (true) {
        bool ok = false;
        foreach (i; 0..MAX) {
            if ((X & (1L << i)) && !B[i].empty) {
                ok = true;
                X ^= B[i].back;
                ans ~= B[i].back;
                B[i].popBack;
                break;
            }
        }
        if (!ok) break;
    }

    if (ans.length < N) {
        writeln("No");
        return;
    }

    writeln("Yes");
    ans.reverse();
    ans.map!(to!string).join(" ").writeln;
}


Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals s.If Kirito starts duelling with the i-th (1 ≤ i ≤ n) dragon and Kirito's strength is not greater than the dragon's strength xi, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by yi.Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.

The first line contains two space-separated integers s and n (1 ≤ s ≤ 104, 1 ≤ n ≤ 103). Then n lines follow: the i-th line contains space-separated integers xi and yi (1 ≤ xi ≤ 104, 0 ≤ yi ≤ 104) — the i-th dragon's strength and the bonus for defeating it.

On a single line print "YES" (without the quotes), if Kirito can move on to the next level and print "NO" (without the quotes), if he can't.

NoteIn the first sample Kirito's strength initially equals 2. As the first dragon's strength is less than 2, Kirito can fight it and defeat it. After that he gets the bonus and his strength increases to 2 + 99 = 101. Now he can defeat the second dragon and move on to the next level.In the second sample Kirito's strength is too small to defeat the only dragon and win.

import std.stdio, std.string, std.algorithm , std.regex, std.conv, std.array;

void main()
{
    const auto readints = "stdin.readln.strip.split().map!(to!int).array";
    mixin("auto sn ="~readints~";");
    auto s=sn[0], n=sn[1];
    int[][] xys;
    foreach(i; 0..n) xys ~= [mixin(readints)];
    xys.sort!((a, b) => a[0] < b[0]);
    foreach (xy;xys){
        if (s<=xy[0]) { writeln("NO"); return;}
        s+=xy[1];
    }
    writeln("YES");
}

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

struct Dragon
{
	int health;
	int gain;
}

int main(string[] argv)
{
	int s, n;
	scanf("%d %d", &s, &n);
	Dragon[] dragons = new Dragon[n];
	foreach (int i; 0..n)
	{
		int x, y;
		scanf("%d %d", &x, &y);
		dragons[i].health = x;
		dragons[i].gain = y;
	}
	dragons.sort!("a.health < b.health");
	foreach (int i; 0..n)
	{
		if (s > dragons[i].health)
		{
			s += dragons[i].gain;
		} else {
			write("NO");
			return 0;
		}
	}
	write("YES");
	return 0;
}

import std.algorithm;
import std.c.stdio;
import std.stdio;
import std.conv;

int curc;
bool eof = false;

void sb()
{
    do
    {
        curc = getchar ();
    }
    while (0 <= curc && curc <= 32);
    if (curc == EOF)
    {
        eof = true;
    }
}

char rc ()
{
    sb ();
    return cast (char) curc;
}

int ni ()
{
    sb ();
    int res = 0;
    do
    {
        res = res * 10 + cast (int) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

char[] ns ()
{
    sb ();
    char[] res = [];
    do
    {
        res ~= to!char(curc);
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

void CFBETA142A()
{
    class Tuple
    {
        int x, y;
        this(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
        override string toString()
        {
            return to!string(this.x) ~ " " ~ to!string(this.y);
        }
    }

    auto s = ni();
    auto n = ni();
    bool ans = true;
    Tuple[] t = new Tuple[n];
    for (int i=0; i<n; ++i)
        t[i] = new Tuple(ni(), ni());
    sort!("a.x<b.x")(t);
    //write(t);
    int cursum = s;
    for (int i=0; i<n; ++i)
        if (t[i].x>=cursum) ans = false;
        else cursum+=t[i].y;
    printf(ans?"YES":"NO");
}

void main()
{
    CFBETA142A();
}

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

immutable int mod = 10^^9 + 7;

void main(){
    int s, n;
    readVars(s, n);
    auto x = new int[](n);
    auto y = new int[](n);

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

    sort(zip(x, y));

    //writeln(x);
    //writeln(y);

    foreach(i ; 0 .. n){
        if (s <= x[i]) {
            writeln("NO");
            return;
        }

        s += y[i];
    }

    writeln("YES");
}

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

// ab.d

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

void main()
{
    const auto readints = "stdin.readln.strip.split(regex(` +`)).map!(to!int).array";
    mixin("auto sn ="~readints~";");
    auto s=sn[0], n=sn[1];
    int[][] xys;
    foreach(i; 0..n) xys ~= [mixin(readints)];
    xys.sort!((a, b) => a[0] < b[0]);
    foreach (xy;xys){
        //writeln(xy);
        //s-=xy[0];
        if (s<0) {
            writeln("NO");
            return;
        }
        s+=xy[1];
    }
    writeln("YES");
}

// ab.d

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

void main()
{
    const auto readints = "stdin.readln.strip.split(regex(` +`)).map!(to!int).array";
    mixin("auto sn ="~readints~";");
    auto s=sn[0], n=sn[1];
    int[][] xys;
    foreach(i; 0..n) xys ~= [mixin(readints)];
    xys.sort!((a, b) => a[0] < b[0]);
    foreach (xy;xys){
        s-=xy[0];
        if (s<0) {
            writeln("NO");
            return;
        }
        s+=xy[1];
    }
    writeln("YES");
}

import std.stdio: writeln, stdin;
import std.string: strip;
import std.algorithm.iteration : map;
import std.regex;
import std.range;
import std.conv;

void main()
{
  auto sn = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto s=sn[0], n=sn[1];

  for(int i = 1; i <= n; i++) {
    auto xy = stdin.readln.strip.split(regex(` +`)).map!(to!int);
    s-=xy[0];
    if (s<0) {
      writeln("NO");
      return;
    }
    s+=xy[1];
  }
  writeln("YES");
}

// ab.d

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

void main()
{
    const auto readints = "stdin.readln.strip.split(regex(` +`)).map!(to!int).array";
    mixin("auto sn ="~readints~";");
    auto s=sn[0], n=sn[1];
    int[][] xys;
    foreach(i; 0..n) xys ~= [mixin(readints)];
    xys.sort!((a, b) => a[0] < b[0]);
    foreach (xy;xys){
        //writeln(xy);
        //s-=xy[0];
        if (s<xy[0]) {
            writeln("NO");
            return;
        }
        s+=xy[1];
    }
    writeln("YES");
}

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

struct Dragon
{
	int health;
	int gain;
}

int main(string[] argv)
{
	int s, n;
	scanf("%d %d", &s, &n);
	Dragon[] dragons = new Dragon[n];
	foreach (int i; 0..n)
	{
		int x, y;
		scanf("%d %d", &x, &y);
		dragons[i].health = x;
		dragons[i].gain = y;
	}
	dragons.sort!("a.health < b.health");
	foreach (int i; 0..n)
	{
		if (s >= dragons[i].health)
		{
			s += dragons[i].gain;
		} else {
			write("NO");
			return 0;
		}
	}
	write("YES");
	return 0;
}


You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick.

For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "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; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

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

void main()
{
	auto q = RD!int;
	auto ans = new bool[](q);
	foreach (i; 0..q)
	{
		auto n = RD!int;
		auto a = RDA;
		a.sort();
		auto size = a[0] * a[$-1];
		bool ok = true;
		while (!a.empty)
		{
			if (a[0] == a[1] && a[$-1] == a[$-2])
			{
				if (a[0] * a[$-1] == size)
				{
					a.popFront; a.popFront; a.popBack; a.popBack;
					continue;
				}
			}
			ok = false;
			break;
		}
		ans[i] = ok;
	}

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


There is a square grid of size $$$n \times n$$$. Some cells are colored in black, all others are colored in white. In one operation you can select some rectangle and color all its cells in white. It costs $$$\min(h, w)$$$ to color a rectangle of size $$$h \times w$$$. You are to make all cells white for minimum total cost.The square is large, so we give it to you in a compressed way. The set of black cells is the union of $$$m$$$ rectangles.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^{9}$$$, $$$0 \le m \le 50$$$) — the size of the square grid and the number of black rectangles. Each of the next $$$m$$$ lines contains 4 integers $$$x_{i1}$$$ $$$y_{i1}$$$ $$$x_{i2}$$$ $$$y_{i2}$$$ ($$$1 \le x_{i1} \le x_{i2} \le n$$$, $$$1 \le y_{i1} \le y_{i2} \le n$$$) — the coordinates of the bottom-left and the top-right corner cells of the $$$i$$$-th black rectangle. The rectangles may intersect.

Print a single integer — the minimum total cost of painting the whole square in white.

NoteThe examples and some of optimal solutions are shown on the pictures below.

/+ dub.sdl:
    name "E"
    dependency "dunkelheit" version="1.0.1"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dkh.foundation, dkh.scanner, dkh.graph.maxflow;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    int n, m;
    sc.read(n, m);

    int[] x1 = new int[m];
    int[] x2 = new int[m];
    int[] y1 = new int[m];
    int[] y2 = new int[m];
    foreach (i; 0..m) {
        sc.read(x1[i], y1[i], x2[i], y2[i]);
        x2[i]++; y2[i]++;
    }

    int[] xv = x1 ~ x2 ~ [0];
    int[] yv = y1 ~ y2 ~ [0];

    xv = xv.sort.uniq.array;
    yv = yv.sort.uniq.array;

    int getX(int x) {
        return xv.assumeSorted.lowerBound(x).length.to!int;
    }
    int getY(int y) {
        return yv.assumeSorted.lowerBound(y).length.to!int;
    }

    int w = xv.length.to!int - 1;
    int h = yv.length.to!int - 1;

    bool[][] mp = new bool[][](h, w);
    foreach (i; 0..m) {
        int l = getX(x1[i]), r = getX(x2[i]);
        int d = getY(y1[i]), u = getY(y2[i]);

        foreach (x; l..r) {
            foreach (y; d..u) {
                mp[y][x] = true;
            }
        }
    }

    struct Edge {
        int to, rev;
        long cap;
    }

    void addEdge(Edge[][] g, int from, int to, long cap) {
        g[from] ~= Edge(to, g[to].length.to!int, cap);
        g[to] ~= Edge(from, g[from].length.to!int-1, 0);
    }

    auto g = new Edge[][](1 + w + h + 1);
    int sv = w + h, tv = sv + 1;

    foreach (i; 0..w) {
        addEdge(g, sv, i, xv[i + 1] - xv[i]);
    }
    foreach (i; 0..h) {
        addEdge(g, w + i, tv, yv[i + 1] - yv[i]);
    }

    foreach (i; 0..w) {
        foreach (j; 0..h) {
            if (mp[j][i]) {
                addEdge(g, i, w + j, 10L^^18);
            }
        }
    }

    writeln(maxFlow!(long, 0)(g, sv, tv).flow);

    return 0;
}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/container/deque.d */
// module dkh.container.deque;

struct DequePayload(T) {
    import core.exception : RangeError;

    private T* _data;
    private uint start, len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        if (start + i < cap) return _data[start + i];
        else return _data[start + i - cap];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import std.algorithm : max;
        import std.conv : to;
        if (newCap <= cap) return;
        T* newData = cast(T*)GC.malloc(newCap * T.sizeof);
        foreach (i; 0..length) {
            newData[i] = this[i];
        }
        _data = newData; start = 0; cap = newCap.to!uint;
    }
    void clear() {
        start = len = 0;
    }
    import std.algorithm : max;
    void insertFront(T item) {
        if (len == cap) reserve(max(cap * 2, 4));
        if (start == 0) start += cap;
        start--; len++;
        this[0] = item;
    }
    void insertBack(T item) {
        if (len == cap) reserve(max(cap * 2, 4));
        len++;
        this[len-1] = item;
    }
    void removeFront() {
        assert(!empty, "Deque.removeFront: Deque is empty");
        start++; len--;
        if (start == cap) start = 0;
    }
    void removeBack() {
        assert(!empty, "Deque.removeBack: Deque is empty");
        len--;
    }
}

struct Deque(T, bool mayNull = true) {
    import core.exception : RangeError;
    import std.range : ElementType, isInputRange;
    import std.traits : isImplicitlyConvertible;

    alias Payload = DequePayload!T;
    Payload* _p;

    static if (!mayNull) @disable this();

    this(U)(U[] values...) if (isImplicitlyConvertible!(U, T)) {
        _p = new Payload();
        foreach (v; values) {
            insertBack(v);
        }
    }

    this(Range)(Range r)
    if (isInputRange!Range &&
    isImplicitlyConvertible!(ElementType!Range, T) &&
    !is(Range == T[])) {
        _p = new Payload();
        foreach (v; r) {
            insertBack(v);
        }
    }
    private this(Payload* p) { _p = p; }
    static Deque make() { return Deque(new Payload()); }

    private bool havePayload() const { return (!mayNull || _p); }
    @property bool empty() const { return (!havePayload || _p.empty); }
    @property size_t length() const { return (havePayload ? _p.length : 0); }
    alias opDollar = length;

    ref inout(T) opIndex(size_t i) inout {
        assert(!empty, "Deque.opIndex: Deque is empty");
        return (*_p)[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void clear() { if (_p) _p.clear(); }

    void insertFront(T item) {
        if (mayNull && !_p) _p = new Payload();
        _p.insertFront(item);
    }
    void insertBack(T item) {
        if (mayNull && !_p) _p = new Payload();
        _p.insertBack(item);
    }
    alias opOpAssign(string op : "~") = insertBack;
    alias stableInsertBack = insertBack;

    void removeFront() {
        assert(!mayNull || _p, "Deque.removeFront: Deque is empty");
        _p.removeFront();
    }
    void removeBack() {
        assert(!mayNull || _p, "Deque.removeBack: Deque is empty");
        _p.removeBack();
    }
    alias stableRemoveBack = removeBack;

    alias Range = RangeT!(DequePayload!T);
    alias ConstRange = RangeT!(const DequePayload!T);
    alias ImmutableRange = RangeT!(immutable DequePayload!T);

    size_t[2] opSlice(size_t dim : 0)(size_t start, size_t end) const {
        assert(start <= end && end <= length);
        return [start, end];
    }
    Range opIndex(size_t[2] rng) { return Range(_p, rng[0], rng[1]); }
    ConstRange opIndex(size_t[2] rng) const { return ConstRange(_p, rng[0], rng[1]); }
    ImmutableRange opIndex(size_t[2] rng) immutable { return ImmutableRange(_p, rng[0], rng[1]); }
    auto opIndex() inout { return this[0..$]; }

    static struct RangeT(QualifiedPayload) {
        alias A = QualifiedPayload;
        import std.traits : CopyTypeQualifiers;
        alias E = CopyTypeQualifiers!(A, T);
        A *p;
        size_t l, r;

        @property bool empty() const { return r <= l; }
        @property size_t length() const { return r - l; }
        alias opDollar = length;

        @property auto save() { return this; }

        ref inout(E) opIndex(size_t i) inout {
            version(assert) if (empty) throw new RangeError();
            return (*p)[l+i];
        }
        @property ref inout(E) front() inout { return this[0]; }
        @property ref inout(E) back() inout { return this[$-1]; }

        void popFront() {
            version(assert) if (empty) throw new RangeError();
            l++;
        }
        void popBack() {
            version(assert) if (empty) throw new RangeError();
            r--;
        }

        size_t[2] opSlice(size_t dim : 0)(size_t start, size_t end) const {
            assert(start <= end && end <= length);
            return [start, end];
        }
        auto opIndex(size_t[2] rng) { return RangeT(p, l+rng[0], l+rng[1]); }
        auto opIndex(size_t[2] rng) const { return RangeT!(const A)(p, l+rng[0], l+rng[1]); }
        auto opIndex(size_t[2] rng) immutable { return RangeT!(immutable A)(p, l+rng[0], l+rng[1]); }
        auto opIndex() inout { return this[0..$]; }
    }
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/graph/maxflow.d */
// module dkh.graph.maxflow;

// import dkh.container.deque;

struct MaxFlowInfo(C) {
    C flow;
    bool[] dual;
}

MaxFlowInfo!(C) maxFlow(C, C EPS, T)(T g, size_t s, size_t t, C gap = C.max) {
    assert(s != t);
    import std.conv : to;
    int[] level = new int[g.length];
    int[] iter = new int[g.length];

    void bfs() {
        level[] = -1; level[s] = 0;
        auto que = Deque!int();
        que.insertBack(s.to!int);
        while (!que.empty) {
            int v = que.front; que.removeFront;
            foreach (e; g[v]) {
                if (e.cap <= EPS) continue;
                if (level[e.to] < 0) {
                    level[e.to] = level[v] + 1;
                    que.insertBack(e.to);
                }
            }
        }
    }

    C dfs(int v, C f) {
        import std.algorithm : min;
        if (v == t) return f;
        C res = 0;
        auto edgeList = g[v][iter[v]..$];
        foreach (ref e; edgeList) {
            if (e.cap <= EPS) continue;
            if (level[v] >= level[e.to]) continue;
            C d = dfs(e.to, min(f, e.cap));
            e.cap -= d;
            g[e.to][e.rev].cap += d;
            res += d;
            f -= d;
            if (f == 0) break;
            iter[v]++;
        }
        return res;
    }

    C flow = 0;
    while (gap - flow > EPS) {
        bfs();
        if (level[t] < 0) break;
        iter[] = 0;
        while (true) {
            C f = dfs(s.to!int, gap - flow);
            if (!f) break;
            flow += f;
        }
    }

    import std.algorithm : map;
    import std.range : array;
    auto mfInfo = MaxFlowInfo!C();
    mfInfo.flow = flow;
    mfInfo.dual = level.map!"a == -1".array;
    return mfInfo;
}

MaxFlowInfo!(C) maxFlowSlow(C, T)(T g, int s, int t, C gap = C.max) {
    assert(s != t);
    import std.algorithm : map;
    import std.range : array;
    import std.conv : to;
    auto n = g.length;

    bool[] used = new bool[n];
    bool dfs(int v) {
        if (v == t) return true;
        used[v] = true;
        foreach (ref e; g[v]) {
            if (used[e.to]) continue;
            if (!e.cap) continue;
            if (dfs(e.to)) {
                e.cap -= 1;
                g[e.to][e.rev].cap += 1;
                return true;
            }
        }
        return false;
    }

    C flow = 0;
    while (flow < gap) {
        used[] = false;
        if (!dfs(s)) break;
        flow++;
    }
    auto mfInfo = MaxFlowInfo!C();
    mfInfo.flow = flow;
    mfInfo.dual = used.map!"!a".array;
    return mfInfo;
}

/* IMPORT /home/yosupo/Programs/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    private File f;

    this(File f) {
        this.f = f;
    }
    private char[512] lineBuf;
    private char[] line;
    private bool succW() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (!line.empty && line.front.isWhite) {
            line.popFront;
        }
        return !line.empty;
    }
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            line = lineBuf[];
            f.readln(line);
            if (!line.length) return false;
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    assert(succW());
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }

    void read(Args...)(auto ref Args args) {
        import std.exception : enforce;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }

    bool hasNext() {
        return succ();
    }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/

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

class MaxFlow(Capa) {
  enum Capa wEPS = 0;
  enum Capa wINF = 10L^^18;
  int n, m;
  int[][] g;
  int[] zu;
  Capa[] capa;
  Capa tof;
  int[] lev, see, que;
  this(int n) {
    this.n = n; m = 0; g = new int[][n]; zu = []; capa = [];
    lev = new int[n]; see = new int[n]; que = new int[n];
  }
  void addEdge(int u, int v, Capa w0, Capa w1 = 0) {
    g[u] ~= m; zu ~= v; capa ~= w0; ++m;
    g[v] ~= m; zu ~= u; capa ~= w1; ++m;
  }
  Capa augment(int src, int ink, Capa flo) {
    if (src == ink) return flo;
    foreach (i; g[src][see[src] .. $]) {
      if (capa[i] > wEPS && lev[src] < lev[zu[i]]) {
        Capa f = augment(zu[i], ink, min(flo, capa[i]));
        if (f > wEPS) { capa[i] -= f; capa[i ^ 1] += f; return f; }
      }
      ++see[src];
    }
    return 0;
  }
  bool dinic(int src, int ink, Capa flo = wINF) {
    for (tof = 0; tof + wEPS < flo; ) {
      int[] q;
      lev[] = -1;
     dinicBFS:
      for (lev[src] = 0, q ~= src; !q.empty; ) {
        int u = q.front; q.popFront;
        foreach (i; g[u]) {
          int v = zu[i];
          if (capa[i] > wEPS && lev[v] == -1) {
            lev[v] = lev[u] + 1; q ~= v;
            if (v == ink) break dinicBFS;
          }
        }
      }
      if (lev[ink] == -1) return false;
      see[] = 0;
      for (; ; ) {
        Capa f = augment(src, ink, flo - tof);
        if (f <= wEPS) break;
        tof += f;
      }
    }
    return true;
  }
}

long N;
int M;
long[] XA, YA, XB, YB;

void main() {
  try {
    for (; ; ) {
      N = readLong();
      M = readInt();
      XA = new long[M];
      YA = new long[M];
      XB = new long[M];
      YB = new long[M];
      foreach (i; 0 .. M) {
        XA[i] = readLong() - 1;
        YA[i] = readLong() - 1;
        XB[i] = readLong();
        YB[i] = readLong();
      }

      auto xs = [0L, N] ~ XA.dup ~ XB.dup;
      auto ys = [0L, N] ~ YA.dup ~ YB.dup;
      xs = xs.sort.uniq.array;
      ys = ys.sort.uniq.array;
      const H = cast(int)(xs.length) - 1;
      const W = cast(int)(xs.length) - 1;
      auto board = new bool[][](H, W);
      foreach (i; 0 .. M) {
        const ea = xs.lowerBound(XA[i]);
        const fa = ys.lowerBound(YA[i]);
        const eb = xs.lowerBound(XB[i]);
        const fb = ys.lowerBound(YB[i]);
        foreach (e; ea .. eb) foreach (f; fa .. fb) {
          board[e][f] = true;
        }
      }
      debug {
        writeln("xs = ", xs);
        writeln("ys = ", ys);
        foreach (e; 0 .. H) {
          foreach (f; 0 .. W) {
            write(board[e][f] ? '#' : '.');
          }
          writeln();
        }
      }

      auto mf = new MaxFlow!long(2 + H + W);
      foreach (e; 0 .. H) {
        mf.addEdge(0, 2 + e, xs[e + 1] - xs[e]);
      }
      foreach (f; 0 .. W) {
        mf.addEdge(2 + H + f, 1, ys[f + 1] - ys[f]);
      }
      foreach (e; 0 .. H) foreach (f; 0 .. W) {
        if (board[e][f]) {
          mf.addEdge(2 + e, 2 + H + f, MaxFlow!long.wINF);
        }
      }
      mf.dinic(0, 1);
      writeln(mf.tof);
    }
  } catch (EOFException e) {
  }
}


Filled with optimism, Hyunuk will host a conference about how great this new year will be!The conference will have $$$n$$$ lectures. Hyunuk has two candidate venues $$$a$$$ and $$$b$$$. For each of the $$$n$$$ lectures, the speaker specified two time intervals $$$[sa_i, ea_i]$$$ ($$$sa_i \le ea_i$$$) and $$$[sb_i, eb_i]$$$ ($$$sb_i \le eb_i$$$). If the conference is situated in venue $$$a$$$, the lecture will be held from $$$sa_i$$$ to $$$ea_i$$$, and if the conference is situated in venue $$$b$$$, the lecture will be held from $$$sb_i$$$ to $$$eb_i$$$. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval $$$[x, y]$$$ overlaps with a lecture held in interval $$$[u, v]$$$ if and only if $$$\max(x, u) \le \min(y, v)$$$.We say that a participant can attend a subset $$$s$$$ of the lectures if the lectures in $$$s$$$ do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue $$$a$$$ or venue $$$b$$$ to hold the conference.A subset of lectures $$$s$$$ is said to be venue-sensitive if, for one of the venues, the participant can attend $$$s$$$, but for the other venue, the participant cannot attend $$$s$$$.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in $$$s$$$ because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$), the number of lectures held in the conference. Each of the next $$$n$$$ lines contains four integers $$$sa_i$$$, $$$ea_i$$$, $$$sb_i$$$, $$$eb_i$$$ ($$$1 \le sa_i, ea_i, sb_i, eb_i \le 10^9$$$, $$$sa_i \le ea_i, sb_i \le eb_i$$$).

Print "YES" if Hyunuk will be happy. Print "NO" otherwise. You can print each letter in any case (upper or lower).

NoteIn second example, lecture set $$$\{1, 3\}$$$ is venue-sensitive. Because participant can't attend this lectures in venue $$$a$$$, but can attend in venue $$$b$$$.In first and third example, venue-sensitive set does not exist.

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		rndGen.seed (1235);
		auto h = new ulong [n];
		foreach (ref c; h)
		{
			c = uniform (1, ulong.max);
		}

		alias Segment = Tuple !(int, q{lo}, int, q{hi});
		auto a = new Segment [n];
		auto b = new Segment [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s %s %s")
			    (a[i].lo, a[i].hi, b[i].lo, b[i].hi);
		}
		long res = 0;

		alias Event = Tuple !(int, q{pos}, int, q{id});

		ulong [] calc (const ref Segment [] a)
		{
			Event [] events;
			foreach (i, const ref s; a)
			{
				events ~= Event (s.lo * 2 + 0, i.to !(int));
				events ~= Event (s.hi * 2 + 1, i.to !(int));
			}
			sort (events);

			auto mark = new ulong [n];
			auto rem = new ulong [n];
			ulong addCur = 0;
			ulong remCur = 0;
			foreach (const ref e; events)
			{
				bool isAdd = !(e.pos & 1);
				if (isAdd)
				{
					addCur ^= h[e.id];
					rem[e.id] = remCur;
				}
				else
				{
					mark[e.id] = addCur ^ rem[e.id];
					remCur ^= h[e.id];
				}
			}
			debug {writeln (mark);}
			return mark;
		}

		writeln (equal (calc (a), calc (b)) ? "YES" : "NO");
	}
}

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 bChmax(T)(T[] bit, int pos, T val)
in {
  assert(0 <= pos && pos < bit.length, "bChmax: 0 <= pos < |bit| must hold");
}
do {
  for (int x = pos; x < bit.length; x |= x + 1) {
    chmax(bit[x], val);
  }
}

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto SA = new long[N];
      auto TA = new long[N];
      auto SB = new long[N];
      auto TB = new long[N];
      foreach (i; 0 .. N) {
        SA[i] = readLong();
        TA[i] = readLong();
        SB[i] = readLong();
        TB[i] = readLong();
      }

      bool ans = true;
      foreach (phase; 0 .. 2) {
        auto xs = SA.dup ~ TA.dup ~ SB.dup ~ TB.dup;
        xs = xs.sort.uniq.array;
        const xsLen = cast(int)(xs.length);

        auto lecsSA = iota(N).array;
        auto lecsTA = iota(N).array;
        lecsSA.sort!((i, j) => (SA[i] < SA[j]));
        lecsTA.sort!((i, j) => (TA[i] < TA[j]));

        auto bit = new long[xsLen];
        bit[] = -1;
        int posI;
        foreach (j; lecsSA) {
          for (; posI < N && TA[lecsTA[posI]] < SA[j]; ++posI) {
            const i = lecsTA[posI];
            debug {
              writeln("add i = ", i);
            }
            const key = xs.lowerBound(SB[i]);
            bit.bChmax(key, TB[i]);
          }
          {
            debug {
              writeln("check j = ", j);
            }
            const key = xs.lowerBound(TB[j]);
            const res = bit.bMax(key + 1);
            if (res >= SB[j]) {
              debug {
                writefln("found j = %s, res = %s", j, res);
              }
              ans = false;
            }
          }
        }

        swap(SA, SB);
        swap(TA, TB);
      }
      writeln(ans ? "YES" : "NO");
    }
  } catch (EOFException e) {
  }
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		rndGen.seed (1235);
		auto h = new ulong [n];
		foreach (ref c; h)
		{
			c = uniform (1, ulong.max);
		}

		alias Segment = Tuple !(int, q{lo}, int, q{hi});
		auto a = new Segment [n];
		auto b = new Segment [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s %s %s")
			    (a[i].lo, a[i].hi, b[i].lo, b[i].hi);
		}
		long res = 0;

		alias Event = Tuple !(int, q{pos}, int, q{id});

		ulong [] calc (const ref Segment [] a)
		{
			Event [] events;
			foreach (i, const ref s; a)
			{
				events ~= Event (s.lo * 2 + 1, i.to !(int));
				events ~= Event (s.hi * 2 + 0, i.to !(int));
			}
			sort (events);

			auto mark = new ulong [n];
			auto rem = new ulong [n];
			ulong addCur = 0;
			ulong remCur = 0;
			foreach (const ref e; events)
			{
				bool isAdd = e.pos & 1;
				if (isAdd)
				{
					addCur ^= h[e.id];
					rem[e.id] = remCur;
				}
				else
				{
					mark[e.id] = addCur ^ rem[e.id];
					remCur ^= h[e.id];
				}
			}
			writeln (mark);
			return mark;
		}

		writeln (equal (calc (a), calc (b)) ? "YES" : "NO");
	}
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		rndGen.seed (1235);
		auto h = new ulong [n];
		foreach (ref c; h)
		{
			c = uniform (1, ulong.max);
		}

		alias Segment = Tuple !(int, q{lo}, int, q{hi});
		auto a = new Segment [n];
		auto b = new Segment [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s %s %s")
			    (a[i].lo, a[i].hi, b[i].lo, b[i].hi);
		}
		long res = 0;

		alias Event = Tuple !(int, q{pos}, int, q{id});

		ulong [] calc (const ref Segment [] a)
		{
			Event [] events;
			foreach (i, const ref s; a)
			{
				events ~= Event (s.lo * 2 + 1, i.to !(int));
				events ~= Event (s.hi * 2 + 0, i.to !(int));
			}
			sort (events);

			auto mark = new ulong [n];
			auto rem = new ulong [n];
			ulong addCur = 0;
			ulong remCur = 0;
			foreach (const ref e; events)
			{
				bool isAdd = e.pos & 1;
				if (isAdd)
				{
					addCur ^= h[e.id];
					rem[e.id] = remCur;
				}
				else
				{
					mark[e.id] = addCur ^ rem[e.id];
					remCur ^= h[e.id];
				}
			}
			debug {writeln (mark);}
			return mark;
		}

		writeln (equal (calc (a), calc (b)) ? "YES" : "NO");
	}
}

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 bChmax(T)(T[] bit, int pos, T val)
in {
  assert(0 <= pos && pos < bit.length, "bChmax: 0 <= pos < |bit| must hold");
}
do {
  for (int x = pos; x < bit.length; x |= x + 1) {
    chmax(bit[x], val);
  }
}

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto SA = new long[N];
      auto TA = new long[N];
      auto SB = new long[N];
      auto TB = new long[N];
      foreach (i; 0 .. N) {
        SA[i] = readLong();
        TA[i] = readLong();
        SB[i] = readLong();
        TB[i] = readLong();
      }

      bool ans = true;
      foreach (phase; 0 .. 2) {
        auto xs = SA.dup ~ TA.dup ~ SB.dup ~ TB.dup;
        xs = xs.sort.uniq.array;
        const xsLen = cast(int)(xs.length);

        auto lecsSA = iota(N).array;
        auto lecsTA = iota(N).array;
        lecsSA.sort!((i, j) => (SA[i] < SA[j]));
        lecsTA.sort!((i, j) => (TA[i] < TA[j]));

        auto bit = new long[xsLen];
        bit[] = -1;
        int posI;
        foreach (j; lecsSA) {
          for (; posI < N && TA[lecsTA[posI]] < SA[j]; ++posI) {
            const i = lecsSA[posI];
            debug {
              writeln("add i = ", i);
            }
            const key = xs.lowerBound(SB[i]);
            bit.bChmax(key, TB[i]);
          }
          {
            debug {
              writeln("check j = ", j);
            }
            const key = xs.lowerBound(TB[j]);
            const res = bit.bMax(key + 1);
            if (res >= SB[j]) {
              debug {
                writefln("found j = %s, res = %s", j, res);
              }
              ans = false;
            }
          }
        }

        swap(SA, SB);
        swap(TA, TB);
      }
      writeln(ans ? "YES" : "NO");
    }
  } catch (EOFException e) {
  }
}


Rumors say that one of Kamal-ol-molk's paintings has been altered. A rectangular brush has been moved right and down on the painting.Consider the painting as a n × m rectangular grid. At the beginning an x × y rectangular brush is placed somewhere in the frame, with edges parallel to the frame, (1 ≤ x ≤ n, 1 ≤ y ≤ m). Then the brush is moved several times. Each time the brush is moved one unit right or down. The brush has been strictly inside the frame during the painting. The brush alters every cell it has covered at some moment.You have found one of the old Kamal-ol-molk's paintings. You want to know if it's possible that it has been altered in described manner. If yes, you also want to know minimum possible area of the brush.

The first line of input contains two integers n and m, (1 ≤ n, m ≤ 1000), denoting the height and width of the painting. The next n lines contain the painting. Each line has m characters. Character 'X' denotes an altered cell, otherwise it's showed by '.'. There will be at least one altered cell in the painting.

Print the minimum area of the brush in a line, if the painting is possibly altered, otherwise print  - 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;

void main ()
{
	int n;
	int m;
	while (readf (" %s %s ", &n, &m) > 0)
	{
		auto s = new string [n];
		foreach (ref x; s)
		{
			x = readln ().strip ();
		}

		int s_row;
		int s_col;
outer_loop:
		foreach (row; 0..n)
		{
			foreach (col; 0..m)
			{
				if (s[row][col] == 'X')
				{
					s_row = row;
					s_col = col;
					break outer_loop;
				}
			}
		}

		bool go (int l_row, int l_col)
		{
			debug {writeln (l_row, ' ', l_col);}
			if (l_row <= 0 || l_col <= 0)
			{
				return false;
			}

			auto b = new char [] [] (n, m);
			foreach (ref c; b)
			{
				c[] = '.';
			}

			int c_row = s_row;
			int c_col = s_col;
			foreach (row; 0..l_row)
			{
				foreach (col; 0..l_col)
				{
					b[c_row + row][c_col + col] = 'X';
				}
			}

			while (true)
			{
				if (c_row + l_row < n &&
				    s[c_row + l_row][c_col] == 'X')
				{
					foreach (col; 0..l_col)
					{
						b[c_row + l_row]
						    [c_col + col] = 'X';
					}
					c_row++;
				}
				else if (c_col + l_col < m &&
				    s[c_row][c_col + l_col] == 'X')
				{
					foreach (row; 0..l_row)
					{
						b[c_row + row]
						    [c_col + l_col] = 'X';
					}
					c_col++;
				}
				else
				{
					break;
				}
			}

			return b[] == s[];
		}

		int t_row = s_row;
		while (t_row < n && s[t_row][s_col] == 'X')
		{
			t_row++;
		}
		int t_col = s_col;
		while (t_col < m && s[s_row][t_col] == 'X')
		{
			t_col++;
		}

		long res = m * n + 1;

		{
			int l_row = t_row - s_row;
			int l_col = t_col - s_col;
			int c_row = s_row;
			int c_col = s_col;
			while (c_col < m)
			{
				if (c_row + l_row < n &&
				    s[c_row + l_row][c_col] == 'X')
				{
					break;
				}
				l_col--;
				c_col++;
			}
			l_col = max (l_col, 1);
			if (go (l_row, l_col))
			{
				res = min (res, l_row * l_col);
			}
		}

		{
			int l_row = t_row - s_row;
			int l_col = t_col - s_col;
			int c_row = s_row;
			int c_col = s_col;
			while (c_row < n)
			{
				if (c_col + l_col < m &&
				    s[c_row][c_col + l_col] == 'X')
				{
					break;
				}
				l_row--;
				c_row++;
			}
			l_row = max (l_row, 1);
			if (go (l_row, l_col))
			{
				res = min (res, l_row * l_col);
			}
		}

		if (res == m * n + 1)
		{
			res = -1;
		}
		writeln (res);
	}
}

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;

void main ()
{
	int n;
	int m;
	while (readf (" %s %s ", &n, &m) > 0)
	{
		auto s = new string [n];
		foreach (ref x; s)
		{
			x = readln ().strip ();
		}

		int s_row;
		int s_col;
outer_loop:
		foreach (row; 0..n)
		{
			foreach (col; 0..m)
			{
				if (s[row][col] == 'X')
				{
					s_row = row;
					s_col = col;
					break outer_loop;
				}
			}
		}

		bool go (int l_row, int l_col)
		{
			debug {writeln (l_row, ' ', l_col);}
			if (l_row <= 0 || l_col <= 0)
			{
				return false;
			}

			auto b = new char [] [] (n, m);
			foreach (ref c; b)
			{
				c[] = '.';
			}

			int c_row = s_row;
			int c_col = s_col;
			foreach (row; 0..l_row)
			{
				foreach (col; 0..l_col)
				{
					b[c_row + row][c_col + col] = 'X';
				}
			}

			while (true)
			{
				if (c_row + l_row < n &&
				    s[c_row + l_row][c_col] == 'X')
				{
					foreach (col; 0..l_col)
					{
						b[c_row + l_row]
						    [c_col + col] = 'X';
					}
					c_row++;
				}
				else if (c_col + l_col < m &&
				    s[c_row][c_col + l_col] == 'X')
				{
					foreach (row; 0..l_row)
					{
						b[c_row + row]
						    [c_col + l_col] = 'X';
					}
					c_col++;
				}
				else
				{
					break;
				}
			}

			return b[] == s[];
		}

		int t_row = s_row;
		while (t_row < n && s[t_row][s_col] == 'X')
		{
			t_row++;
		}
		int t_col = s_col;
		while (t_col < m && s[s_row][t_col] == 'X')
		{
			t_col++;
		}

		long res = m * n + 1;

		{
			int l_row = t_row - s_row;
			int l_col = t_col - s_col;
			int c_row = s_row;
			int c_col = s_col;
			while (c_col + l_col < m)
			{
				if (c_row + l_row < n &&
				    s[c_row + l_row][c_col] == 'X')
				{
					l_row--;
					break;
				}
				l_row--;
			}
			if (go (l_row, l_col))
			{
				res = min (res, l_row * l_col);
			}
		}

		{
			int l_row = t_row - s_row;
			int l_col = t_col - s_col;
			int c_row = s_row;
			int c_col = s_col;
			while (c_row + l_row < n)
			{
				if (c_col + l_col < m &&
				    s[c_row][c_col + l_col] == 'X')
				{
					l_col--;
					break;
				}
				l_col--;
			}
			if (go (l_row, l_col))
			{
				res = min (res, l_row * l_col);
			}
		}

		if (res == m * n + 1)
		{
			res = -1;
		}
		writeln (res);
	}
}

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;

void main ()
{
	int n;
	int m;
	while (readf (" %s %s ", &n, &m) > 0)
	{
		auto s = new string [n];
		foreach (ref x; s)
		{
			x = readln ().strip ();
		}

		int s_row;
		int s_col;
outer_loop:
		foreach (row; 0..n)
		{
			foreach (col; 0..m)
			{
				if (s[row][col] == 'X')
				{
					s_row = row;
					s_col = col;
					break outer_loop;
				}
			}
		}

		bool go (int l_row, int l_col)
		{
			debug {writeln (l_row, ' ', l_col);}
			if (l_row <= 0 || l_col <= 0)
			{
				return false;
			}

			auto b = new char [] [] (n, m);
			foreach (ref c; b)
			{
				c[] = '.';
			}

			int c_row = s_row;
			int c_col = s_col;
			foreach (row; 0..l_row)
			{
				foreach (col; 0..l_col)
				{
					b[c_row + row][c_col + col] = 'X';
				}
			}

			while (true)
			{
				if (c_row + l_row < n &&
				    s[c_row + l_row][c_col] == 'X')
				{
					foreach (col; 0..l_col)
					{
						b[c_row + l_row]
						    [c_col + col] = 'X';
					}
					c_row++;
				}
				else if (c_col + l_col < m &&
				    s[c_row][c_col + l_col] == 'X')
				{
					foreach (row; 0..l_row)
					{
						b[c_row + row]
						    [c_col + l_col] = 'X';
					}
					c_col++;
				}
				else
				{
					break;
				}
			}

			return b[] == s[];
		}

		int t_row = s_row;
		while (t_row < n && s[t_row][s_col] == 'X')
		{
			t_row++;
		}
		int t_col = s_col;
		while (t_col < m && s[s_row][t_col] == 'X')
		{
			t_col++;
		}

		long res = m * n + 1;

		{
			int l_row = t_row - s_row;
			int l_col = t_col - s_col;
			int c_row = s_row;
			int c_col = s_col;
			while (c_col + l_col < m)
			{
				if (c_row + l_row < n &&
				    s[c_row + l_row][c_col] == 'X')
				{
					l_row--;
					break;
				}
				l_row--;
				c_col++;
			}
			if (go (l_row, l_col))
			{
				res = min (res, l_row * l_col);
			}
		}

		{
			int l_row = t_row - s_row;
			int l_col = t_col - s_col;
			int c_row = s_row;
			int c_col = s_col;
			while (c_row + l_row < n)
			{
				if (c_col + l_col < m &&
				    s[c_row][c_col + l_col] == 'X')
				{
					l_col--;
					break;
				}
				l_col--;
				c_row++;
			}
			if (go (l_row, l_col))
			{
				res = min (res, l_row * l_col);
			}
		}

		if (res == m * n + 1)
		{
			res = -1;
		}
		writeln (res);
	}
}