You are given a book with $$$n$$$ chapters.Each chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list.Currently you don't understand any of the chapters. You are going to read the book from the beginning till the end repeatedly until you understand the whole book. Note that if you read a chapter at a moment when you don't understand some of the required chapters, you don't understand this chapter.Determine how many times you will read the book to understand every chapter, or determine that you will never understand every chapter no matter how many times you read the book.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot10^4$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — number of chapters. Then $$$n$$$ lines follow. The $$$i$$$-th line begins with an integer $$$k_i$$$ ($$$0 \le k_i \le n-1$$$) — number of chapters required to understand the $$$i$$$-th chapter. Then $$$k_i$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i, k_i}$$$ ($$$1 \le a_{i, j} \le n, a_{i, j} \ne i, a_{i, j} \ne a_{i, l}$$$ for $$$j \ne l$$$) follow — the chapters required to understand the $$$i$$$-th chapter. It is guaranteed that the sum of $$$n$$$ and sum of $$$k_i$$$ over all testcases do not exceed $$$2\cdot10^5$$$.

For each test case, if the entire book can be understood, print how many times you will read it, otherwise print $$$-1$$$.

NoteIn the first example, we will understand chapters $$$\{2, 4\}$$$ in the first reading and chapters $$$\{1, 3\}$$$ in the second reading of the book.In the second example, every chapter requires the understanding of some other chapter, so it is impossible to understand the book.In the third example, every chapter requires only chapters that appear earlier in the book, so we can understand everything in one go.In the fourth example, we will understand chapters $$$\{2, 3, 4\}$$$ in the first reading and chapter $$$1$$$ in the second reading of the book.In the fifth example, we will understand one chapter in every reading from $$$5$$$ to $$$1$$$.

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto requires = new int[][](n);
	auto requiredBy = new int[][](n);
	auto requirements = new int[](n);
	auto understandable = redBlackTree!int;
	auto processed = new bool[](n);
	int size = n;
	foreach(i; 0 .. n)
	{
		auto k = readInt!int;
		requires[i] = ma(k, readInt!int - 1);
		requirements[i] = cast(int)requires[i].length;
		foreach(j; requires[i])
			requiredBy[j] ~= i;
		if (requires[i].length == 0)
		{
			understandable.insert(i);
		}
	}
	int passes = 0;
	while (!understandable.empty)
	{
		passes++;
		auto range = understandable.upperBound(-1);
		while (!range.empty)
		{
			auto current = range.front;
			understandable.removeKey(current);
			processed[current] = true;
			foreach(dependents; requiredBy[current])
			{
				requirements[dependents]--;
				assert(requirements[dependents] >= 0);
				if (requirements[dependents] == 0)
				{
					understandable.insert(dependents);
				}
			}
			range = understandable.upperBound(current);
		}
	}
	if (!all(processed))
	{
		writeln(-1);
	}
	else
	{
		writeln(passes);
	}
}

//{{{
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;
// }}}

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto requires = new int[][](n);
	auto requiredBy = new int[][](n);
	auto requirements = new int[](n);
	auto understandable = redBlackTree!int;
	auto processed = new bool[](n);
	int size = n;
	foreach(i; 0 .. n)
	{
		auto k = readInt!int;
		requires[i] = ma(k, readInt!int - 1);
		requirements[i] = cast(int)requires[i].length;
		foreach(j; requires[i])
			requiredBy[j] ~= i;
		if (requires[i].length == 0)
		{
			understandable.insert(i);
		}
	}
	int passes = 0;
	while (!understandable.empty)
	{
		passes++;
		auto range = understandable.upperBound(-1);
		while (!range.empty)
		{
			auto current = range.front;
			understandable.removeKey(current);
			processed[current] = true;
			foreach(dependents; requiredBy[current])
			{
				requirements[dependents]--;
				assert(requirements[dependents] >= 0);
				if (requirements[dependents] == 0)
				{
					understandable.insert(dependents);
				}
			}
			range = understandable.upperBound(current);
		}
	}
	bool remain = false;
	foreach(ins;processed) if (!ins) remain = true;
	if (remain)
	{
		writeln(-1);
	}
	else
	{
		writeln(passes);
	}
}

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

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

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

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

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

import std.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[] K;
int[][] A;

int[] vis;
int[] dp;

bool dfs(int u) {
  vis[u] = 1;
  dp[u] = 1;
  foreach (v; A[u]) {
    if (vis[v] == 0) {
      if (!dfs(v)) {
        return false;
      }
    } else if (vis[v] == 1) {
      return false;
    }
    chmax(dp[u], ((u < v) ? 1 : 0) + dp[v]);
  }
  vis[u] = 2;
  return true;
}

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

        vis = new int[N];
        dp = new int[N];
        bool ok = true;
        foreach (u; 0 .. N) {
          if (vis[u] == 0) {
            if (!dfs(u)) {
              ok = false;
              break;
            }
          }
        }

        int ans;
        if (ok) {
          ans = dp.maxElement;
        } else {
          ans = -1;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

int[][] scc(in int[][] G, in int[][] rG) {
    // calculate scc
    int N = cast(int)(G.length);
    auto used = new bool[N];
    int[] postorder;
    void vis_forward(int v) {
        used[v] = true;
        foreach (u; G[v]) {
            if (used[u]) continue;
            vis_forward(u);
        }
        postorder ~= v;
    }
    for (int v = 0; v < N; v++) {
        if (used[v]) continue;
        vis_forward(v);
    }
    auto cid = new int[N]; cid[] = -1; // i = cid[v]: vertex `v` belongs to the `i`-th component
    void vis_backward(int v, int k) {
        cid[v] = k;
        foreach (u; rG[v]) {
            if (cid[u] >= 0) continue;
            vis_backward(u, k);
        }
    }
    int k = 0;
    foreach_reverse (v; postorder) {
        if (cid[v] >= 0) continue;
        vis_backward(v, k++);
    }
    auto ret = new int[][k];
    foreach (v; 0 .. N) {
        ret[ cid[v] ] ~= v;
    }
    return ret;
}

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

alias Edge = Tuple!(int, "to", int, "cost");

void solve() {
    int N = read!int;
    auto xG = new int[][N];
    auto rG = new int[][N];
    auto G = new Edge[][N];
    foreach (i; 0 .. N) {
        auto rs = readarray!int[1 .. $];
        foreach (r; rs) {
            int j = r - 1;
            xG[i] ~= j;
            rG[j] ~= i;
            if (j < i) {
                G[i] ~= Edge(j, 0);
            } else {
                G[i] ~= Edge(j, 1);
            }
        }
    }
    auto grs = scc(xG, rG);
    if (grs.length == xG.length) {
        // ok. there's no scc
        auto ord = new int[N]; ord[] = -1;
        int f(int v) {
            if (ord[v] >= 0) return ord[v];
            int ret = 0;
            foreach (e; G[v]) {
                int x = e.cost + f(e.to);
                ret.chmax(x);
            }
            return ord[v] = ret;
        }
        int ans = 0;
        for (int v = 0; v < N; v++) {
            ans.chmax(f(v));
        }
        writeln(ans + 1);
    } else {
        writeln(-1);
    }
}

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[] K;
int[][] A;

int[] vis;
int[] dp;

bool dfs(int u) {
  vis[u] = 1;
  dp[u] = 1;
  foreach (v; A[u]) {
    if (vis[v] == 0) {
      if (!dfs(v)) {
        return false;
      }
      chmax(dp[u], ((u < v) ? 1 : 0) + dp[v]);
    } else if (vis[v] == 1) {
      return false;
    }
  }
  vis[u] = 2;
  return true;
}

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

        vis = new int[N];
        dp = new int[N];
        bool ok = true;
        foreach (u; 0 .. N) {
          if (vis[u] == 0) {
            if (!dfs(u)) {
              ok = false;
              break;
            }
          }
        }

        int ans;
        if (ok) {
          ans = dp.maxElement;
        } else {
          ans = -1;
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


You are given an array $$$a$$$ of $$$n$$$ integers and an integer $$$s$$$. It is guaranteed that $$$n$$$ is odd.In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to $$$s$$$.The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array $$$6, 5, 8$$$ is equal to $$$6$$$, since if we sort this array we will get $$$5, 6, 8$$$, and $$$6$$$ is located on the middle position.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$1\le n\le 2\cdot 10^5-1$$$, $$$1\le s\le 10^9$$$) — the length of the array and the required value of median. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1\le a_i \le 10^9$$$) — the elements of the array $$$a$$$. It is guaranteed that $$$n$$$ is odd.

