Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds:  $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$;  There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i < b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j < i$$$.

The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1500$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing two space-separated strings $$$s$$$ and $$$c$$$ ($$$2 \le |s| \le 5000, 1 \le |c| \le 5000$$$). The strings $$$s$$$ and $$$c$$$ consists of uppercase English letters. It is guaranteed that the sum of $$$|s|$$$ in the input is at most $$$5000$$$ and the sum of the $$$|c|$$$ in the input is at most $$$5000$$$.

For each test case, output a single line containing a single string, which is either   the new name which is obtained after swapping no more than one pair of characters that is strictly lexicographically smaller than $$$c$$$. In case there are many possible such strings, you can output any of them;  three dashes (the string "---" without quotes) if it is impossible.

3
AZAMON APPLE
AZAMON AAAAAAAAAAALIBABA
APPLE BANANA

NoteIn the first test case, it is possible to swap the second and the fourth letters of the string and the resulting string "AMAZON" is lexicographically smaller than "APPLE".It is impossible to improve the product's name in the second test case and satisfy all conditions.In the third test case, it is possible not to swap a pair of characters. The name "APPLE" is lexicographically smaller than "BANANA". Note that there are other valid answers, e.g., "APPEL".

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 (ti; 0..t)
	{
		auto s = RD!(char[]);
		auto c = RD!string;
		auto f = new bool[][](s.length+1, 26);
		foreach_reverse (i; 0..s.length)
		{
			f[i] = f[i+1].dup;
			auto p = s[i] - 'A';
			f[i][p] = true;
		}
		(){
		foreach (i; 0..s.length)
		{
			auto p = s[i] - 'A';
			foreach (j; 0..p)
			{
				if (f[i][j])
				{
					foreach_reverse (k; 0..s.length)
					{
						auto p2 = s[k] - 'A';
						if (p2 == j)
						{
							swap(s[i], s[k]);
							return;
						}
					}
				}
			}
		}}();
		bool ok = true;
		size_t last = size_t.max;
		auto len = min(s.length, c.length);
		foreach (i; 0..len)
		{
			if (s[i] < c[i])
			{
				ok = true;
				break;
			}
			else if (s[i] > c[i])
			{
				ok = false;
				break;
			}
			last = i;
		}
		if (ok && last == len-1)
		{
			ok = s.length < c.length;
		}
		if (ok)
			ans[ti] = s.idup;
		else
			ans[ti] = "---";
	}
	foreach (e; ans)
		writeln(e);

	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 (ti; 0..t)
	{
		auto s = RD!(char[]);
		auto c = RD!string;
		auto f = new bool[][](s.length+1, 26);
		foreach_reverse (i; 0..s.length)
		{
			f[i] = f[i+1].dup;
			auto p = s[i] - 'A';
			f[i][p] = true;
		}
		(){
		foreach (i; 0..s.length)
		{
			auto p = s[i] - 'A';
			if (p == 0) continue;
			foreach (j; 0..p)
			{
				if (f[i+1][j])
				{
					foreach_reverse (k; 0..s.length)
					{
						auto p2 = s[k] - 'A';
						if (p2 == j)
						{
							swap(s[i], s[k]);
							return;
						}
					}
				}
			}
		}}();
		bool ok = true;
		size_t last;
		auto len = min(s.length, c.length);
		foreach (i; 0..len)
		{
			if (s[i] < c[i])
				break;
			else if (s[i] > c[i])
			{
				ok = false;
				break;
			}
			last = i;
		}
		if (ok && last == len-1)
		{
			ok = s.length < c.length;
		}
		if (ok)
			ans[ti] = s.idup;
		else
			ans[ti] = "---";
	}
	foreach (e; ans)
		writeln(e);

	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 (ti; 0..t)
	{
		auto s = RD!(char[]);
		auto c = RD!string;
		auto f = new bool[][](s.length+1, 26);
		foreach_reverse (i; 0..s.length)
		{
			f[i] = f[i+1].dup;
			auto p = s[i] - 'A';
			f[i][p] = true;
		}
		(){
		foreach (i; 0..s.length)
		{
			auto p = s[i] - 'A';
			foreach (j; 0..p)
			{
				if (f[i+1][j])
				{
					foreach_reverse (k; 0..s.length)
					{
						auto p2 = s[k] - 'A';
						if (p2 == j)
						{
							swap(s[i], s[k]);
							return;
						}
					}
				}
			}
		}}();
		bool ok;
		size_t last;
		auto len = min(s.length, c.length);
		foreach (i; 0..len)
		{
			if (s[i] < c[i])
			{
				ok = true;
				break;
			}
			else if (s[i] > c[i])
			{
				ok = false;
				break;
			}
			last = i;
		}
		/*if (ok && last == len-1)
		{
			ok = s.length < c.length;
		}*/
		if (ok)
			ans[ti] = s.idup;
		else
			ans[ti] = "---";
	}
	foreach (e; ans)
		writeln(e);

	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 (ti; 0..t)
	{
		auto s = RD!(char[]);
		auto c = RD!string;
		auto f = new bool[][](s.length+1, 26);
		foreach_reverse (i; 0..s.length)
		{
			f[i] = f[i+1].dup;
			auto p = s[i] - 'A';
			f[i][p] = true;
		}
		(){
		foreach (i; 0..s.length)
		{
			auto p = s[i] - 'A';
			foreach (j; 0..p)
			{
				if (f[i][j])
				{
					foreach_reverse (k; 0..s.length)
					{
						auto p2 = s[k] - 'A';
						if (p2 == j)
						{
							swap(s[i], s[k]);
							return;
						}
					}
				}
			}
		}}();
		bool ok = true;
		size_t last;
		auto len = min(s.length, c.length);
		foreach (i; 0..len)
		{
			if (s[i] < c[i])
			{
				ok = true;
				break;
			}
			else if (s[i] > c[i])
			{
				ok = false;
				break;
			}
			last = i;
		}
		if (ok && last == len-1)
		{
			ok = s.length <= c.length;
		}
		if (ok)
			ans[ti] = s.idup;
		else
			ans[ti] = "---";
	}
	foreach (e; ans)
		writeln(e);

	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 (ti; 0..t)
	{
		auto s = RD!(char[]);
		auto c = RD!string;
		auto f = new bool[][](s.length+1, 26);
		foreach_reverse (i; 0..s.length)
		{
			f[i] = f[i+1].dup;
			auto p = s[i] - 'A';
			f[i][p] = true;
		}
		(){
		foreach (i; 0..s.length)
		{
			auto p = s[i] - 'A';
			foreach (j; 0..p)
			{
				if (f[i][j])
				{
					foreach_reverse (k; 0..s.length)
					{
						auto p2 = s[k] - 'A';
						if (p2 == j)
						{
							swap(s[i], s[k]);
							return;
						}
					}
				}
			}
		}}();
		bool ok = true;
		size_t last;
		auto len = min(s.length, c.length);
		foreach (i; 0..len)
		{
			if (s[i] < c[i])
			{
				ok = true;
				break;
			}
			else if (s[i] > c[i])
			{
				ok = false;
				break;
			}
			last = i;
		}
		if (ok && last == len-1)
		{
			ok = s.length < c.length;
		}
		if (ok)
			ans[ti] = s.idup;
		else
			ans[ti] = "---";
	}
	foreach (e; ans)
		writeln(e);

	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 (ti; 0..t)
	{
		auto s = RD!(char[]);
		auto c = RD!string;
		auto f = new bool[][](s.length+1, 26);
		foreach_reverse (i; 0..s.length)
		{
			f[i] = f[i+1].dup;
			auto p = s[i] - 'A';
			f[i][p] = true;
		}
		(){
		foreach (i; 0..s.length)
		{
			auto p = s[i] - 'A';
			if (p == 0) continue;
			foreach (j; 0..p)
			{
				if (f[i+1][j])
				{
					foreach_reverse (k; 0..s.length)
					{
						auto p2 = s[k] - 'A';
						if (p2 == j)
						{
							swap(s[i], s[k]);
							return;
						}
					}
				}
			}
		}}();
		bool ok = true;
		size_t last;
		auto len = min(s.length, c.length);
		foreach (i; 0..len)
		{
			if (s[i] < c[i])
				break;
			else if (s[i] > c[i])
			{
				ok = false;
				break;
			}
			last = i;
		}
		if (ok && last == len-1)
		{
			//ok = s.length < c.length;
			ok = false;
		}
		if (ok)
			ans[ti] = s.idup;
		else
			ans[ti] = "---";
	}
	foreach (e; ans)
		writeln(e);

	stdout.flush;
	debug readln;
}