In a single line output the minimum number of operations to make the median being equal to $$$s$$$.

NoteIn the first sample, $$$6$$$ can be increased twice. The array will transform to $$$8, 5, 8$$$, which becomes $$$5, 8, 8$$$ after sorting, hence the median is equal to $$$8$$$.In the second sample, $$$19$$$ can be increased once and $$$15$$$ can be increased five times. The array will become equal to $$$21, 20, 12, 11, 20, 20, 12$$$. If we sort this array we get $$$11, 12, 12, 20, 20, 20, 21$$$, this way the median is $$$20$$$.

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;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto S = s[1].to!long;
    auto A = readln.split.map!(to!long).array;
    A.sort();

    int i = N / 2;
    long ans = 0;

    if (A[i] > S) {
        while (i >= 0 && A[i] > S) {
            ans += A[i] - S;
            i -= 1;
        }
    } else if (A[i] < S) {
        while (i < N && A[i] < S) {
            ans += S - A[i];
            i += 1;
        }
    }

    ans.writeln;
}

import core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.datetime;
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;

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

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

    arr.sort();

    auto ans = 0L;
    if (arr[n/2] < s) {
        foreach (e; arr[n/2 .. $]) {
            if (e < s) ans += s - e;
        }
    } else if (arr[n/2] > s) {
        foreach (e; arr[0 .. n/2 + 1]) {
            if (e > s) ans += e - s;
        }
    }

    ans.writeln;
}

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

void main ()
{
	int n, s;
	while (readf (" %s %s", &n, &s) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		long res = 0;
		foreach (i; 0..n)
		{
			if (i <= n / 2)
			{
				res += max (0, a[i] - s);
			}
			if (i >= n / 2)
			{
				res += max (0, s - a[i]);
			}
		}
		writeln (res);
	}
}


A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).

The first line contains one integer $$$n$$$ ($$$13 \le n < 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.

If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.

NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.

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

void main() {
    auto N = readln.chomp.to!int;
    auto S = readln.chomp;
    auto used = new bool[](N);

    for (int i = 0, j = 0, t = 0, rest = N; rest > 11; t ^= 1, --rest) {
        if (t == 0) {
            while (i < N && (used[i] || S[i] == '8')) ++i;
            if (i >= N) {
                writeln("YES");
                return;
            }
            used[i] = true;
        } else {
            while (j < N && (used[j] || S[j] != '8')) ++j;
            if (j >= N) {
                writeln("NO");
                return;
            }
            used[j] = true;
        }
    }

    foreach (i; 0..N) {
        if (!used[i]) {
            writeln(S[i] == '8' ? "YES" : "NO");
            return;
        }
    }
}

//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;

void main() {
  auto n = readln.strip.to!int;
  auto s = readln.strip[0 .. n];
  auto psteps = (n - 11) >> 1;
  auto t = s[0 .. n - 10];
  int e;
  foreach (i; 0 .. t.length) {
    if (t[i] == '8') {
      ++e;
    }
  }
  writeln (e > psteps ? "YES" : "NO");
}

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto N = RD!int;
	auto s = RD!string;

	auto m = N - 11 + 1;
	long cnt;
	foreach (i; 0..m)
	{
		if (s[i] == '8')
		{
			++cnt;
		}
	}

	writeln(cnt > m / 2 ? "YES" : "NO");
	stdout.flush();
	debug readln();
}


You're given an array $$$a$$$ of length $$$2n$$$. Is it possible to reorder it in such way so that the sum of the first $$$n$$$ elements isn't equal to the sum of the last $$$n$$$ elements?

The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$), where $$$2n$$$ is the number of elements in the array $$$a$$$. The second line contains $$$2n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{2n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.

If there's no solution, print "-1" (without quotes). Otherwise, print a single line containing $$$2n$$$ space-separated integers. They must form a reordering of $$$a$$$. You are allowed to not change the order.

NoteIn the first example, the first $$$n$$$ elements have sum $$$2+1+3=6$$$ while the last $$$n$$$ elements have sum $$$1+1+2=4$$$. The sums aren't equal.In the second example, there's no solution.

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

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

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

    arr.sort();

    if (arr.front == arr.back) {
        writeln(-1);
        return;
    }

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

//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;

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

void main() {
  auto r = new InputReader;
  auto n = 2 * r.next!int;
  auto a = r.nextA!int(n);
  auto idx = new size_t[n];
  a.sort();
  if (a[0] == a[n-1]) {
    writeln (-1);
  } else {
    writefln ("%(%s %)", a);
  }
}

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

void main()
{
    uint n;
    scanf("%ud", &n);
    int[] a = new int[2 * n];
    for (int i = 0; i < 2 * n; i++)
    {
        scanf("%d", &a[i]);
    }

    sort(a);

    auto t1 = sum(a[0 .. n]);
    auto t2 = sum(a[n .. 2 * n]);
    if (t1 == t2)
        writeln(-1);
    else
        writefln("%(%d %)", a);
}

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
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 N = RD!int;
	auto A = RDR.ARR;
	A.sort();
	long sum1, sum2;
	foreach (i; 0..N*2)
	{
		if (i < N)
			sum1 += A[i];
		else
			sum2 += A[i];
	}

	if (sum1 == sum2)
		writeln(-1);
	else
		A.map!(to!string).join(" ").writeln;
	stdout.flush();
	debug readln();
}


You are given an array $$$a_1, a_2, \dots, a_n$$$, consisting of $$$n$$$ integers. You are also given an integer value $$$x$$$.Let $$$f(k)$$$ be the maximum sum of a contiguous subarray of $$$a$$$ after applying the following operation: add $$$x$$$ to the elements on exactly $$$k$$$ distinct positions. An empty subarray should also be considered, it has sum $$$0$$$.Note that the subarray doesn't have to include all of the increased elements.Calculate the maximum value of $$$f(k)$$$ for all $$$k$$$ from $$$0$$$ to $$$n$$$ independently.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of testcases. The first line of the testcase contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 5000$$$; $$$0 \le x \le 10^5$$$) — the number of elements in the array and the value to add. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^5 \le a_i \le 10^5$$$). The sum of $$$n$$$ over all testcases doesn't exceed $$$5000$$$.

For each testcase, print $$$n + 1$$$ integers — the maximum value of $$$f(k)$$$ for all $$$k$$$ from $$$0$$$ to $$$n$$$ independently.