Polar bears like unique arrays — that is, arrays without repeated elements. You have got a unique array s with length n containing non-negative integers. Since you are good friends with Alice and Bob, you decide to split the array in two. Precisely, you need to construct two arrays a and b that are also of length n, with the following conditions for all i (1 ≤ i ≤ n):  ai, bi are non-negative integers;  si = ai + bi . Ideally, a and b should also be unique arrays. However, life in the Arctic is hard and this is not always possible. Fortunately, Alice and Bob are still happy if their arrays are almost unique. We define an array of length n to be almost unique, if and only if it can be turned into a unique array by removing no more than  entries.For example, the array [1, 2, 1, 3, 2] is almost unique because after removing the first two entries, it becomes [1, 3, 2]. The array [1, 2, 1, 3, 1, 2] is not almost unique because we need to remove at least 3 entries to turn it into a unique array.So, your task is to split the given unique array s into two almost unique arrays a and b.

The first line of the input contains integer n (1 ≤ n ≤ 105). The second line contains n distinct integers s1, s2, ... sn (0 ≤ si ≤ 109).

If it is possible to make Alice and Bob happy (if you can split the given array), print "YES" (without quotes) in the first line. In the second line, print the array a. In the third line, print the array b. There may be more than one solution. Any of them will be accepted. If it is impossible to split s into almost unique arrays a and b, print "NO" (without quotes) in the first line.

NoteIn the sample, we can remove the first two entries from a and the second entry from b to make them both unique.

import std.algorithm;
import std.container;
import std.exception;
import std.math;
import std.stdio;
import std.string;
import std.typecons;

alias Tuple !(int, "v", int, "p") pair;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new pair [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i].v);
			a[i].p = i;
		}
		sort (a);
		int m = (n + 2) / 3;
		auto b = new int [n];
		auto c = new int [n];
		foreach (i; 0..m)
		{
			b[a[i].p] = a[i].v;
			c[a[i].p] = 0;
		}
		foreach (i; m..n - m)
		{
			b[a[i].p] = 0;
			c[a[i].p] = a[i].v;
		}
		foreach (i; n - m..n)
		{
			c[a[i].p] = n - 1 - i;
			b[a[i].p] = a[i].v - c[a[i].p];
		}
		writeln ("YES");
		writefln ("%(%s %)", b);
		writefln ("%(%s %)", c);
	}
}

import std.algorithm;
import std.container;
import std.exception;
import std.math;
import std.stdio;
import std.string;
import std.typecons;

alias Tuple !(int, "v", int, "p") pair;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new pair [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i].v);
			a[i].p = i;
		}
		sort (a);
		auto q = new int [n];
		foreach (i; 0..n)
		{
			q[a[i].p] = i;
		}
		int m = (n + 2) / 3;
		auto b = new int [n];
		auto c = new int [n];
		foreach (i; 0..m)
		{
			b[q[i]] = a[i].v;
			c[q[i]] = 0;
		}
		foreach (i; m..n - m)
		{
			b[q[i]] = 0;
			c[q[i]] = a[i].v;
		}
		foreach (i; n - m..n)
		{
			c[q[i]] = n - 1 - i;
			b[q[i]] = a[i].v - c[q[i]];
		}
		writeln ("YES");
		writefln ("%(%s %)", b);
		writefln ("%(%s %)", c);
	}
}


For an array $$$[b_1, b_2, \ldots, b_m]$$$ define its number of inversions as the number of pairs $$$(i, j)$$$ of integers such that $$$1 \le i < j \le m$$$ and $$$b_i>b_j$$$. Let's call array $$$b$$$ odd if its number of inversions is odd. For example, array $$$[4, 2, 7]$$$ is odd, as its number of inversions is $$$1$$$, while array $$$[2, 1, 4, 3]$$$ isn't, as its number of inversions is $$$2$$$.You are given a permutation $$$[p_1, p_2, \ldots, p_n]$$$ of integers from $$$1$$$ to $$$n$$$ (each of them appears exactly once in the permutation). You want to split it into several consecutive subarrays (maybe just one), so that the number of the odd subarrays among them is as large as possible. What largest number of these subarrays may be odd?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$)  — the size of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$, all $$$p_i$$$ are distinct)  — the elements of the permutation. The sum of $$$n$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.

For each test case output a single integer  — the largest possible number of odd subarrays that you can get after splitting the permutation into several consecutive subarrays.

NoteIn the first and third test cases, no matter how we split our permutation, there won't be any odd subarrays.In the second test case, we can split our permutation into subarrays $$$[4, 3], [2, 1]$$$, both of which are odd since their numbers of inversions are $$$1$$$.In the fourth test case, we can split our permutation into a single subarray $$$[2, 1]$$$, which is odd.In the fifth test case, we can split our permutation into subarrays $$$[4, 5], [6, 1, 2, 3]$$$. The first subarray has $$$0$$$ inversions, and the second has $$$3$$$, so it is odd.

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

void main() {
	int t, count;
	readf("%d\n", t);
	while(t) {
		int n;
		bool b = true;
		count = 0;
		readf("%d\n", n);
		int[] numbs = to!(int[])(strip(readln).split(" "));
		for (int i = 0; i < n-1; i++) {
				if( b && numbs[i] > numbs[i+1]) {
					count++;
					b = false;
					continue;
				}
				b = true;
			}
			writeln(count);
			t--;
		}
	}


Pay attention: this problem is interactive.Penguin Xoriy came up with a new game recently. He has n icicles numbered from 1 to n. Each icicle has a temperature — an integer from 1 to 109. Exactly two of these icicles are special: their temperature is y, while a temperature of all the others is x ≠ y. You have to find those special icicles. You can choose a non-empty subset of icicles and ask the penguin what is the bitwise exclusive OR (XOR) of the temperatures of the icicles in this subset. Note that you can't ask more than 19 questions.You are to find the special icicles.

The first line contains three integers n, x, y (2 ≤ n ≤ 1000, 1 ≤ x, y ≤ 109, x ≠ y) — the number of icicles, the temperature of non-special icicles and the temperature of the special icicles.

To give your answer to the penguin you have to print character "!" (without quotes), then print two integers p1, p2 (p1 < p2) — the indexes of the special icicles in ascending order. Note that "!" and p1 should be separated by a space; the indexes should be separated by a space too. After you gave the answer your program should terminate immediately.

NoteThe answer for the first question is .The answer for the second and the third questions is 1, therefore, special icicles are indexes 1 and 3.You can read more about bitwise XOR operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.

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;

int ask(int[] q) {
    writeln("? " ~ q.length.to!string ~ " " ~ q.map!(a => a.to!string).join(" "));
    stdout.flush;
    return readln.chomp.to!int;
}

void answer(int x, int y) {
    writeln("! ", x, " ", y);
    stdout.flush;
}

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto X = s[1];
    auto Y = s[2];

    int xor = 0;
    foreach (mask; 0..10) {
        int[] q;
        foreach (i; 1..N+1) if (i & (1 << mask)) q ~= i;
        if (q.length == 0) continue;
        int ret = ask(q);
        ret = ret == X || ret == 0 ? 0 : 1;
        xor |= (ret << mask);
    }

    int b;
    foreach (mask; 0..10) if (xor & (1 << mask)) b = mask;

    int ans = 1 << b;
    foreach (mask; 0..10) {
        if (mask == b) continue;
        int[] q;
        foreach (i; 1..N+1) if ((i & (1 << mask)) && (i & (1 << b))) q ~= i;
        if (q.length == 0) continue;
        int ret = ask(q);
        ret = ret == X || ret == 0 ? 0 : 1;
        ans |= (ret << mask);
    }

    int ans2 = xor ^ ans;
    answer(min(ans, ans2), max(ans, ans2));
}


— Hey folks, how do you like this problem?— That'll do it. BThero is a powerful magician. He has got $$$n$$$ piles of candies, the $$$i$$$-th pile initially contains $$$a_i$$$ candies. BThero can cast a copy-paste spell as follows:   He chooses two piles $$$(i, j)$$$ such that $$$1 \le i, j \le n$$$ and $$$i \ne j$$$.  All candies from pile $$$i$$$ are copied into pile $$$j$$$. Formally, the operation $$$a_j := a_j + a_i$$$ is performed. BThero can cast this spell any number of times he wants to — but unfortunately, if some pile contains strictly more than $$$k$$$ candies, he loses his magic power. What is the maximum number of times BThero can cast the spell without losing his power?

The first line contains one integer $$$T$$$ ($$$1 \le T \le 500$$$) — the number of test cases. Each test case consists of two lines:    the first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 1000$$$, $$$2 \le k \le 10^4$$$);  the second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le k$$$).  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$, and the sum of $$$k$$$ over all test cases does not exceed $$$10^4$$$.

For each test case, print one integer — the maximum number of times BThero can cast the spell without losing his magic power.

NoteIn the first test case we get either $$$a = [1, 2]$$$ or $$$a = [2, 1]$$$ after casting the spell for the first time, and it is impossible to cast it again.

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

string FMT_F = "%.10f";

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

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

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

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

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

		int x = int.max;
		int pos;
		foreach (i; 0..n)
		{
			if (a[i] < x)
			{
				x = a[i];
				pos = i;
			}
		}
		foreach (i; 0..n)
		{
			if (i == pos) continue;
			auto rem = k - a[i];
			ans[ti] += rem / x;
		}
	}

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


The development of a text editor is a hard problem. You need to implement an extra module for brackets coloring in text.Your editor consists of a line with infinite length and cursor, which points to the current character. Please note that it points to only one of the characters (and not between a pair of characters). Thus, it points to an index character. The user can move the cursor left or right one position. If the cursor is already at the first (leftmost) position, then it does not move left.Initially, the cursor is in the first (leftmost) character.Also, the user can write a letter or brackets (either (, or )) to the position that the cursor is currently pointing at. A new character always overwrites the old value at that position.Your editor must check, whether the current line is the correct text. Text is correct if the brackets in them form the correct bracket sequence.Formally, correct text (CT) must satisfy the following rules:   any line without brackets is CT (the line can contain whitespaces);  If the first character of the string — is (, the last — is ), and all the rest form a CT, then the whole line is a CT;  two consecutively written CT is also CT. Examples of correct texts: hello(codeforces), round, ((i)(write))edi(tor)s, ( me). Examples of incorrect texts: hello)oops(, round), ((me).The user uses special commands to work with your editor. Each command has its symbol, which must be written to execute this command.The correspondence of commands and characters is as follows:   L — move the cursor one character to the left (remains in place if it already points to the first character);  R — move the cursor one character to the right;  any lowercase Latin letter or bracket (( or )) — write the entered character to the position where the cursor is now. For a complete understanding, take a look at the first example and its illustrations in the note below.You are given a string containing the characters that the user entered. For the brackets coloring module's work, after each command you need to:  check if the current text in the editor is a correct text;  if it is, print the least number of colors that required, to color all brackets. If two pairs of brackets are nested (the first in the second or vice versa), then these pairs of brackets should be painted in different colors. If two pairs of brackets are not nested, then they can be painted in different or the same colors. For example, for the bracket sequence ()(())()() the least number of colors is $$$2$$$, and for the bracket sequence (()(()())())(()) — is $$$3$$$.Write a program that prints the minimal number of colors after processing each command.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the number of commands.  The second line contains $$$s$$$ — a sequence of commands. The string $$$s$$$ consists of $$$n$$$ characters. It is guaranteed that all characters in a string are valid commands.

In a single line print $$$n$$$ integers, where the $$$i$$$-th number is:   $$$-1$$$ if the line received after processing the first $$$i$$$ commands is not valid text,  the minimal number of colors in the case of the correct text.

NoteIn the first example, the text in the editor will take the following form:  (^  ( ^  (a ^  (a  ^  (ab  ^  (ab   ^  (ab)   ^  (ab)  ^  (a))  ^  (a)) ^  (()) ^

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

immutable int logHalf = 20;
immutable int half = 1 << logHalf;
immutable int limit = half << 1;

struct Tree
{
	int [] d;
	int [] tMin;
	int [] tMax;

	this (int _)
	{
		d = new int [limit];
		tMin = new int [limit];
		tMax = new int [limit];
	}

	void relax (int tv)
	{
		if (d[tv] == 0)
		{
			return;
		}
		if (tv < half)
		{
			d[tv * 2 + 0] += d[tv];
			d[tv * 2 + 1] += d[tv];
			tMin[tv * 2 + 0] += d[tv];
			tMin[tv * 2 + 1] += d[tv];
			tMax[tv * 2 + 0] += d[tv];
			tMax[tv * 2 + 1] += d[tv];
		}
		d[tv] = 0;
	}

	void recalc (int tv)
	{
		if (tv < half)
		{
			tMin[tv] = min (tMin[tv * 2 + 0], tMin[tv * 2 + 1]);
			tMax[tv] = max (tMax[tv * 2 + 0], tMax[tv * 2 + 1]);
		}
	}

	void add (int lo, int tv, int tlo, int thi, int value)
	{
		if (thi <= lo)
		{
			return;
		}
		if (lo <= tlo)
		{
			d[tv] += value;
			tMin[tv] += value;
			tMax[tv] += value;
			return;
		}
		relax (tv);
		auto tme = (tlo + thi) >> 1;
		add (lo, tv * 2 + 0, tlo, tme, value);
		add (lo, tv * 2 + 1, tme, thi, value);
		recalc (tv);
	}

	auto ask (int lo, int tv, int tlo, int thi)
	{
		if (thi <= lo)
		{
			return tuple (0, 0);
		}
		if (lo <= tlo)
		{
			return tuple (tMin[tv], tMax[tv]);
		}
		relax (tv);
		auto tme = (tlo + thi) >> 1;
		auto x = ask (lo, tv * 2 + 0, tlo, tme);
		auto y = ask (lo, tv * 2 + 1, tme, thi);
		recalc (tv);
		return tuple (min (x[0], y[0]), max (x[1], y[1]));
	}
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto commands = readln.strip;
		int pos = 0;
		int total = 0;
		auto s = new char [half];
		auto t = Tree (-1);

		void go (int pos, int delta)
		{
			total += delta;
			t.add (pos, 1, 0, half, delta);
		}

		auto ans = new int [n];
		ans[] = -1;
		foreach (i, const ref char c; commands)
		{
			if (c == 'L')
			{
				pos = max (0, pos - 1);
			}
			else if (c == 'R')
			{
				pos += 1;
			}
			else if (s[pos] != c)
			{
				int delta = 0;
				delta -= (s[pos] == '(');
				delta += (s[pos] == ')');
				delta += (c == '(');
				delta -= (c == ')');
				go (pos, delta);
				s[pos] = c;
			}

			if (total == 0)
			{
				auto cur = t.ask (0, 1, 0, half);
				if (cur[0] >= 0)
				{
					ans[i] = cur[1];
				}
			}
		}
		writefln ("%(%s %)", ans);
	}
}

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

immutable int logHalf = 20;
immutable int half = 1 << logHalf;
immutable int limit = half << 1;

struct Tree
{
	int [] d;
	int [] tMin;
	int [] tMax;

	this (int _)
	{
		d = new int [limit];
		tMin = new int [limit];
		tMax = new int [limit];
	}

	void relax (int tv)
	{
		if (d[tv] == 0)
		{
			return;
		}
		if (tv < half)
		{
			d[tv * 2 + 0] += d[tv];
			d[tv * 2 + 1] += d[tv];
			tMin[tv * 2 + 0] += d[tv];
			tMin[tv * 2 + 1] += d[tv];
			tMax[tv * 2 + 0] += d[tv];
			tMax[tv * 2 + 1] += d[tv];
		}
		d[tv] = 0;
	}

	void recalc (int tv)
	{
		if (tv < half)
		{
			tMin[tv] = min (tMin[tv * 2 + 0], tMin[tv * 2 + 1]);
			tMax[tv] = max (tMax[tv * 2 + 0], tMax[tv * 2 + 1]);
		}
	}

	void add (int lo, int tv, int tlo, int thi, int value)
	{
		if (thi <= lo)
		{
			return;
		}
		if (lo <= tlo)
		{
			d[tv] += value;
			tMin[tv] += value;
			tMax[tv] += value;
			return;
		}
		relax (tv);
		auto tme = (tlo + thi) >> 1;
		add (lo, tv * 2 + 0, tlo, tme, value);
		add (lo, tv * 2 + 1, tme, thi, value);
		recalc (tv);
	}
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto commands = readln.strip;
		int pos = 0;
		int total = 0;
		auto s = new char [half];
		auto t = Tree (-1);

		void go (int pos, int delta)
		{
			total += delta;
			t.add (pos, 1, 0, half, delta);
		}

		auto ans = new int [n];
		ans[] = -1;
		foreach (i, const ref char c; commands)
		{
			if (c == 'L')
			{
				pos = max (0, pos - 1);
			}
			else if (c == 'R')
			{
				pos += 1;
			}
			else if (s[pos] != c)
			{
				int delta = 0;
				delta -= (s[pos] == '(');
				delta += (s[pos] == ')');
				delta += (c == '(');
				delta -= (c == ')');
				if (delta != 0)
				{
					go (pos, delta);
				}
				s[pos] = c;
			}

			if (total == 0)
			{
				if (t.tMin[1] >= 0)
				{
					ans[i] = t.tMax[1];
				}
			}
		}
		writefln ("%(%s %)", ans);
	}
}


You are given a string $$$s$$$, consisting only of characters '0' and '1'.You have to choose a contiguous substring of $$$s$$$ and remove all occurrences of the character, which is a strict minority in it, from the substring.That is, if the amount of '0's in the substring is strictly smaller than the amount of '1's, remove all occurrences of '0' from the substring. If the amount of '1's is strictly smaller than the amount of '0's, remove all occurrences of '1'. If the amounts are the same, do nothing.You have to apply the operation exactly once. What is the maximum amount of characters that can be removed?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The only line of each testcase contains a non-empty string $$$s$$$, consisting only of characters '0' and '1'. The length of $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the maximum amount of characters that can be removed after applying the operation exactly once.

NoteIn the first testcase, you can choose substrings "0", "1" or "01". In "0" the amount of '0' is $$$1$$$, the amount of '1' is $$$0$$$. '1' is a strict minority, thus all occurrences of it are removed from the substring. However, since there were $$$0$$$ of them, nothing changes. Same for "1". And in "01" neither of '0' or '1' is a strict minority. Thus, nothing changes. So there is no way to remove any characters.In the second testcase, you can choose substring "10101010101". It contains $$$5$$$ characters '0' and $$$6$$$ characters '1'. '0' is a strict minority. Thus, you can remove all its occurrences. There exist other substrings that produce the same answer.In the third testcase, you can choose substring "011000100". It contains $$$6$$$ characters '0' and $$$3$$$ characters '1'. '1' is a strict minority. Thus, you can remove all its occurrences.

import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        auto s = readln.strip;
        auto z = count(s, '0');
        auto o = s.length - z;
        if (z == 0 || o == 0)
            writeln(0);
        else if (o == z)
            if (s.length > 2)
                writeln(o - 1);
            else
                writeln(0);
        else
            writeln(min(o, z));
    }
}

// cheese-cracker [2022-01-31]

void solve(){
    auto s = scan!(dchar[]);
    long on = 0;
    long off = 0;
    long res = 0;
    foreach(c; s){
        on += (c == '1');
        off += (c == '0');
        if(max(on, off) > min(on, off) && max(on, off) > 1){
            res = max(res, min(on, off));
        }
    }
    writeln(res);
}

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

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


You are given an array $$$a$$$ of size $$$n$$$. Each element in this array is an integer between $$$1$$$ and $$$10^9$$$.You can perform several operations to this array. During an operation, you can replace an element in the array with any integer between $$$1$$$ and $$$10^9$$$. Output the minimum number of operations needed such that the resulting array doesn't contain any local maximums, and the resulting array after the operations.An element $$$a_i$$$ is a local maximum if it is strictly larger than both of its neighbors (that is, $$$a_i > a_{i - 1}$$$ and $$$a_i > a_{i + 1}$$$). Since $$$a_1$$$ and $$$a_n$$$ have only one neighbor each, they will never be a local maximum.

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

For each test case, first output a line containing a single integer $$$m$$$ — minimum number of operations required. Then ouput a line consist of $$$n$$$ integers — the resulting array after the operations. Note that this array should differ in exactly $$$m$$$ elements from the initial array. If there are multiple answers, print any.

NoteIn the first example, the array contains no local maximum, so we don't need to perform operations.In the second example, we can change $$$a_2$$$ to $$$3$$$, then the array don't have local maximums.

import std.stdio, std.string, std.conv;
import std.algorithm.iteration;
import std.algorithm.searching;
import std.algorithm.mutation;
import std.range;
import std.typecons;
import std.algorithm;
void solution(ref File input, ref File output)
{
    auto t = input.readln.chomp.to!int;
    while (t-- > 0) {
        auto _ = input.readln;
        auto source = input.readln.chomp.split(' ').map!(to!int).array;
        int answer;
        for (int i = 1; i < source.length - 1; i++)
        {
            if (source[i] > source[i - 1] && source[i] > source[i + 1])
            {
                answer += 1;
                if (i + 2 < source.length - 1)
                {
                    source[i + 1] = max(source[i], source[i + 2]);
                } else
                {
                    source[i + 1] = source[i];
                }
            }
        }
        output.writeln(answer);
        output.writeln(source.map!(to!string).join(' '));

    }
}
void main()
{
    File input, output;
    debug(1) {
        input = File("input.txt", "r");
        output = File("output.txt", "w");
    } else {
        input = stdin;
        output = stdout;
    }
    solution(input, output);
}


There are $$$n$$$ emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The $$$i$$$-th emote increases the opponent's happiness by $$$a_i$$$ units (we all know that emotes in this game are used to make opponents happy).You have time to use some emotes only $$$m$$$ times. You are allowed to use any emotion once, more than once, or not use it at all. The only restriction is that you cannot use the same emote more than $$$k$$$ times in a row (otherwise the opponent will think that you're trolling him).Note that two emotes $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that $$$a_i = a_j$$$ are considered different.You have to make your opponent as happy as possible. Find the maximum possible opponent's happiness.