NoteIn the first testcase, it doesn't matter which elements you add $$$x$$$ to. The subarray with the maximum sum will always be the entire array. If you increase $$$k$$$ elements by $$$x$$$, $$$k \cdot x$$$ will be added to the sum.In the second testcase:   For $$$k = 0$$$, the empty subarray is the best option.  For $$$k = 1$$$, it's optimal to increase the element at position $$$3$$$. The best sum becomes $$$-1 + 5 = 4$$$ for a subarray $$$[3, 3]$$$.  For $$$k = 2$$$, it's optimal to increase the element at position $$$3$$$ and any other element. The best sum is still $$$4$$$ for a subarray $$$[3, 3]$$$.  For $$$k = 3$$$, you have to increase all elements. The best sum becomes $$$(-2 + 5) + (-7 + 5) + (-1 + 5) = 5$$$ for a subarray $$$[1, 3]$$$.

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto X = scan!long;
      auto A = scan!long(N);

      const maxNum = A.maxElement;

      alias Term = Tuple!(int, "l", int, "r");
      auto acc = new long[](N + 1);
      foreach(i, a; A) acc[i + 1] = acc[i] + a;

      auto ans = new long[](N + 1);
      ans[] = int.min;
      foreach_reverse(k; 0..N + 1) {
        if (k < N) ans[k] = ans[k + 1];
        foreach(l; 0..N + 1 - k) {
          ans[k].chmax(acc[l + k] - acc[l]);
        }
      }

      foreach(i; 1..N + 1) {
        ans[i] = max(ans[i] + i * X, ans[i - 1]);
      }

      return ans.toAnswerString;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto X = scan!long;
      auto A = scan!long(N);

      const maxNum = A.maxElement;

      alias Term = Tuple!(int, "l", int, "r");
      auto acc = new long[](N + 1);
      foreach(i, a; A) acc[i + 1] = acc[i] + a;

      long maxi = long.min;
      int maxLen;
      foreach(l; 0..N) foreach(r; l + 1..N + 1) {
        if (maxi.chmax(acc[r] - acc[l])) maxLen = r - l;
      }

      auto ans = new long[](N + 1);
      foreach(k; 0..N + 1) {
        if (k > 0) ans[k] = ans[k - 1];
        foreach(l; 0..N + 1 - k) {
          if (maxLen >= k) ans[k].chmax(maxi + k*X); else ans[k].chmax(acc[l + k] - acc[l] + k*X);
        }
      }

      return ans.toAnswerString;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto X = scan!long;
      auto A = scan!long(N);

      const maxNum = A.maxElement;

      alias Term = Tuple!(int, "l", int, "r");
      auto acc = new long[](N + 1);
      foreach(i, a; A) acc[i + 1] = acc[i] + a;

      long maxi;
      int maxLen;
      foreach(l; 0..N) foreach(r; l + 1..N + 1) {
        if (maxi.chmax(acc[r] - acc[l])) maxLen = r - l;
      }
      maxi.deb;

      auto ans = new long[](N + 1);
      foreach(k; 0..N + 1) {
        if (k > 0) ans[k] = ans[k - 1];
        foreach(l; 0..N + 1 - k) {
          if (maxLen >= k) ans[k] = maxi + k*X; else ans[k].chmax(acc[l + k] - acc[l] + k*X);
        }
      }

      return ans.toAnswerString;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;
      auto X = scan!long;
      auto A = scan!long(N);

      const maxNum = A.maxElement;

      alias Term = Tuple!(int, "l", int, "r");
      auto acc = new long[](N + 1);
      foreach(i, a; A) acc[i + 1] = acc[i] + a;

      Term[][long] terms;
      long maxSum = long.min;
      foreach(l; 0..N) foreach(r; l+1..N + 1) {
        const s = acc[r] - acc[l];
        if (maxSum.chmax(s)) {
          terms.clear;
          terms[s] ~= Term(l, r);
        } else if (maxSum == s) {
          terms[s] ~= Term(l, r);
        }
      }

      auto ans = new long[](N + 1);
      foreach(term; terms[maxSum]) {
        long s = maxSum;
        ans[0].chmax(s);

        const mid = term.r - term.l;
        foreach(i; 0..mid) {
          s += X;
          ans[i + 1].chmax(s);
        }

        int l = term.l;
        int r = term.r;
        foreach(i; mid..N) {
          if (r == N || (l > 0 && A[l - 1] > A[r])) {
            s += X;
            s += A[--l];
          } else {
            s += X;
            s += A[r++];
          }
          ans[i + 1] = max(ans[i + 1], s);
        }
      }

      foreach(i; 0..N) ans[i + 1] = max(ans[i], ans[i + 1]);
      return ans.toAnswerString;
    }

    foreach(i; 0..QN) {
      subSolve().writeln;
    }
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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


The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size.During the registration, the organizers asked each of the n participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him.Write a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size:   the size he wanted, if he specified one size;  any of the two neibouring sizes, if he specified two sizes. If it is possible, the program should find any valid distribution of the t-shirts.

The first line of the input contains six non-negative integers — the number of t-shirts of each size. The numbers are given for the sizes S, M, L, XL, XXL, XXXL, respectively. The total number of t-shirts doesn't exceed 100 000. The second line contains positive integer n (1 ≤ n ≤ 100 000) — the number of participants. The following n lines contain the sizes specified by the participants, one line per participant. The i-th line contains information provided by the i-th participant: single size or two sizes separated by comma (without any spaces). If there are two sizes, the sizes are written in increasing order. It is guaranteed that two sizes separated by comma are neighboring.

If it is not possible to present a t-shirt to each participant, print «NO» (without quotes). Otherwise, print n + 1 lines. In the first line print «YES» (without quotes). In the following n lines print the t-shirt sizes the orginizers should give to participants, one per line. The order of the participants should be the same as in the input. If there are multiple solutions, print any of them.

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

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

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

    int[string] mp;
    mp["S"] = 0;
    mp["M"] = 1;
    mp["L"] = 2;
    mp["XL"] = 3;
    mp["XXL"] = 4;
    mp["XXXL"] = 5;

    string[int] mp2;
    mp2[0] = "S";
    mp2[1] = "M";
    mp2[2] = "L";
    mp2[3] = "XL";
    mp2[4] = "XXL";
    mp2[5] = "XXXL";

    auto opts = new int[][] (5);
    auto ans = new int[] (n);
    foreach (i; 0 .. n) {
        auto szs = readln.chomp.split(",");
        auto ids = szs.map!(x => mp[x]).array;
        if (ids.length == 1) {
            if (arr[ids[0]] == 0) {
                writeln("NO");
                return;
            }

            ans[i] = ids[0];
            arr[ids[0]] -= 1;
        } else {
            opts[ids[0]] ~= i;
        }
    }

    foreach (i, rw; opts) {
        int p = i.to!int;
        foreach (e; rw) {
            if (arr[p] == 0) {
                if (p == i && arr[p+1] > 0) { p += 1; }
                else {
                    writeln("NO");
                    return;
                }
            }

            ans[e] = p;
            --arr[p];
        }
    }

    writeln("YES");
    ans.map!(x => mp2[x]).each!writeln;
}

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

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

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

    int[string] mp;
    mp["S"] = 0;
    mp["M"] = 1;
    mp["L"] = 2;
    mp["XL"] = 3;
    mp["XXL"] = 4;
    mp["XXXL"] = 5;

    string[int] mp2;
    mp2[0] = "S";
    mp2[1] = "M";
    mp2[2] = "L";
    mp2[3] = "XL";
    mp2[4] = "XXL";
    mp2[5] = "XXXL";

    auto opts = new int[][] (5);
    auto ans = new int[] (n);
    foreach (i; 0 .. n) {
        auto szs = readln.chomp.split(",");
        auto ids = szs.map!(x => mp[x]).array;
        if (ids.length == 1) {
            if (arr[ids[0]] == 0) {
                writeln("NO");
                return;
            }

            ans[i] = ids[0];
            arr[ids[0]] -= 1;
        } else {
            opts[ids[0]] ~= i;
        }
    }

    foreach (i, rw; opts) {
        int p = i.to!int;
        foreach (e; rw) {
            if (arr[p] == 0) {
                if (p == i) { p += 1; }
                else {
                    writeln("NO");
                    return;
                }
            }

            ans[e] = p;
            --arr[p];
        }
    }

    writeln("YES");
    ans.map!(x => mp2[x]).each!writeln;
}


Recently Monocarp got a job. His working day lasts exactly $$$m$$$ minutes. During work, Monocarp wants to drink coffee at certain moments: there are $$$n$$$ minutes $$$a_1, a_2, \dots, a_n$$$, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute). However, Monocarp's boss doesn't like when Monocarp takes his coffee breaks too often. So for the given coffee break that is going to be on minute $$$a_i$$$, Monocarp must choose the day in which he will drink coffee during the said minute, so that every day at least $$$d$$$ minutes pass between any two coffee breaks. Monocarp also wants to take these $$$n$$$ coffee breaks in a minimum possible number of working days (he doesn't count days when he is not at work, and he doesn't take coffee breaks on such days). Take into account that more than $$$d$$$ minutes pass between the end of any working day and the start of the following working day.For each of the $$$n$$$ given minutes determine the day, during which Monocarp should take a coffee break in this minute. You have to minimize the number of days spent.

The first line contains three integers $$$n$$$, $$$m$$$, $$$d$$$ $$$(1 \le n \le 2\cdot10^{5}, n \le m \le 10^{9}, 1 \le d \le m)$$$ — the number of coffee breaks Monocarp wants to have, the length of each working day, and the minimum number of minutes between any two consecutive coffee breaks. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le m)$$$, where $$$a_i$$$ is some minute when Monocarp wants to have a coffee break.

In the first line, write the minimum number of days required to make a coffee break in each of the $$$n$$$ given minutes.  In the second line, print $$$n$$$ space separated integers. The $$$i$$$-th of integers should be the index of the day during which Monocarp should have a coffee break at minute $$$a_i$$$. Days are numbered from $$$1$$$. If there are multiple optimal solutions, you may print any of them.

NoteIn the first example, Monocarp can take two coffee breaks during the first day (during minutes $$$1$$$ and $$$5$$$, $$$3$$$ minutes will pass between these breaks). One break during the second day (at minute $$$2$$$), and one break during the third day (at minute $$$3$$$).In the second example, Monocarp can determine the day of the break as follows: if the minute when he wants to take a break is odd, then this break is on the first day, if it is even, then this break is on the second day.

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;

void main() {
    auto s = readln.split;
    auto N = s[0].to!int;
    auto M = s[1].to!long;
    auto D = s[2].to!long;
    auto A = readln.split.map!(to!long).array;

    auto rbt = new RedBlackTree!(Tuple!(long, int))();
    foreach (i; 0..N) rbt.insert(tuple(A[i], i));

    auto ans = new int[](N);

    for (int i = 1; !rbt.empty; ++i) {
        long x = rbt.front[0];
        ans[rbt.front[1]] = i;
        rbt.removeFront;
        auto ub = rbt.upperBound(tuple(x+D+1, -1));
        while (!ub.empty) {
            auto t = ub.front;
            x = t[0];
            ans[t[1]] = i;
            rbt.removeKey(t);
            ub = rbt.upperBound(tuple(t[0]+D+1, -1));
        }
    }

    ans.reduce!max.writeln;
    ans.map!(to!string).join(" ").writeln;
}


Note that the memory limit is unusual.You are given a multiset consisting of $$$n$$$ integers. You have to process queries of two types:  add integer $$$k$$$ into the multiset;  find the $$$k$$$-th order statistics in the multiset and remove it. $$$k$$$-th order statistics in the multiset is the $$$k$$$-th element in the sorted list of all elements of the multiset. For example, if the multiset contains elements $$$1$$$, $$$4$$$, $$$2$$$, $$$1$$$, $$$4$$$, $$$5$$$, $$$7$$$, and $$$k = 3$$$, then you have to find the $$$3$$$-rd element in $$$[1, 1, 2, 4, 4, 5, 7]$$$, which is $$$2$$$. If you try to delete an element which occurs multiple times in the multiset, only one occurence is removed. After processing all queries, print any number belonging to the multiset, or say that it is empty.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^6$$$) — the number of elements in the initial multiset and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_1 \le a_2 \le \dots \le a_n \le n$$$) — the elements of the multiset. The third line contains $$$q$$$ integers $$$k_1$$$, $$$k_2$$$, ..., $$$k_q$$$, each representing a query:    if $$$1 \le k_i \le n$$$, then the $$$i$$$-th query is "insert $$$k_i$$$ into the multiset";  if $$$k_i < 0$$$, then the $$$i$$$-th query is "remove the $$$|k_i|$$$-th order statistics from the multiset". For this query, it is guaranteed that $$$|k_i|$$$ is not greater than the size of the multiset.

If the multiset is empty after all queries, print $$$0$$$. Otherwise, print any integer that belongs to the resulting multiset.

NoteIn the first example, all elements of the multiset are deleted.In the second example, the elements $$$5$$$, $$$1$$$, $$$4$$$, $$$2$$$ are deleted (they are listed in chronological order of their removal).In the third example, $$$6$$$ is not the only answer.

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

struct BITree(alias _fun, alias E, T)
if (is(typeof(E) : T))
{
    import std.functional : binaryFun;
    alias OP = binaryFun!_fun;

    ///
    this(size_t n, T[] ts) {
        this.n = n;
        this.tree.length = n+1;
        foreach (ref e; this.tree) e = E;
        foreach (i, t; ts) this.update(i, t);
    }

    void update(size_t i, T e) {
        i += 1;
        while (i <= this.n) {
            this.tree[i] = OP(this.tree[i], e);
            i += i & -i;
        }
    }

    ///
    T query(size_t i) {
        auto r = E;
        while (i > 0) {
            r = OP(r, this.tree[i]);
            i -= i & -i;
        }
        return r;
    }

private:
    size_t n;
    T[] tree;
}

auto bitree(alias fun, alias init, T)(size_t n, T[] ts = [])
{
    return BITree!(fun, init, T)(n, ts);
}

///
auto bitree(alias fun, alias init, T)(T[] ts)
{
    return BITree!(fun, init, T)(ts.length, ts);
}

auto sum_bitree(T)(size_t n, T[] ts = [])
{
    return bitree!("a + b", 0, T)(n, ts);
}

auto sum_bitree(T)(T[] ts)
{
    return sum_bitree!T(ts.length, ts);
}

void main()
{
    auto nq = readln.split.to!(int[]);
    auto N = nq[0];
    auto Q = nq[1];
    auto bit = sum_bitree!int(N+1);
    foreach (_; 0..N) {
        int a;
        readf(" %d", &a);
        bit.update(a, 1);
    }
    foreach (_; 0..Q) {
        int q;
        readf(" %d", &q);
        if (q < 0) {
            q = -q;
            size_t l = 1, r = N+1;
            while (l+1 < r) {
                auto m = (l+r)/2;
                if (bit.query(m) < q) {
                    l = m;
                } else {
                    r = m;
                }
            }
            bit.update(l, -1);
        } else {
            bit.update(q, 1);
        }
    }
    foreach (i; 1..N+1) if (bit.query(i+1) > 0) {
        writeln(i);
        return;
    }
    writeln(0);
}