The first line of the input contains three integers $$$n, m$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le k \le m \le 2 \cdot 10^9$$$) — the number of emotes, the number of times you can use emotes and the maximum number of times you may use the same emote in a row. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is value of the happiness of the $$$i$$$-th emote.

Print one integer — the maximum opponent's happiness if you use emotes in a way satisfying the problem statement.

NoteIn the first example you may use emotes in the following sequence: $$$4, 4, 5, 4, 4, 5, 4, 4, 5$$$.

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

immutable int INF = 10L ^^ 9 + 23;

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

    auto a = readln.chomp.split.map!(to!int).array;

    a.sort();

    int dv = m / (k+1);
    long cycle = a[$-1].to!long * k + a[$-2];
    long cycleTot = cycle * dv;

    debug { dv.writeln; cycle.writeln; }

    int left = m % (k+1);
    long leftVal = a[$-1].to!long * left;

    long ans = cycleTot + leftVal;
    ans.writeln;
}


You are given an array $$$a$$$ of length $$$n$$$.Let's define the eversion operation. Let $$$x = a_n$$$. Then array $$$a$$$ is partitioned into two parts: left and right. The left part contains the elements of $$$a$$$ that are not greater than $$$x$$$ ($$$\le x$$$). The right part contains the elements of $$$a$$$ that are strictly greater than $$$x$$$ ($$$> x$$$). The order of elements in each part is kept the same as before the operation, i. e. the partition is stable. Then the array is replaced with the concatenation of the left and the right parts.For example, if the array $$$a$$$ is $$$[2, 4, 1, 5, 3]$$$, the eversion goes like this: $$$[2, 4, 1, 5, 3] \to [2, 1, 3], [4, 5] \to [2, 1, 3, 4, 5]$$$.We start with the array $$$a$$$ and perform eversions on this array. We can prove that after several eversions the array $$$a$$$ stops changing. Output the minimum number $$$k$$$ such that the array stops changing after $$$k$$$ eversions.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer $$$k$$$ — the number of eversions after which the array stops changing.

immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto a = ma(n, readInt!int);
  auto mxAi = a.fold!max;
  int ops = 0;
  int mx = 0;
  foreach_reverse(i; 0 .. n)
    {
      if (a[i] == mxAi) break;
      if (a[i] > mx)
	{
	  ops++;
	  mx = a[i];
	}
    }
  ops.writeln;
}

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

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

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

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

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