import std.stdio;

immutable int limit = (1 << 20) + 1;
int [limit] t;

void add (int v, int delta = 1)
{
	for ( ; v < limit; v += v & -v)
	{
		t[v] += delta;
	}
}

int pop (int k)
{
	int pos = limit >> 1;
	for (int x = limit >> 2; x > 0; x >>= 1)
	{
		if (k > t[pos])
		{
			k -= t[pos];
			pos += x;
		}
		else
		{
			pos -= x;
		}
	}
	pos += (k > t[pos]);
	add (pos, -1);
	return pos;
}

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		t[] = 0;

		foreach (i; 0..n)
		{
			int v;
			readf !(" %s") (v);
			add (v);
		}

		foreach (j; 0..m)
		{
			int k;
			readf !(" %s") (k);
			if (k > 0)
			{
				add (k);
			}
			else
			{
				pop (-k);
			}
		}

		auto res = pop (1);
		writeln (t[res] >= 0 ? res : 0);
	}
}

import std.stdio;
immutable int z = 1 << 20;
int [z] t;
void a (int v, int d = 1) {
	for ( ; v < z; v += v & -v) t[v] += d;
}
int p (int k) {
	int v = z >> 1;
	for (int b = z >> 2; b > 0; b >>= 1)
		if (k > t[v]) k -= t[v], v += b;
		else v -= b;
	v += (k > t[v]);
	a (v, -1);
	return v;
}
void main () {
	int n, m, x, r;
	readf !(" %d %d") (n, m);
	foreach (i; 0..n) readf !(" %d") (x), a (x);
	foreach (j; 0..m) {
		readf !(" %d") (x);
		if (x > 0) a (x);
		else p (-x);
	}
	r = p (1);
	writeln (r < z ? r : 0);
}

import std.stdio;

immutable int limit = 1 << 20;
__gshared int [limit] t;

void add (int v, int delta = 1)
{
	for ( ; v < limit; v += v & -v)
	{
		t[v] += delta;
	}
}

int pop (int k)
{
	int pos = limit >> 1;
	for (int x = limit >> 2; x > 0; x >>= 1)
	{
		if (k > t[pos])
		{
			k -= t[pos];
			pos += x;
		}
		else
		{
			pos -= x;
		}
	}
	pos += (k > t[pos]);
	add (pos, -1);
	return pos;
}

void main ()
{
	int n, m, v, k;
	while (readf !(" %s %s") (n, m) > 0)
	{
		t[] = 0;

		foreach (i; 0..n)
		{
			readf !(" %s") (v);
			add (v);
		}

		foreach (j; 0..m)
		{
			readf !(" %s") (k);
			if (k > 0)
			{
				add (k);
			}
			else
			{
				pop (-k);
			}
		}

		auto res = pop (1);
		writeln (res < limit ? res : 0);
	}
}

import std.stdio;

immutable int limit = 1 << 20;
int [limit] t;

void add (int v, int delta = 1) {
	for ( ; v < limit; v += v & -v) t[v] += delta;
}

int pop (int k) {
	int pos = limit >> 1;
	for (int x = limit >> 2; x > 0; x >>= 1)
		if (k > t[pos]) k -= t[pos], pos += x;
		else pos -= x;
	pos += (k > t[pos]);
	add (pos, -1);
	return pos;
}

void main () {
	int n, m, v, k;
	readf !(" %d %d") (n, m);
	foreach (i; 0..n) readf !(" %d") (v), add (v);
	foreach (j; 0..m) {
		readf !(" %d") (k);
		if (k > 0) add (k);
		else pop (-k);
	}

	auto res = pop (1);
	writeln (res < limit ? res : 0);
}

import std.stdio;

immutable int limit = 1 << 20;
int [limit] t;

void add (int v, int delta = 1)
{
	for ( ; v < limit; v += v & -v)
	{
		t[v] += delta;
	}
}

int pop (int k)
{
	int pos = limit >> 1;
	for (int x = limit >> 2; x > 0; x >>= 1)
	{
		if (k > t[pos])
		{
			k -= t[pos];
			pos += x;
		}
		else
		{
			pos -= x;
		}
	}
	pos += (k > t[pos]);
	add (pos, -1);
	return pos;
}

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		t[] = 0;

		foreach (i; 0..n)
		{
			int v;
			readf !(" %s") (v);
			add (v);
		}

		foreach (j; 0..m)
		{
			int k;
			readf !(" %s") (k);
			if (k > 0)
			{
				add (k);
			}
			else
			{
				pop (-k);
			}
		}

		auto res = pop (1);
		writeln (res < limit ? res : 0);
	}
}

import core.bitop, std.stdio;

void main ()
{
	int n, m;
	while (readf !(" %s %s") (n, m) > 0)
	{
		auto z = 1 << bsr (n);
		auto t = new int [z * 2 + 1];

		void add (int v, int delta = 1)
		{
			for ( ; v <= z * 2; v += v & -v)
			{
				t[v] += delta;
			}
		}

		int pop (int k)
		{
			int pos = z;
			for (int x = z >> 1; x > 0; x >>= 1)
			{
				if (k > t[pos])
				{
					k -= t[pos];
					pos += x;
				}
				else
				{
					pos -= x;
				}
			}
			pos += (k > t[pos]);
			add (pos, -1);
			return pos;
		}

		foreach (i; 0..n)
		{
			int v;
			readf !(" %s") (v);
			add (v);
		}

		foreach (j; 0..m)
		{
			int k;
			readf !(" %s") (k);
			if (k > 0)
			{
				add (k);
			}
			else
			{
				pop (-k);
			}
		}

		auto res = pop (1);
		writeln (t[res] >= 0 ? res : 0);
	}
}

import std.stdio;

immutable int limit = 1 << 20;
__gshared int [limit] t;

void add (int v, int delta = 1)
{
	for ( ; v < limit; v += v & -v)
	{
		t[v] += delta;
	}
}

int pop (int k)
{
	int pos = limit >> 1;
	for (int x = limit >> 2; x > 0; x >>= 1)
	{
		if (k > t[pos])
		{
			k -= t[pos];
			pos += x;
		}
		else
		{
			pos -= x;
		}
	}
	pos += (k > t[pos]);
	add (pos, -1);
	return pos;
}

void main ()
{
	int n, m, v, k;
	while (readf !(" %d %d") (n, m) > 0)
	{
		t[] = 0;

		foreach (i; 0..n)
		{
			readf !(" %d") (v);
			add (v);
		}

		foreach (j; 0..m)
		{
			readf !(" %d") (k);
			if (k > 0)
			{
				add (k);
			}
			else
			{
				pop (-k);
			}
		}

		auto res = pop (1);
		writeln (res < limit ? res : 0);
	}
}

import std.stdio;

immutable int limit = 1 << 20;
int [] t;

void add (int v, int delta = 1)
{
	for ( ; v < limit; v += v & -v)
	{
		t[v] += delta;
	}
}

int pop (int k)
{
	int pos = limit >> 1;
	for (int x = limit >> 2; x > 0; x >>= 1)
	{
		if (k > t[pos])
		{
			k -= t[pos];
			pos += x;
		}
		else
		{
			pos -= x;
		}
	}
	pos += (k > t[pos]);
	add (pos, -1);
	return pos;
}

void main ()
{
	t = new int [limit];
	int n, m, v, k;
	while (readf !(" %s %s") (n, m) > 0)
	{
		t[] = 0;

		foreach (i; 0..n)
		{
			readf !(" %s") (v);
			add (v);
		}

		foreach (j; 0..m)
		{
			readf !(" %s") (k);
			if (k > 0)
			{
				add (k);
			}
			else
			{
				pop (-k);
			}
		}

		auto res = pop (1);
		writeln (res < limit ? res : 0);
	}
}