During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.You are given a sequence $$$a$$$, consisting of $$$n$$$ distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process.  First element $$$a_1$$$ becomes the root of the tree.  Elements $$$a_2, a_3, \ldots, a_n$$$ are added one by one. To add element $$$a_i$$$ one needs to traverse the tree starting from the root and using the following rules:   The pointer to the current node is set to the root.  If $$$a_i$$$ is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node.  If at some point there is no required child, the new node is created, it is assigned value $$$a_i$$$ and becomes the corresponding child of the current node.

The first line of the input contains a single integer $$$n$$$ ($$$2 \leq n \leq 100\,000$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ distinct integers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) — the sequence $$$a$$$ itself.

Output $$$n - 1$$$ integers. For all $$$i > 1$$$ print the value written in the node that is the parent of the node with value $$$a_i$$$ in it.

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

immutable int INF = 10 ^^ 9 + 23;

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

    auto arr = readln.chomp.split.map!(to!int).array;

    auto rbt = make!(RedBlackTree!int)([0, arr[0], INF]);

    debug { rbt.writeln; }

    int [int] lvl;
    lvl[arr[0]] = 0;
    lvl[0] = -1;
    lvl[INF] = -1;

    int[] ans;

    foreach (i, e; arr[1 .. $]) {
        int lower = rbt.lowerBound(e).back;
        int higher = rbt.upperBound(e).front;

        if (lvl[lower] > lvl[higher]) { ans ~= lower; }
        else { ans ~= higher; }

        lvl[e] = lvl[ans.back] + 1;
        rbt.insert(e);
    }

    ans.writefln!"%(%s %)";
}


Vasya has a multiset $$$s$$$ consisting of $$$n$$$ integer numbers. Vasya calls some number $$$x$$$ nice if it appears in the multiset exactly once. For example, multiset $$$\{1, 1, 2, 3, 3, 3, 4\}$$$ contains nice numbers $$$2$$$ and $$$4$$$.Vasya wants to split multiset $$$s$$$ into two multisets $$$a$$$ and $$$b$$$ (one of which may be empty) in such a way that the quantity of nice numbers in multiset $$$a$$$ would be the same as the quantity of nice numbers in multiset $$$b$$$ (the quantity of numbers to appear exactly once in multiset $$$a$$$ and the quantity of numbers to appear exactly once in multiset $$$b$$$).

The first line contains a single integer $$$n~(2 \le n \le 100)$$$. The second line contains $$$n$$$ integers $$$s_1, s_2, \dots s_n~(1 \le s_i \le 100)$$$ — the multiset $$$s$$$.

If there exists no split of $$$s$$$ to satisfy the given requirements, then print "NO" in the first line. Otherwise print "YES" in the first line. The second line should contain a string, consisting of $$$n$$$ characters. $$$i$$$-th character should be equal to 'A' if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$a$$$ and 'B' if if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$b$$$. Elements are numbered from $$$1$$$ to $$$n$$$ in the order they are given in the input. If there exist multiple solutions, then print any of them.

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

  int n; rd(n);
  auto a=readln.split.to!(int[]);

  auto freq=new int[](105);
  foreach(e; a) freq[e]++;
  int nice=0;
  foreach(e; freq){
    if(e==1) nice++;
  }
  if(nice&1){
    if(n==nice){
      writeln("NO");
      return;
    }
    bool o=reduce!((r, e)=>(r || (e>=3)))(false, freq);
    if(o==false){
      writeln("NO");
      return;
    }
    writeln("YES");
    int _nice=0;
    char[] ans;
    bool done=false;
    foreach(i; 0..n){
      if(freq[a[i]]>=3){
        if(done==false){
          ans~='A';
          done=true;
        }else{
          ans~='B';
        }
      }else if(_nice*2<nice-1){
        if(freq[a[i]]==1){
          ans~='A';
          _nice++;
        }else{
          ans~='B';
        }
      }else{
        ans~='B';
      }
    }
    writeln(ans);
    return;
  }
  writeln("YES");
  int _nice=0;
  char[] ans;
  foreach(i; 0..n){
    if(_nice*2<nice){
      if(freq[a[i]]==1){
        ans~='A';
        _nice++;
      }else{
        ans~='B';
      }
    }else{
      ans~='B';
    }
  }
  writeln(ans);
}

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

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

  int n; rd(n);
  auto a=readln.split.to!(int[]);

  auto freq=new int[](105);
  foreach(e; a) freq[e]++;
  int nice=0;
  foreach(e; freq){
    if(e==1) nice++;
  }
  if(nice&1){
    if(n==nice){
      writeln("NO");
      return;
    }
    bool o=reduce!((r, e)=>(r || (e>=3)))(false, freq);
    if(o==false){
      writeln("NO");
      return;
    }
    writeln("YES");
    int _nice=0;
    char[] ans;
    bool done=false;
    foreach(i; 0..n){
      if(freq[a[i]]>=3){
        if(done==false){
          ans~='A';
          done=true;
        }else{
          ans~='B';
        }
      }else if(_nice*2<nice){
        if(freq[a[i]]==1){
          ans~='A';
          _nice++;
        }else{
          ans~='B';
        }
      }else{
        ans~='B';
      }
    }
    writeln(ans);
    return;
  }
  writeln("YES");
  int _nice=0;
  char[] ans;
  foreach(i; 0..n){
    if(_nice*2<nice){
      if(freq[a[i]]==1){
        ans~='A';
        _nice++;
      }else{
        ans~='B';
      }
    }else{
      ans~='B';
    }
  }
  writeln(ans);
}

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

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

  int n; rd(n);
  auto a=readln.split.to!(int[]);

  auto freq=new int[](105);
  foreach(e; a) freq[e]++;
  int nice=0;
  foreach(e; freq){
    if(e==1) nice++;
  }
  if(nice&1){
    writeln("NO");
    return;
  }
  writeln("YES");
  int _nice=0;
  auto used=new bool[](n);
  foreach(i; 0..n){
    if(_nice*2<nice){
      if(freq[a[i]]==1){
        write("A");
        _nice++;
      }else{
        write("B");
      }
    }else{
      write("B");
    }
  }
  writeln("");
}

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

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

  int n; rd(n);
  auto a=readln.split.to!(int[]);

  auto freq=new int[](105);
  foreach(e; a) freq[e]++;
  int nice=0;
  foreach(e; freq){
    if(e==1) nice++;
  }
  if(nice&1){
    writeln("NO");
    return;
  }
  int _nice=0;
  auto used=new bool[](n);
  foreach(i; 0..n){
    if(_nice*2<nice){
      if(freq[a[i]]==1){
        write("A");
        _nice++;
      }else{
        write("B");
      }
    }else{
      write("B");
    }
  }
  writeln("");
}

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

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

  int n; rd(n);
  auto a=readln.split.to!(int[]);

  auto freq=new int[](105);
  foreach(e; a) freq[e]++;
  int nice=0;
  foreach(e; freq){
    if(e==1) nice++;
  }
  if(nice&1){
    if(n==nice){
      writeln("NO");
      return;
    }
    bool o=reduce!((r, e)=>(r || (e>=3)))(false, freq);
    if(o==false){
      writeln("NO");
      return;
    }
    int _nice=0;
    char[] ans;
    bool done=false;
    foreach(i; 0..n){
      if(freq[a[i]]>=3){
        if(done==false){
          ans~='A';
          done=true;
        }else{
          ans~='B';
        }
      }else if(_nice*2<nice){
        if(freq[a[i]]==1){
          ans~='A';
          _nice++;
        }else{
          ans~='B';
        }
      }else{
        ans~='B';
      }
    }
    writeln(ans);
    return;
  }
  writeln("YES");
  int _nice=0;
  char[] ans;
  foreach(i; 0..n){
    if(_nice*2<nice){
      if(freq[a[i]]==1){
        ans~='A';
        _nice++;
      }else{
        ans~='B';
      }
    }else{
      ans~='B';
    }
  }
  writeln(ans);
}

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


Santa Claus has received letters from $$$n$$$ different kids throughout this year. Of course, each kid wants to get some presents from Santa: in particular, the $$$i$$$-th kid asked Santa to give them one of $$$k_i$$$ different items as a present. Some items could have been asked by multiple kids.Santa is really busy, so he wants the New Year Bot to choose the presents for all children. Unfortunately, the Bot's algorithm of choosing presents is bugged. To choose a present for some kid, the Bot does the following:  choose one kid $$$x$$$ equiprobably among all $$$n$$$ kids;  choose some item $$$y$$$ equiprobably among all $$$k_x$$$ items kid $$$x$$$ wants;  choose a kid $$$z$$$ who will receive the present equipropably among all $$$n$$$ kids (this choice is independent of choosing $$$x$$$ and $$$y$$$); the resulting triple $$$(x, y, z)$$$ is called the decision of the Bot. If kid $$$z$$$ listed item $$$y$$$ as an item they want to receive, then the decision valid. Otherwise, the Bot's choice is invalid.Santa is aware of the bug, but he can't estimate if this bug is really severe. To do so, he wants to know the probability that one decision generated according to the aforementioned algorithm is valid. Can you help him?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the number of kids who wrote their letters to Santa. Then $$$n$$$ lines follow, the $$$i$$$-th of them contains a list of items wanted by the $$$i$$$-th kid in the following format: $$$k_i$$$ $$$a_{i, 1}$$$ $$$a_{i, 2}$$$ ... $$$a_{i, k_i}$$$ ($$$1 \le k_i, a_{i, j} \le 10^6$$$), where $$$k_i$$$ is the number of items wanted by the $$$i$$$-th kid, and $$$a_{i, j}$$$ are the items themselves. No item is contained in the same list more than once. It is guaranteed that $$$\sum \limits_{i = 1}^{n} k_i \le 10^6$$$.

Print the probatility that the Bot produces a valid decision as follows: Let this probability be represented as an irreducible fraction $$$\frac{x}{y}$$$. You have to print $$$x \cdot y^{-1} \mod 998244353$$$, where $$$y^{-1}$$$ is the inverse element of $$$y$$$ modulo $$$998244353$$$ (such integer that $$$y \cdot y^{-1}$$$ has remainder $$$1$$$ modulo $$$998244353$$$).

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

pure nothrow @nogc
T gcdext(T) (T a, T b, ref T x, ref T y) {
  if (!b) {
    x = 1;
    y = 0;
    return a;
  }
  T res = gcdext (b, a % b, y, x);
  y -= x * (a / b);
  return res;
}

pure
X genericPower(alias mul, X, Y) (X x, Y y, X one = 1.to!X)
  if (isUnsigned!Y) {
  X a = one, b = x;
  while (y > 0) {
    if (y & 1) {
      a = binaryFun!mul (a, b);
    }
    b = binaryFun!mul (b, b);
    y >>>= 1;
  }
  return a;
}

struct IntM(int q = 1_000_000_007) {
  alias N = IntM!q;
  private:
  int v;
  //invariant () { assert (v >= 0 && v < q); }
  pure nothrow @nogc
  static int from(T) (const T m) if (isIntegral!T) {
    int v = m % q;
    static if (isSigned!T) {
      if (v < 0) {
        v += q;
      }
    }
    return v;
  }
  public:
  pure nothrow @nogc
  this(T) (const T m) if (isIntegral!T) {
    v = from!T (m);
  }
  pure nothrow @nogc
  N opAssign(T) (const T m) if (isIntegral!T) {
    v = from!T (m);
    return this;
  }
  pure nothrow @nogc
  N opUnary (string op : "-")() const {
    return N (-v);
  }
  pure nothrow @nogc
  ref N opUnary (string op : "++")() {
    if (++v >= q) {
      v -= q;
    }
    return this;
  }
  pure nothrow @nogc
  ref N opUnary (string op : "--")() {
    if (--v < 0) {
      v += q;
    }
    return this;
  }
  pure nothrow @nogc
  ref N opOpAssign (string op : "+")(in N rhs) {
    v = (v + rhs.v) % q;
    return this;
  }
  pure nothrow @nogc
  ref N opOpAssign (string op : "-")(in N rhs) {
    v = (v - rhs.v + q) % q;
    return this;
  }
  pure nothrow @nogc
  ref N opOpAssign (string op : "*")(in N rhs) {
    v = (v.to!(long) * rhs.v) % q;
    return this;
  }
  pure nothrow @nogc
  ref N opOpAssign (string op : "/")(in N rhs) {
    return this *= rhs.inversion ();
  }
  pure nothrow @nogc
  ref N opOpAssign (string op)(in int rhs) if (op == "+" || op == "-" || op == "*" || op == "/") {
    mixin ("return this " ~ op ~ "= N(rhs);");
  }
  pure nothrow @nogc
  N opBinary (string op)(in N rhs) const if (op == "+" || op == "-" || op == "*" || op == "/") {
    N t = this;
    mixin ("t " ~ op ~ "= rhs;");
    return t;
  }
  pure nothrow @nogc
  N opBinary(string op,T)(const T rhs) const if (isIntegral!T && (op == "+" || op == "-" || op == "*" || op == "/")) {
    mixin ("return this " ~ op ~ " N(rhs);");
  }
  pure nothrow @nogc
  N opBinaryRight(string op,T)(const T rhs) const if (isIntegral!T && (op == "+" || op == "*")) {
    mixin ("return this " ~ op ~ " N(rhs);");
  }
  pure nothrow @nogc
  N inversion () const {
    int x, y;
    immutable g = gcdext!int (v, q, x, y);
    assert (g == 1);
    return N (x);
  }
  pure nothrow @nogc
  N opBinary (string op : "^^")(in ulong rhs) const {
    return genericPower! ("a * b", N, ulong) (this, rhs);
  }
  pure nothrow @nogc
  int opCast(T : int)() const { return v; }
  pure nothrow @nogc
  int opCmp (const N rhs) const {
    if (v < rhs.v) {
      return -1;
    }
    if (v > rhs.v) {
      return 1;
    }
    return 0;
  }
  pure nothrow
  string toString() const { return v.text; }
}

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

alias N = IntM!998244353;