You are given a bracket sequence $$$s$$$ consisting of $$$n$$$ opening '(' and closing ')' brackets.A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.You can change the type of some bracket $$$s_i$$$. It means that if $$$s_i = $$$ ')' then you can change it to '(' and vice versa.Your task is to calculate the number of positions $$$i$$$ such that if you change the type of the $$$i$$$-th bracket, then the resulting bracket sequence becomes regular.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of the bracket sequence. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ opening '(' and closing ')' brackets.

Print one integer — the number of positions $$$i$$$ such that if you change the type of the $$$i$$$-th bracket, then the resulting bracket sequence becomes regular.

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

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

    auto s = readln.chomp.to!(dchar[]).array;

    int lo = 0;
    int b = 0;
    foreach (e; s) {
        if (e == '(') { b += 1; }
        else { b -= 1; }

        lo = min(lo, b);
    }

    if (lo < -2 ||
        abs(b) != 2 ||
        (lo < 0 && b == 2)) {
        writeln(0);
        return;
    }

    if (b == 2) {
        foreach (ref e; s) {
            if (e == '(') { e = ')'; }
            else { e = '('; }
        }

        s.reverse();
    }

    int ans = 0;
    int cb = 0;
    foreach (e; s) {
        if (e == '(') { cb += 1; }
        else { cb -= 1; }

        debug { writeln(cb, ' ', e); }
        if (e == ')') { ans += 1; }

        if (cb < 0) { break; }
    }

    ans.writeln;
}

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

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

    auto s = readln.chomp.to!(dchar[]).array;

    int b = 0;
    foreach (e; s) {
        if (e == '(') { b += 1; }
        else { b -= 1; }

        if (b < -2) {
            writeln(0);
            return;
        }
    }

    if (abs(b) != 2) {
        writeln(0);
        return;
    }

    if (b == 2) {
        foreach (ref e; s) {
            if (e == '(') { e = ')'; }
            else { e = '('; }
        }

        s.reverse();
    }

    int ans = 0;
    int cb = 0;
    foreach (e; s) {
        if (e == '(') { cb += 1; }
        else { cb -= 1; }

        debug { writeln(cb, ' ', e); }
        if (e == ')') { ans += 1; }

        if (cb < 0) { break; }
    }

    ans.writeln;
}


Marmot found a row with n pillars. The i-th pillar has the height of hi meters. Starting from one pillar i1, Marmot wants to jump on the pillars i2, ..., ik. (1 ≤ i1 < i2 < ... < ik ≤ n). From a pillar i Marmot can jump on a pillar j only if i < j and |hi - hj| ≥ d, where |x| is the absolute value of the number x.Now Marmot is asking you find out a jump sequence with maximal length and print it.

The first line contains two integers n and d (1 ≤ n ≤ 105, 0 ≤ d ≤ 109). The second line contains n numbers h1, h2, ..., hn (1 ≤ hi ≤ 1015).

The first line should contain one integer k, the maximal length of a jump sequence. The second line should contain k integers i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n), representing the pillars' indices from the maximal length jump sequence. If there is more than one maximal length jump sequence, print any.

NoteIn the first example Marmot chooses the pillars 1, 2, 3, 5 with the heights 1, 3, 6, 4. Another jump sequence of length 4 is 1, 2, 4, 5.

import std.stdio;
import std.exception;
import std.algorithm;
import std.range;
import std.random;

void main() { while (solve()) {} }

struct pt {
	int val;
	int pos;
	auto opCmp(pt other) {
		if (this.val != other.val)
			return this.val - other.val;
		return this.pos - other.pos;
	}
}

class tree {
	long key;
	int prior;
	pt val, mx;
	tree l, r;
	this(long key) {
		this.key = key;
		this.prior = uniform!int;
		this.val = this.mx = pt.init;
		l = r = null;
	}
};

void update(tree t) {
	if (!t) return;
	t.mx = t.val;
	if (t.l) t.mx = max(t.mx, t.l.mx);
	if (t.r) t.mx = max(t.mx, t.r.mx);
}

tree merge(tree a, tree b) {
	if (!a) return b;
	if (!b) return a;
	tree t;
	if (a.prior > b.prior) {
		a.r = merge(a.r, b);
		t = a;
	} else {
		b.l = merge(a, b.l);
		t = b;
	}
	update(t);
	return t;
}

void split(tree t, long key, ref tree l, ref tree r) {
	if (!t) {
		l = r = null;
		return;
	}

	if (t.key >= key) {
		split(t.l, key, l, t.l);
		r = t;
	} else {
		split(t.r, key, t.r, r);
		l = t;
	}
	update(l);
	update(r);
}

bool solve() {
	size_t n;
	long d;
	if (!readf(" %s %s", &n, &d)) return false;
	if (d == 0) {
		foreach (i; 0..n) enforce(readf(" %s", &d));
		writeln(n);
		foreach (i; 0..n) {
			if (i > 0) write(' ');
			write(i + 1);
		}
		writeln;
		return true;
	}
	tree root;

	auto p = new int[n];
	int ans = -1, pos;

	foreach (i; 0..n) {
		long x;
		enforce(readf(" %s", &x));
		tree l, mid, r;
		split(root, x + d, l, r);
		split(l, x - d + 1, l, mid);
		pt curVal = pt(1, -1);
		if (l) curVal = max(curVal, pt(1 + l.mx.val, l.mx.pos));
		if (r) curVal = max(curVal, pt(1 + r.mx.val, r.mx.pos));
		root = merge(l, merge(mid, r));

		split(root, x, l, r);
		split(r, x + 1, mid, r);

		if (curVal.val > ans) {
			ans = curVal.val;
			pos = cast(int)i;
		}
		p[i] = curVal.pos;

		curVal.pos = cast(int)i;
		if (!mid) mid = new tree(x);
		else curVal = max(curVal, mid.val);

		mid.val = mid.mx = curVal;
		root = merge(l, merge(mid, r));

		//writefln("%s %s %s", i, curVal.val, curVal.pos);
	}
	writeln(ans);
	int[] ansv;
	foreach (i; 0..ans) {
		//writeln("pos = ", pos);
		ansv ~= pos;
		pos = p[pos];
	}
	ansv.reverse;
	foreach(i, x; ansv) {
		if (i > 0) write(' ');
		write(x + 1);
	}
	writeln;
	return true;
}

import std.stdio;
import std.exception;
import std.algorithm;
import std.range;
import std.random;

void main() { while (solve()) {} }

struct pt {
	int val;
	int pos;
	auto opCmp(pt other) {
		if (this.val != other.val)
			return this.val - other.val;
		return this.pos - other.pos;
	}
}

class tree {
	long key;
	int prior;
	pt val, mx;
	tree l, r;
	this(long key) {
		this.key = key;
		this.prior = uniform!int;
		this.val = this.mx = pt.init;
		l = r = null;
	}
};

void update(tree t) {
	if (!t) return;
	t.mx = t.val;
	if (t.l) t.mx = max(t.mx, t.l.mx);
	if (t.r) t.mx = max(t.mx, t.r.mx);
}

tree merge(tree a, tree b) {
	if (!a) return b;
	if (!b) return a;
	tree t;
	if (a.prior > b.prior) {
		a.r = merge(a.r, b);
		t = a;
	} else {
		b.l = merge(a, b.l);
		t = b;
	}
	update(t);
	return t;
}