void main() {
  auto r = new InputReader;
  auto n = r.next!uint;
  auto a = new uint[][n];
  uint maxA;
  size_t maxL;
  foreach (i; 0 .. n) {
    a[i] = r.nextA!uint(r.next!uint);
    foreach (x; a[i]) {
      if (maxA < x) maxA = x;
    }
    if (maxL < a[i].length) maxL = a[i].length;
  }
  auto c = new int[maxA+1];
  auto il = new N[maxL+1];
  foreach (i; 0 .. n) {
    foreach (x; a[i]) ++c[x];
    auto l = a[i].length;
    if (il[l].v == 0) il[l] = N (l.to!int).inversion ();
  }
  auto invN = N (n).inversion();
  N res = 0;
  foreach (i; 0 .. n) {
    N t = 0;
    foreach (x; a[i]) {
      N u;
      u.v = c[x];
      t += u * invN;
    }
    res += t * il[a[i].length];
  }
  writeln (res * invN);
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

int N = 1_000_099;

void solve(){
	int n = rint;
	Finite[] ps;
	foreach(i; 0 .. N) ps ~= Finite(0);
	long[] us = new long[](N);
	foreach(i; 0 .. n){
		int k = rint;
		int[] as = rint(k).map!(x => x - 1).array;
		foreach(a; as){
			ps[a] += Finite(1) / k;
			us[a] += 1;
		}
	}
	Finite ans = Finite(0);
	foreach(a; 0 .. N) ans += ps[a] * us[a] / n / n;

	ans.writeln;
}

import std.conv;
struct Finite{
	long value; static long mod = 998244353;
	private static long[] _inv = [0, 1], _frac = [1, 1], _invfrac = [1, 1];
	this(long v){ value = val(v); }
	static long val(long v){
		if(v >= 0) return v % mod;
		else return (v + mod  - (v / mod) * mod) % mod;
	}
	bool opCast(T: bool)(){ return value != 0; }
	Finite opUnary(string s){ long v;
		if(s == "+") v = value;
		else if(s == "-") v = mod - value;
		else if(s == "++") v = value + 1;
		else if(s == "--") v = value + mod - 1;
		else assert(0, "Operator unary " ~ s ~ " not implemented");
		return Finite(v);
	}
	Finite opBinary(string s)(Finite b){
		return opBinary!s(b.value);
	}
	Finite opBinary(string s)(long u){ long v;
		if(s == "+") v = value + u;
		else if(s == "-") v = value + mod - u;
		else if(s == "*") v = value * u;
		else if(s == "/") v = value * inv(u);
		else assert(0, "Operator " ~ s ~ " not implemented");
		return Finite(v);
	}
	Finite opBinaryRight(string s)(long u){ long v;
		if(s == "+") v = u + value;
		else if(s == "-") v = u + mod - value;
		else if(s == "*") v = u * value;
		else if(s == "/") v = u * invvalue;
		else assert(0, "Operator " ~ s ~ " not implemented");
		return Finite(v);
	}
	Finite opAssign(long v){ value = v; return this; }
	Finite opOpAssign(string s)(Finite b){
		return opOpAssign!s(b.value);
	}
	Finite opOpAssign(string s)(long v){
		if(s == "+") value = (value + v) % mod;
		else if(s == "-") value = (value + mod - v) % mod;
		else if(s == "*") value = (value * v) % mod;
		else if(s == "/") value = (value * inv(v)) % mod;
		else assert(0, "Operator " ~ s ~ "= not implemented");
		return this;
	}
	bool opEquals(Finite b){
		return(value == b.value);
	}
	string toString(){ return value.to!string; }
	long inv(long v){
		v = val(v);
		while(v >= _inv.length){
			_inv ~= _inv[(mod % $).to!int] * (mod - mod / _inv.length) % mod;
		}
		return _inv[v.to!int];
	}
	long invvalue(){
		return inv(value);
	}
	static Finite opCall(long v){ return Finite(val(v)); }

}

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

pure nothrow @nogc
T gcdext(T) (T a, T b, ref T x, ref T y) {
  if (!b) {
    x = 1;
    y = 0;
    return a;
  }
  T res = gcdext (b, a % b, y, x);
  y -= x * (a / b);
  return res;
}

pure
X genericPower(alias mul, X, Y) (X x, Y y, X one = 1.to!X)
  if (isUnsigned!Y) {
  X a = one, b = x;
  while (y > 0) {
    if (y & 1) {
      a = binaryFun!mul (a, b);
    }
    b = binaryFun!mul (b, b);
    y >>>= 1;
  }
  return a;
}

struct IntM(int q = 1_000_000_007) {
  alias N = IntM!q;
  private:
  int v;
  //invariant () { assert (v >= 0 && v < q); }
  pure nothrow @nogc
  static int from(T) (const T m) if (isIntegral!T) {
    int v = m % q;
    static if (isSigned!T) {
      if (v < 0) {
        v += q;
      }
    }
    return v;
  }
  public:
  pure nothrow @nogc
  this(T) (const T m) if (isIntegral!T) {
    v = from!T (m);
  }
  pure nothrow @nogc
  N opAssign(T) (const T m) if (isIntegral!T) {
    v = from!T (m);
    return this;
  }
  pure nothrow @nogc
  N opUnary (string op : "-")() const {
    return N (-v);
  }
  pure nothrow @nogc
  ref N opUnary (string op : "++")() {
    if (++v >= q) {
      v -= q;
    }
    return this;
  }
  pure nothrow @nogc
  ref N opUnary (string op : "--")() {
    if (--v < 0) {
      v += q;
    }
    return this;
  }
  pure nothrow @nogc
  ref N opOpAssign (string op : "+")(in N rhs) {
    v = (v + rhs.v) % q;
    return this;
  }
  pure nothrow @nogc
  ref N opOpAssign (string op : "-")(in N rhs) {
    v = (v - rhs.v + q) % q;
    return this;
  }
  pure nothrow @nogc
  ref N opOpAssign (string op : "*")(in N rhs) {
    v = (v.to!(long) * rhs.v) % q;
    return this;
  }
  pure nothrow @nogc
  ref N opOpAssign (string op : "/")(in N rhs) {
    return this *= rhs.inversion ();
  }
  pure nothrow @nogc
  ref N opOpAssign (string op)(in int rhs) if (op == "+" || op == "-" || op == "*" || op == "/") {
    mixin ("return this " ~ op ~ "= N(rhs);");
  }
  pure nothrow @nogc
  N opBinary (string op)(in N rhs) const if (op == "+" || op == "-" || op == "*" || op == "/") {
    N t = this;
    mixin ("t " ~ op ~ "= rhs;");
    return t;
  }
  pure nothrow @nogc
  N opBinary(string op,T)(const T rhs) const if (isIntegral!T && (op == "+" || op == "-" || op == "*" || op == "/")) {
    mixin ("return this " ~ op ~ " N(rhs);");
  }
  pure nothrow @nogc
  N opBinaryRight(string op,T)(const T rhs) const if (isIntegral!T && (op == "+" || op == "*")) {
    mixin ("return this " ~ op ~ " N(rhs);");
  }
  pure nothrow @nogc
  N inversion () const {
    int x, y;
    immutable g = gcdext!int (v, q, x, y);
    assert (g == 1);
    return N (x);
  }
  pure nothrow @nogc
  N opBinary (string op : "^^")(in ulong rhs) const {
    return genericPower! ("a * b", N, ulong) (this, rhs);
  }
  pure nothrow @nogc
  int opCast(T : int)() const { return v; }
  pure nothrow @nogc
  int opCmp (const N rhs) const {
    if (v < rhs.v) {
      return -1;
    }
    if (v > rhs.v) {
      return 1;
    }
    return 0;
  }
  pure nothrow
  string toString() const { return v.text; }
}

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }

  template next(T) if (isSigned!T) {
    final T next ()  {
      T res;
      ubyte b = skipByte (45);
      if (b == 45) {
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  final T[] nextA(T) (int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

alias N = IntM!998244353;

void main() {
  auto r = new InputReader;
  auto n = r.next!uint;
  auto a = new uint[][n];
  uint maxA;
  foreach (i; 0 .. n) {
    a[i] = r.nextA!uint(r.next!uint);
    foreach (x; a[i]) {
      if (maxA < x) maxA = x;
    }
  }
  auto c = new int[maxA+1];
  auto il = new N[n+1];
  foreach (i; 0 .. n) {
    foreach (x; a[i]) ++c[x];
    auto l = a[i].length;
    if (il[l].v == 0) il[l] = N (l.to!int).inversion ();
  }
  auto invN = N (n).inversion();
  N res = 0;
  foreach (i; 0 .. n) {
    N t = 0;
    foreach (x; a[i]) {
      N u;
      u.v = c[x];
      t += u * invN;
    }
    res += t * il[a[i].length];
  }
  writeln (res * invN);
}


Vova decided to clean his room. The room can be represented as the coordinate axis $$$OX$$$. There are $$$n$$$ piles of trash in the room, coordinate of the $$$i$$$-th pile is the integer $$$p_i$$$. All piles have different coordinates.Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $$$x$$$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $$$x$$$ and move all piles from $$$x$$$ to $$$x+1$$$ or $$$x-1$$$ using his broom. Note that he can't choose how many piles he will move.Also, there are two types of queries:  $$$0$$$ $$$x$$$ — remove a pile of trash from the coordinate $$$x$$$. It is guaranteed that there is a pile in the coordinate $$$x$$$ at this moment.  $$$1$$$ $$$x$$$ — add a pile of trash to the coordinate $$$x$$$. It is guaranteed that there is no pile in the coordinate $$$x$$$ at this moment. Note that it is possible that there are zero piles of trash in the room at some moment.Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.For better understanding, please read the Notes section below to see an explanation for the first example.

The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$) — the number of piles in the room before all queries and the number of queries, respectively. The second line of the input contains $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th pile. The next $$$q$$$ lines describe queries. The $$$i$$$-th query is described with two integers $$$t_i$$$ and $$$x_i$$$ ($$$0 \le t_i \le 1; 1 \le x_i \le 10^9$$$), where $$$t_i$$$ is $$$0$$$ if you need to remove a pile from the coordinate $$$x_i$$$ and is $$$1$$$ if you need to add a pile to the coordinate $$$x_i$$$. It is guaranteed that for $$$t_i = 0$$$ there is such pile in the current set of piles and for $$$t_i = 1$$$ there is no such pile in the current set of piles.

Print $$$q+1$$$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $$$q$$$ queries.

NoteConsider the first example.Initially, the set of piles is $$$[1, 2, 6, 8, 10]$$$. The answer before the first query is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with one move, all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves and all piles from $$$6$$$ to $$$8$$$ with $$$2$$$ moves.After the first query, the set becomes $$$[1, 2, 4, 6, 8, 10]$$$. Then the answer is $$$7$$$ because you can move all piles from $$$6$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$4$$$ to $$$2$$$ with $$$2$$$ moves, all piles from $$$2$$$ to $$$1$$$ with $$$1$$$ move and all piles from $$$10$$$ to $$$8$$$ with $$$2$$$ moves.After the second query, the set of piles becomes $$$[1, 2, 4, 6, 8, 9, 10]$$$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).After the third query, the set of piles becomes $$$[1, 2, 4, 8, 9, 10]$$$ and the answer is $$$5$$$ because you can move all piles from $$$1$$$ to $$$2$$$ with $$$1$$$ move, all piles from $$$2$$$ to $$$4$$$ with $$$2$$$ moves, all piles from $$$10$$$ to $$$9$$$ with $$$1$$$ move and all piles from $$$9$$$ to $$$8$$$ with $$$1$$$ move.After the fourth query, the set becomes $$$[1, 2, 4, 8, 9]$$$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $$$10$$$).After the fifth query, the set becomes $$$[1, 2, 4, 8, 9, 100]$$$. You can move all piles from $$$1$$$ and further to $$$9$$$ and keep $$$100$$$ at its place. So the answer is $$$8$$$.After the sixth query, the set becomes $$$[1, 2, 4, 8, 9, 50, 100]$$$. The answer is $$$49$$$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $$$50$$$ to $$$9$$$ too.

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

alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, long);
static string[] inp;
T rd(T = long)(){ while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0){ auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

/* Work in improving lb/ub finding technique in D lang */

void solve(){
    int n, q;
    n = rd!int; q = rd!int;
    ll[] arr = rdarr;
    arr.sort;
    auto diffs = rbt!(true, ll);
    ll sumdiff = 0, maxdiff = 0;
    foreach(i; 1..n){
        diffs.insert(arr[i] - arr[i-1]);
        sumdiff += (arr[i] - arr[i-1]);
        maxdiff = max(maxdiff, arr[i] - arr[i-1]);
    }

    auto points = rbt!(true, ll);
    points.insert(arr);
    writeln(sumdiff - maxdiff);

    foreach(i; 0..q){
        int stat = rd!int; ll qpt = rd, lo, hi;
        if(stat){
        // Add
            if(points.length){
                if(qpt in points){
                    diffs.insert([0, 0]);
                }else{
                    auto down = points.lowerBound(qpt);
                    auto up = points.upperBound(qpt);
                    if(!down.empty){
                        lo = down.back;
                        diffs.insert(qpt - lo);
                        sumdiff += (qpt - lo);
                    }
                    if(!up.empty){
                        hi = up.front;
                        diffs.insert(hi - qpt);
                        sumdiff += (hi - qpt);
                    }
                    // Erase Previous Diff
                    if(!up.empty && !down.empty){
                        diffs.removeKey(hi - lo);
                        sumdiff -= hi - lo;
                    }
                }
            }
            points.insert(qpt);
        }else{
        // Remo
            points.removeKey(qpt);
            if(qpt in points){
                diffs.removeKey([0, 0]);
            }else{
                auto down = points.lowerBound(qpt);
                auto up = points.upperBound(qpt);
                if(!down.empty){
                    lo = down.back;
                    diffs.removeKey(qpt - lo);
                    sumdiff -= (qpt - lo);
                }
                if(!up.empty){
                    hi = up.front;
                    diffs.removeKey(hi - qpt);
                    sumdiff -= (hi - qpt);
                }
                // Insert Next Diff
                if(!up.empty && !down.empty){
                    diffs.insert(hi - lo);
                    sumdiff += hi - lo;
                }
            }
        }
        /* debug{writeln(points); writeln(diffs);} */
        maxdiff = (diffs.length) ? diffs.back : 0;
        writeln(sumdiff - maxdiff);
    }
}

void main(){
    long t = 1;
    /* t = rd; */
    while(t--) solve();
    stdout.flush;
}


There are $$$n$$$ cities in Shaazzzland, numbered from $$$0$$$ to $$$n-1$$$. Ghaazzzland, the immortal enemy of Shaazzzland, is ruled by AaParsa.As the head of the Ghaazzzland's intelligence agency, AaParsa is carrying out the most important spying mission in Ghaazzzland's history on Shaazzzland.AaParsa has planted $$$m$$$ transport cannons in the cities of Shaazzzland. The $$$i$$$-th cannon is planted in the city $$$a_i$$$ and is initially pointing at city $$$b_i$$$.It is guaranteed that each of the $$$n$$$ cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs $$$(a_i, b_i)$$$ are distinct).AaParsa used very advanced technology to build the cannons, the cannons rotate every second. In other words, if the $$$i$$$-th cannon is pointing towards the city $$$x$$$ at some second, it will target the city $$$(x + 1) \mod n$$$ at the next second.As their name suggests, transport cannons are for transportation, specifically for human transport. If you use the $$$i$$$-th cannon to launch yourself towards the city that it's currently pointing at, you'll be airborne for $$$c_i$$$ seconds before reaching your target destination.If you still don't get it, using the $$$i$$$-th cannon at the $$$s$$$-th second (using which is only possible if you are currently in the city $$$a_i$$$) will shoot you to the city $$$(b_i + s) \mod n$$$ and you'll land in there after $$$c_i$$$ seconds (so you'll be there in the $$$(s + c_i)$$$-th second). Also note the cannon that you initially launched from will rotate every second but you obviously won't change direction while you are airborne. AaParsa wants to use the cannons for travelling between Shaazzzland's cities in his grand plan, and he can start travelling at second $$$0$$$. For him to fully utilize them, he needs to know the minimum number of seconds required to reach city $$$u$$$ from city $$$v$$$ using the cannons for every pair of cities $$$(u, v)$$$.Note that AaParsa can stay in a city for as long as he wants.

The first line contains two integers $$$n$$$ and $$$m$$$ $$$(2 \le n \le 600 , n \le m \le n^2)$$$ — the number of cities and cannons correspondingly. The $$$i$$$-th line of the following $$$m$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$ and $$$c_i$$$ $$$( 0 \le a_i , b_i \le n-1 , 1 \le c_i \le 10^9)$$$, denoting the cannon in the city $$$a_i$$$, which is initially pointing to $$$b_i$$$ and travelling by which takes $$$c_i$$$ seconds. It is guaranteed that each of the $$$n$$$ cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs $$$(a_i, b_i)$$$ are distinct).