void split(tree t, long key, ref tree l, ref tree r) {
	if (!t) {
		l = r = null;
		return;
	}

	if (t.key >= key) {
		split(t.l, key, l, t.l);
		r = t;
	} else {
		split(t.r, key, t.r, r);
		l = t;
	}
	update(l);
	update(r);
}

bool solve() {
	size_t n;
	long d;
	if (!readf(" %s %s", &n, &d)) return false;
	tree root;

	auto p = new int[n];
	int ans = -1, pos;

	foreach (i; 0..n) {
		long x;
		enforce(readf(" %s", &x));
		tree l, mid, r;
		split(root, x + d, l, r);
		split(l, x - d + 1, l, mid);
		pt curVal = pt(1, cast(int)i);
		if (l) curVal = max(curVal, pt(1 + l.mx.val, l.mx.pos));
		if (r) curVal = max(curVal, pt(1 + r.mx.val, r.mx.pos));
		root = merge(l, merge(mid, r));

		split(root, x, l, r);
		split(r, x + 1, mid, r);
		if (!mid) mid = new tree(x);
		else curVal = max(curVal, mid.val);
		auto myVal = curVal;
		myVal.pos = cast(int)i;
		mid.val = mid.mx = myVal;
		root = merge(l, merge(mid, r));

		//writefln("%s %s %s", i, curVal.val, curVal.pos);

		if (curVal.val > ans) {
			ans = curVal.val;
			pos = cast(int)i;
		}
		p[i] = curVal.pos;
	}
	writeln(ans);
	int[] ansv;
	foreach (i; 0..ans) {
		//writeln("pos = ", pos);
		ansv ~= pos;
		pos = p[pos];
	}
	ansv.reverse;
	foreach(i, x; ansv) {
		if (i > 0) write(' ');
		write(x + 1);
	}
	writeln;
	return true;
}


A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person.You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of $$$n$$$ ($$$n \ge 3$$$) positive distinct integers (i.e. different, no duplicates are allowed).Find the largest subset (i.e. having the maximum number of elements) of this array such that its sum is a composite number. A positive integer $$$x$$$ is called composite if there exists a positive integer $$$y$$$ such that $$$1 < y < x$$$ and $$$x$$$ is divisible by $$$y$$$.If there are multiple subsets with this largest size with the composite sum, you can output any of them. It can be proven that under the constraints of the problem such a non-empty subset always exists.

Each test consists of multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 \leq n \leq 100$$$) — the length of the array. The second line of each test case contains $$$n$$$ distinct integers $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$1 \leq a_{i} \leq 200$$$) — the elements of the array.

Each test case should have two lines of output. The first line should contain a single integer $$$x$$$: the size of the largest subset with composite sum. The next line should contain $$$x$$$ space separated integers representing the indices of the subset of the initial array.

NoteIn the first test case, the subset $$$\{a_2, a_1\}$$$ has a sum of $$$9$$$, which is a composite number. The only subset of size $$$3$$$ has a prime sum equal to $$$11$$$. Note that you could also have selected the subset $$$\{a_1, a_3\}$$$ with sum $$$8 + 2 = 10$$$, which is composite as it's divisible by $$$2$$$.In the second test case, the sum of all elements equals to $$$21$$$, which is a composite number. Here we simply take the whole array as our subset.

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	bool isPrime(long m)
	{
		for (long d = 2; d * d <= m; d++)
		{
			if (m % d == 0) return false;
		}
		return true;
	}
	long total = a.sum;
	if (isPrime(total))
	{
		writeln(n-1);
		int exclude = -1;
		foreach(i, ai; a)
			if (!isPrime(total - ai))
			{
				exclude = cast(int)i;
				break;
			}
		assert(exclude != -1);
		foreach(i; 1 .. n + 1)
			if (i != exclude + 1)
				write(i, " ");
		writeln;
	}
	else
	{
		writeln(n);
		foreach(i; 1 .. n + 1)
			write(i, " ");
		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;
// }}}


You are given a long decimal number $$$a$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$. You also have a function $$$f$$$ that maps every digit from $$$1$$$ to $$$9$$$ to some (possibly the same) digit from $$$1$$$ to $$$9$$$.You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in $$$a$$$, and replace each digit $$$x$$$ from this segment with $$$f(x)$$$. For example, if $$$a = 1337$$$, $$$f(1) = 1$$$, $$$f(3) = 5$$$, $$$f(7) = 3$$$, and you choose the segment consisting of three rightmost digits, you get $$$1553$$$ as the result.What is the maximum possible number you can obtain applying this operation no more than once?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of digits in $$$a$$$. The second line contains a string of $$$n$$$ characters, denoting the number $$$a$$$. Each character is a decimal digit from $$$1$$$ to $$$9$$$. The third line contains exactly $$$9$$$ integers $$$f(1)$$$, $$$f(2)$$$, ..., $$$f(9)$$$ ($$$1 \le f(i) \le 9$$$).

Print the maximum number you can get after applying the operation described in the statement no more than once.

// https://codeforces.com/problemset/problem/1157/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

    string a = readln.chomp;

    int[] f = [-1];
    f ~= readln.split.map!(to!int).array;

    int idx = 0;
    while(idx < n && f[a[idx]-'0'] <= a[idx]-'0') {
        a[idx].write;
        idx += 1;
    }

    while(idx < n && f[a[idx]-'0'] >= a[idx]-'0') {
        f[a[idx]-'0'].write;
        idx += 1;
    }

    while(idx < n) {
        a[idx].write;
        idx += 1;
    }
    writeln;
}

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 s = readln.strip.map !(x => x - '0').array;
		auto f = 0 ~ readln.splitter.map !(to !(int)).array;
		int pos = 0;
		while (pos < n && f[s[pos]] <= s[pos])
		{
			pos += 1;
		}
		while (pos < n && f[s[pos]] >= s[pos])
		{
			s[pos] = f[s[pos]];
			pos += 1;
		}
		writefln ("%(%s%)", s);
	}
}

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

void solve(){

	int n = read.to!int;
	char[] a = readln.chomp.to!(char[]);

	char[char] y;
	foreach(c; "123456789") y[c] = '0', y[c] += read.to!int.to!char;

	int f = 0;
	foreach(i, c; a){
		if(f == 0){
			if(y[c] <= c) continue;
			else{
				f = 1;
				a[i] = y[c];
			}
		}
		else if(f == 1){
			if(y[c] < c){
				f = 2;
				break;
			}
			else{
				a[i] = y[c];
			}
		}
	}

	a.to!string.writeln;

}

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto N = RD;
	auto s = RD!string;
	auto a = RDR.ARR;

	auto use = new bool[](9);
	foreach (i; 0..9)
	{
		if (a[i] > i+1) use[i] = true;
	}
	debug writeln(use);

	string ans;
	long mode;
	foreach (c; s)
	{
		uint x = c - '0';
		if (mode == 0 && a[x-1] > x)
		{
			ans ~= to!string(a[x-1]);
			mode = 1;
		}
		else if (mode == 1 && a[x-1] >= x)
		{
			ans ~= to!string(a[x-1]);
		}
		else
		{
			ans ~= c;
			if (mode == 1)
				mode = 2;
		}
	}

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

// https://codeforces.com/problemset/problem/1157/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

    string a = readln.chomp;

    int[] f = [-1];
    f ~= readln.split.map!(to!int).array;

    bool change = true;
    foreach(ch; a) {
        int digit = ch-'0';
        if(f[digit] < digit)
            change = false;
        if(f[digit] > digit && change)
            f[digit].write;
        else
            digit.write;
    } writeln;
}

// https://codeforces.com/problemset/problem/1157/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

    string a = readln.chomp;

    int[] f = [-1];
    f ~= readln.split.map!(to!int).array;

    foreach(ch; a) {
        int digit = ch-'0';
        if(f[digit] > digit)
            f[digit].write;
        else
            digit.write;
    } writeln;
}

// https://codeforces.com/problemset/problem/1157/B
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

    string a = readln.chomp;

    int[] f = [-1];
    f ~= readln.split.map!(to!int).array;

    int idx = 0;
    while(idx < n && f[idx] <= a[idx]) {
        a[idx].write;
        idx += 1;
    }

    while(idx < n && f[idx] >= a[idx]) {
        f[idx].write;
        idx += 1;
    }

    while(idx < n) {
        a[idx].write;
        idx += 1;
    }
    writeln;
}

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto N = RD;
	auto s = RD!string;
	auto a = RDR.ARR;

	auto use = new bool[](9);
	foreach (i; 0..9)
	{
		if (a[i] > i) use[i] = true;
	}

	string ans;
	foreach (i, c; s)
	{
		uint x = c - '0';
		if (use[x-1])
			ans ~= to!string(a[x-1]);
		else
			ans ~= c;
	}

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

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto N = RD;
	auto s = RD!string;
	auto a = RDR.ARR;

	auto use = new bool[](9);
	foreach (i; 0..9)
	{
		if (a[i] > i+1) use[i] = true;
	}
	debug writeln(use);

	string ans;
	long mode;
	foreach (c; s)
	{
		uint x = c - '0';
		if (mode == 0 && a[x-1] > x)
		{
			ans ~= to!string(a[x-1]);
			mode = 1;
		}
		if (mode == 1 && a[x-1] >= x)
		{
			ans ~= to!string(a[x-1]);
		}
		else
		{
			ans ~= c;
			if (mode == 1)
				mode = 2;
		}
	}

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

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto N = RD;
	auto s = RD!string;
	auto a = RDR.ARR;

	auto use = new bool[](9);
	foreach (i; 0..9)
	{
		if (a[i] > i) use[i] = true;
	}

	long ans;
	foreach (i, c; s)
	{
		long d = s.length - i - 1;
		uint x = c - '0';
		if (use[x-1])
			ans += a[x-1] * (10^^d);
		else
			ans += x * (10^^d);
	}

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

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

string FMT_F = "%.10f";

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

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto N = RD;
	auto s = RD!string;
	auto a = RDR.ARR;

	auto use = new bool[](9);
	foreach (i; 0..9)
	{
		if (a[i] > i+1) use[i] = true;
	}
	debug writeln(use);

	string ans;
	long mode;
	foreach (c; s)
	{
		uint x = c - '0';
		if ((mode == 0 || mode == 1) && use[x-1])
		{
			ans ~= to!string(a[x-1]);
			mode = 1;
		}
		else
		{
			ans ~= c;
			if (mode == 1)
				mode = 2;
		}
	}

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


One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?

The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).

If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.

//Да, я упоролся решать эту задачу Splay-деревом)
import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

struct Node {
    int value, firstValue, lastValue;
    bool sorted = true;
    Splay left, right, parent;

    invariant {
        assert(firstValue == (left !is null ? left.firstValue : value));
        assert(lastValue == (right !is null ? right.lastValue : value));
        assert(sorted == (
            left.sorted && right.sorted &&
            value >= (left !is null ? left.lastValue : value) &&
            value <= (right !is null ? right.firstValue : value)
        ));
    }

    enum { L, R }

    this(int x) {
        value = firstValue = lastValue = x;
    }

    Splay splayLeft() return
    out (result) {
        assert(result.parent is null);
        assert(result.left is null);
    }
    body {
        if (left !is null)
            return left.splayLeft();
        splay();
        return Splay(&this);
    }

    Splay splayRight() return
    out (result) {
        assert(result.parent is null);
        assert(result.right is null);
    }
    body {
        if (right !is null)
            return right.splayRight();
        splay();
        return Splay(&this);
    }

    void splay()
    out {
        assert(parent is null);
    }
    body {
        while (true) {
            auto parent = parent;
            if (parent is null)
                return;
            if (parent.parent is null) {
                rotate();
                return;
            }
            if (side == parent.side)
                parent.rotate();
            else
                rotate();
            rotate();
        }
    }

    void rotate()
    in {
        assert(parent !is null);
    }
    body {
        auto parent = parent;
        auto gparent = parent.parent;
        auto side = side;
        auto parentSide = gparent !is null ? parent.side : 0;
        unlink();
        parent.unlink();
        if (side == L) {
            if (auto right = right) {
                right.unlink();
                right.link(L, parent);
            }
            parent.link(R, Splay(&this));
        } else {
            if (auto left = left) {
                left.unlink();
                left.link(R, parent);
            }
            parent.link(L, Splay(&this));
        }
        link(parentSide, gparent);
    }

private:
    void recalc() {
        firstValue = left !is null ? left.firstValue : value;
        lastValue = right !is null ? right.lastValue : value;
        sorted = left.sorted && right.sorted;
        if (left !is null)
            sorted &= value >= left.lastValue;
        if (right !is null)
            sorted &= value <= right.firstValue;
    }

    @property int side() const
    in {
        assert(parent !is null);
    }
    body {
        return &this is parent.left ? L : R;
    }

    void link(int c, Splay newParent)
    in {
        assert(parent is null);
        if (newParent !is null)
            assert((c == L ? newParent.left : newParent.right) is null);
    }
    out {
        assert(parent is newParent);
    }
    body {
        if (!newParent)
            return;
        parent = newParent;
        if (c == L)
            newParent.left = &this;
        else
            newParent.right = &this;
        newParent.recalc();
    }

    void unlink()
    out {
        assert(parent is null);
    }
    body {
        if (parent is null)
            return;
        if (side == L)
            parent.left = null;
        else
            parent.right = null;
        parent.recalc();
        parent = null;
    }
}

struct Splay {
    Node* _node;

    alias _node this;

    @property int firstValue() const { return _node !is null ? _node.firstValue : int.min; }
    @property int lastValue() const { return _node !is null ? _node.lastValue : int.max; }
    @property bool sorted() const { return _node !is null ? _node.sorted : true; }

    void append(Splay t) {
        if (_node)
            link(L, t);
        this = t;
    }

    void shift() {
        auto item = splayRight();
        this = item.left;
        unlink();
        this = splayLeft();
        link(R, item);
        this = item;
    }
}

Node[10^^5] _nodes;

void main() {
    int n;
nextCase:
    while (scanf("%d", &n) == 1) {
        version (LocalProject)
            _nodes[ ] = Node.init;
        Splay t;
        foreach (ref node; _nodes[0 .. n]) {
            int x;
            scanf("%d", &x);
            node = Node(x);
            t.append(Splay(&node));
        }

        foreach (i; 0 .. n) {
            if (t.sorted) {
                printf("%d\n", i);
                continue nextCase;
            }
            t.shift();
        }
        puts("-1");
    }
}

import core.thread;
import std.conv, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.math, std.range;

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

//	chmin/chmax
void chmin(T)(ref T t, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int N;
int[] A;

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

		int[] pos;
		foreach (i; 0 .. N) {
			if (A[i] > A[(i + 1) % N]) {
				pos ~= i;
			}
		}

		if (pos.length == 0) {
			writeln(0);
		} else if (pos.length == 1) {
			writeln(N - 1 - pos[0]);
		} else {
			writeln(-1);
		}
	}
	} catch (EOFException) {}
}