Print $$$n$$$ lines, each line should contain $$$n$$$ integers. The $$$j$$$-th integer in the $$$i$$$-th line should be equal to the minimum time required to reach city $$$j$$$ from city $$$i$$$.

NoteIn the first example one possible path for going from $$$0$$$ to $$$2$$$ would be:   Stay inside $$$0$$$ and do nothing for $$$1$$$ second.  Use the first cannon and land at $$$2$$$ after $$$1$$$ second.  Note that: we could have used the second cannon in $$$0$$$-th second but it would have taken us $$$3$$$ seconds to reach city $$$2$$$ in that case.

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

immutable uint infinity = uint.max / 2;

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		readln;
		alias Edge = Tuple !(int, q{v}, int, q{t});
		auto g = new uint [] [] (n, n);
		foreach (ref line; g)
		{
			line[] = infinity;
		}
		foreach (j; 0..m)
		{
			int a, b, c;
			readf !(" %s %s %s") (a, b, c);
			g[a][b] = min (g[a][b], c);
		}

		auto start = g.map !(line => n - line.minPos.length.to !(int));
		auto r = new uint [] [] (n, n);
		foreach (ref line; r)
		{
			line[] = infinity;
		}

		foreach (k; 0..n)
		{
			auto d = new uint [n];
			d[] = infinity;
			d[k] = 0;
			auto vis = new bool [n];
			foreach (step; 0..n)
			{
				int i = 0;
				uint dist = infinity;
				foreach (j; 0..n)
				{
					if (!vis[j] && dist > d[j])
					{
						i = j;
						dist = d[j];
					}
				}

				vis[i] = true;
				r[k][i] = dist;
				int rem = dist % n;
				uint prev = infinity;
				int j = start[i];
				int v = (j + rem) % n;
				int p = 0;
				while (p < n)
				{
					while (j < n && v < n && p < n)
					{
						prev = min (prev + 1, g[i][j]);
						d[v] = min (d[v], d[i] + prev);
						j += 1;
						v += 1;
						p += 1;
					}
					j %= n;
					v %= n;
				}
			}
		}

		writefln !("%(%(%s %)\n%)") (r);
		break;
	}
}