We will consider the numbers $$$a$$$ and $$$b$$$ as adjacent if they differ by exactly one, that is, $$$|a-b|=1$$$.We will consider cells of a square matrix $$$n \times n$$$ as adjacent if they have a common side, that is, for cell $$$(r, c)$$$ cells $$$(r, c-1)$$$, $$$(r, c+1)$$$, $$$(r-1, c)$$$ and $$$(r+1, c)$$$ are adjacent to it.For a given number $$$n$$$, construct a square matrix $$$n \times n$$$ such that:   Each integer from $$$1$$$ to $$$n^2$$$ occurs in this matrix exactly once;  If $$$(r_1, c_1)$$$ and $$$(r_2, c_2)$$$ are adjacent cells, then the numbers written in them must not be adjacent.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. Each test case is characterized by one integer $$$n$$$ ($$$1 \le n \le 100$$$).

For each test case, output:    -1, if the required matrix does not exist;  the required matrix, otherwise (any such matrix if many of them exist).  The matrix should be outputted as $$$n$$$ lines, where each line contains $$$n$$$ integers.

// Vicfred
// https://codeforces.com/contest/1520/problem/C
// greedy
import std.stdio;

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

while(t--) {
    int n;
    readf("%s\n", &n);

    if(n == 2) {
        "-1".writeln;
        continue;
    }

    int[][] matrix = new int[][](n,n);
    int i = 1;
    bool flag = false;
    for(int y = 0; y < n; ++y) {
        for(int x = 0; x < n; ++x) {
            if(!flag && i*2 > n*n) {
                flag = true;
                i = 1;
            }
            if(flag) {
                matrix[y][x] = i*2-1;
                i += 1;
            }
            else {
                matrix[y][x] = i*2;
                i+=1;
            }
        }
    }
    for(int k = 0; k < n; k++) {
        for(int j = 0; j < n; j++) {
            writef("%s ", matrix[k][j]);
        } "".writeln;
    }
}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		if (n == 2) continue;

		ans[ti] = new int[][](n, n);
		int num = 1;
		foreach (i; 0..n)
		{
			ans[ti][i][i] = num;
			++num;
		}
		foreach (i; 1..n)
		{
			foreach (j; 0..n-i)
			{
				ans[ti][i+j][j] = num;
				++num;
			}
			foreach (j; 0..n-i)
			{
				ans[ti][j][i+j] = num;
				++num;
			}
		}
	}

	foreach (e; ans)
	{
		if (e.empty)
			writeln(-1);
		else
		{
			foreach (ee; e)
				ee.map!(to!string).join(" ").writeln;
		}
	}
	stdout.flush;
	debug readln;
}


Let there be an array $$$b_1, b_2, \ldots, b_k$$$. Let there be a partition of this array into segments $$$[l_1; r_1], [l_2; r_2], \ldots, [l_c; r_c]$$$, where $$$l_1 = 1$$$, $$$r_c = k$$$, and for any $$$2 \leq i \leq c$$$ holds that $$$r_{i-1} + 1 = l_i$$$. In other words, each element of the array belongs to exactly one segment.Let's define the cost of a partition as $$$$$$c + \sum_{i = 1}^{c} \operatorname{mex}(\{b_{l_i}, b_{l_i + 1}, \ldots, b_{r_i}\}),$$$$$$ where $$$\operatorname{mex}$$$ of a set of numbers $$$S$$$ is the smallest non-negative integer that does not occur in the set $$$S$$$. In other words, the cost of a partition is the number of segments plus the sum of MEX over all segments. Let's define the value of an array $$$b_1, b_2, \ldots, b_k$$$ as the maximum possible cost over all partitions of this array.You are given an array $$$a$$$ of size $$$n$$$. Find the sum of values of all its subsegments.An array $$$x$$$ is a subsegment of an array $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The input contains several test cases. The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 30$$$) — the number of test cases. The first line for each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the length of the array. The second line contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case print a single integer — the answer to the problem.

NoteIn the second test case:   The best partition for the subsegment $$$[2, 0, 1]$$$: $$$[2], [0, 1]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0, 1\}) = 2 + 0 + 2 = 4$$$.  The best partition for the subsegment $$$[2, 0]$$$: $$$[2], [0]$$$. The cost of this partition equals to $$$2 + \operatorname{mex}(\{2\}) + \operatorname{mex}(\{0\}) = 2 + 0 + 1 = 3$$$  The best partition for the subsegment $$$[2]$$$: $$$[2]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{2\}) = 1 + 0 = 1$$$.  The best partition for the subsegment $$$[0, 1]$$$: $$$[0, 1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0, 1\}) = 1 + 2 = 3$$$.  The best partition for the subsegment $$$[0]$$$: $$$[0]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{0\}) = 1 + 1 = 2$$$.  The best partition for the subsegment $$$[1]$$$: $$$[1]$$$. The cost of this partition equals to $$$1 + \operatorname{mex}(\{1\}) = 1 + 0 = 1$$$. The sum of values over all subsegments equals to $$$4 + 3 + 1 + 3 + 2 + 1 = 14$$$.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;

		auto x = new int [] [] (n + 1, n + 1);
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n + 1)
			{
				bool [int] s;
				foreach (k; i..j)
				{
					s[a[k]] = true;
				}
				x[i][j] = 0;
				while (x[i][j] in s)
				{
					x[i][j] += 1;
				}
				x[i][j] += 1;
			}
		}

		auto f = new int [] [] (n + 1, n + 1);
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n + 1)
			{
				f[i][j] = x[i][j];
				foreach (k; i..j)
				{
					f[i][j] = max (f[i][j],
					    f[i][k] + x[k][j]);
				}
			}
		}

		int res = 0;
		foreach (i; 0..n)
		{
			foreach (j; i + 1..n + 1)
			{
				res += f[i][j];
			}
		}
		writeln (res);
	}
}

// cheese-cracker [2022-02-12]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    long summ = 0;
    for(int i = 1; i <= n; ++i){
        summ += i * (n + 1 - i);
    }
    for(int i = 1; i <= n; ++i){
        if(arr[i-1] == 0){
            summ += i * (n + 1 - i);
        }
    }
    writeln(summ);
}

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

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

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

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

		auto cnt = new long[](n+1);
		foreach (i; 0..n)
			cnt[i+1] = cnt[i] + (a[i] == 0 ? 1 : 0);
		foreach (l; 0..n)
		{
			foreach (r; l+1..n+1)
			{
				ans[ti] += r-l + cnt[r]-cnt[l];
			}
		}
	}

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

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

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

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

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

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

        auto mex = new int[][](N + 1, N + 1);
        foreach (i; 0 .. N) {
          bool[int] app;
          foreach (j; i .. N) {
            app[A[j]] = true;
            for (int x = 0; ; ++x) {
              if (x !in app) {
                mex[i][j + 1] = x;
                break;
              }
            }
          }
        }

        auto dp = new int[][](N + 1, N + 1);
        foreach_reverse (i; 0 .. N) foreach (j; i + 1 .. N + 1) {
          dp[i][j] = 1 + mex[i][j];
          foreach (k; i + 1 .. j) {
            chmax(dp[i][j], dp[i][k] + dp[k][j]);
          }
        }
        int ans;
        foreach_reverse (i; 0 .. N) foreach (j; i + 1 .. N + 1) {
          ans += dp[i][j];
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


You are given a tree (connected, undirected, acyclic graph) with $$$n$$$ vertices. Two edges are adjacent if they share exactly one endpoint. In one move you can remove an arbitrary edge, if that edge is adjacent to an even number of remaining edges.Remove all of the edges, or determine that it is impossible. If there are multiple solutions, print any.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. Then $$$n-1$$$ lines follow. The $$$i$$$-th of them contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i,v_i \le n$$$) the endpoints of the $$$i$$$-th edge. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print "NO" if it is impossible to remove all the edges. Otherwise print "YES", and in the next $$$n-1$$$ lines print a possible order of the removed edges. For each edge, print its endpoints in any order.

NoteTest case $$$1$$$: it is possible to remove the edge, because it is not adjacent to any other edge.Test case $$$2$$$: both edges are adjacent to exactly one edge, so it is impossible to remove any of them. So the answer is "NO".Test case $$$3$$$: the edge $$$2-3$$$ is adjacent to two other edges. So it is possible to remove it. After that removal it is possible to remove the remaining edges too.

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

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

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

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

int N;
int[] A, B;

int[][] G;
int[2][] dp;

void dfs(int u, int p) {
  int[] vs;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      vs ~= v;
      dfs(v, u);
    }
  }
  const len = cast(int)(vs.length);
  foreach (s; 0 .. 2) {
    int[2] num;
    num[0] = (len + 1) / 2;
    num[1] = (len + 1) - num[0];
    if (num[s] > 0) {
      --num[s];
      int[2][2] cnt;
      foreach (v; vs) {
        ++cnt[dp[v][0]][dp[v][1]];
      }
      if (cnt[0][0] == 0) {
        if (cnt[1][0] <= num[0] && cnt[0][1] <= num[1]) {
          dp[u][s] = 1;
        }
      }
    }
  }
}

int[][] ans;

void recover(int u, int p, int s) {
  int[] vs;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      vs ~= v;
    }
  }
  const len = cast(int)(vs.length);
  {
    int[2] num;
    num[0] = (len + 1) / 2;
    num[1] = (len + 1) - num[0];
    if (num[s] > 0) {
      --num[s];
      int[][2] vss;
      foreach (v; vs) {
        if (dp[v][0] && !dp[v][1]) vss[0] ~= v;
        if (!dp[v][0] && dp[v][1]) vss[1] ~= v;
      }
      foreach (v; vs) {
        if (dp[v][0] && dp[v][1]) {
          if (vss[0].length < num[0]) {
            vss[0] ~= v;
          } else {
            vss[1] ~= v;
          }
        }
      }
      bool f;
      int[2] itr;
      foreach_reverse (i; 1 .. (len + 1) + 1) {
        if ((i & 1) == s && !f) {
          if (~p) {
            ans ~= [u, p];
          }
          f = true;
        } else {
          const v = vss[i & 1][itr[i & 1]++];
          recover(v, u, i & 1);
        }
      }
    }
  }
}

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

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

        const s0 = (G[0].length + 1) & 1;
        if (dp[0][s0]) {
          ans = [];
          recover(0, -1, s0);
          writeln("YES");
          foreach (e; ans) {
            writeln(e[0] + 1, " ", e[1] + 1);
          }
        } else {
          writeln("NO");
        }
      }
    }
  } catch (EOFException e) {
  }
}


You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation $$$a$$$.

For each test case, output a single integer — the minimum number of operations described above to sort the array $$$a$$$ in ascending order.

NoteIn the explanations, $$$a[i, j]$$$ defines the subarray of $$$a$$$ that starts from the $$$i$$$-th element and ends with the $$$j$$$-th element.In the first test case of the example, you can select the subarray $$$a[2, 3]$$$ and swap the elements in it.In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.In the third test case of the example, you can select the subarray $$$a[3, 5]$$$ and reorder the elements in it so $$$a$$$ becomes $$$[2, 1, 3, 4, 5]$$$, and then select the subarray $$$a[1, 2]$$$ and swap the elements in it, so $$$a$$$ becomes $$$[1, 2, 3, 4, 5]$$$.

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.numeric;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln().chomp.to!int;
        auto arr = readln().chomp.splitter(" ").map!(to!int).array;
        auto sorted = arr.array.sort;

        if(arr.equal(sorted))
            writeln(0);
        else if(arr[0] == 1 || arr[arr.length-1] == arr.length)
            writeln(1);
        else if(arr[0] != arr.length || arr[arr.length-1] != 1)
            writeln(2);
        else
            writeln(3);
    }
}

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

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

while(t--) {
    int n;
    readf("%d\n", &n);
    int[] a = readln.split.map!(to!int).array;
    bool is_sorted = true;
    for(int i = 1; i < n; ++i) {
        if(a[i] < a[i - 1]) {
            is_sorted = false;
            break;
        }
    }
    if(is_sorted) {
        "0".writeln;
        continue;
    }
    if(a[0] == 1 || a[$-1] == n) {
        "1".writeln;
        continue;
    }
    if(a[0] == n && a[$-1] == 1) {
        "3".writeln;
        continue;
    }
    "2".writeln;
}
}

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.numeric;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln().chomp.to!int;
        auto arr = readln().chomp.splitter(" ").map!(to!int).array;
        auto sorted = arr.array.sort;

        if(arr.equal(sorted))
            writeln(0);
        else if(arr[0] == 1 || arr[arr.length-1] == arr.length)
            writeln(1);
        else if(arr[0] != arr.length || arr[arr.length-1] == 1)
            writeln(2);
        else
            writeln(3);
    }
}

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.numeric;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln().chomp.to!int;
        auto arr = readln().chomp.splitter(" ").map!(to!int).array;
        auto sorted = arr.array.sort.array;

        int res = 0;
        int o = 0;
        int e = 0;

        if(arr == sorted)
            writeln(0);
        else if(arr[0] == 1 || arr[$] == arr.length)
            writeln(1);
        else if(arr[0] != arr.length || arr[$] == 1)
            writeln(2);
        else
            writeln(3);
    }
}

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.numeric;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln().chomp.to!int;
        auto arr = readln().chomp.splitter(" ").map!(to!int).array;

        int res = 0;
        int o = 0;
        int e = 0;
        while(e < arr.length)
        {
            if(arr[e] != e+1)
            {
                res++;
                while(e < arr.length && arr[e] != e+1)
                    e++;
                e--;
            }
            else
            {
                o++;
            }
            e++;
        }

        if(o == 0)
            writeln(res+1);
        else
            writeln(res);
    }
}

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.numeric;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln().chomp.to!int;
        auto arr = readln().chomp.splitter(" ").map!(to!int).array;

        int res = 0;
        int o = 0;
        int e = 0;
        while(e < arr.length)
        {
            if(arr[e] != e+1)
            {
                res++;
                while(e < arr.length && arr[e] != e+1)
                    e++;
                e--;
            }
            else
            {
                o++;
            }
            e++;
        }

        if(o == 0)
            writeln(2);
        else
            writeln(res);
    }
}

import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;
import std.numeric;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln().chomp.to!int;
        auto arr = readln().chomp.splitter(" ").map!(to!int).array;

        int res = 0;
        int o = 0;
        int e = 0;
        while(e < arr.length)
        {
            if(arr[e] != e+1)
            {
                res++;
                while(e < arr.length && arr[e] != e+1)
                    e++;
            }
            else
            {
                o++;
            }
            e++;
        }

        if(o == 0)
            writeln(2);
        else
            writeln(res);
    }
}

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

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

while(t--) {
    int n;
    readf("%d\n", &n);
    int[] a = readln.split.map!(to!int).array;
    bool is_sorted = true;
    for(int i = 1; i < n; ++i) {
        if(a[i] < a[i - 1]) {
            is_sorted = false;
            break;
        }
    }
    if(is_sorted) {
        "0".writeln;
        continue;
    }
    if(a[0] == 1 || a[$-1] == 1) {
        "1".writeln;
        continue;
    }
    if(a[0] == n && a[$-1] == 1) {
        "3".writeln;
        continue;
    }
    "2".writeln;
}
}

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

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

while(t--) {
    int n;
    readf("%d\n", &n);
    int[] a = readln.split.map!(to!int).array;
    bool is_sorted = true;
    for(int i = 1; i < n; ++i) {
        if(a[i] < a[i - 1]) {
            is_sorted = false;
            break;
        }
    }
    if(is_sorted) {
        "0".writeln;
        continue;
    }
    if(a[0] == 1) {
        "1".writeln;
        continue;
    }
    if(a[0] == n && a[$-1] == 1) {
        "3".writeln;
        continue;
    }
    "2".writeln;
}
}


Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task.Two matrices $$$A$$$ and $$$B$$$ are given, each of them has size $$$n \times m$$$. Nastya can perform the following operation to matrix $$$A$$$ unlimited number of times:   take any square square submatrix of $$$A$$$ and transpose it (i.e. the element of the submatrix which was in the $$$i$$$-th row and $$$j$$$-th column of the submatrix will be in the $$$j$$$-th row and $$$i$$$-th column after transposing, and the transposed submatrix itself will keep its place in the matrix $$$A$$$). Nastya's task is to check whether it is possible to transform the matrix $$$A$$$ to the matrix $$$B$$$.    Example of the operation As it may require a lot of operations, you are asked to answer this question for Nastya.A square submatrix of matrix $$$M$$$ is a matrix which consist of all elements which comes from one of the rows with indeces $$$x, x+1, \dots, x+k-1$$$ of matrix $$$M$$$ and comes from one of the columns with indeces $$$y, y+1, \dots, y+k-1$$$ of matrix $$$M$$$. $$$k$$$ is the size of square submatrix. In other words, square submatrix is the set of elements of source matrix which form a solid square (i.e. without holes).

The first line contains two integers $$$n$$$ and $$$m$$$ separated by space ($$$1 \leq n, m \leq 500$$$) — the numbers of rows and columns in $$$A$$$ and $$$B$$$ respectively. Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$A$$$ ($$$1 \leq A_{ij} \leq 10^{9}$$$). Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$B$$$ ($$$1 \leq B_{ij} \leq 10^{9}$$$).

Print "YES" (without quotes) if it is possible to transform $$$A$$$ to $$$B$$$ and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).

NoteConsider the third example. The matrix $$$A$$$ initially looks as follows.$$$$$$ \begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{bmatrix} $$$$$$Then we choose the whole matrix as transposed submatrix and it becomes$$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 8\\ 3 & 6 & 9 \end{bmatrix} $$$$$$Then we transpose the submatrix with corners in cells $$$(2, 2)$$$ and $$$(3, 3)$$$. $$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & \textbf{5} & \textbf{8}\\ 3 & \textbf{6} & \textbf{9} \end{bmatrix} $$$$$$So matrix becomes$$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 6\\ 3 & 8 & 9 \end{bmatrix} $$$$$$and it is $$$B$$$.

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

void main() {
  auto r = new InputReader;
  immutable int n = r.next!uint;
  immutable int m = r.next!uint;
  auto a = uninitializedArray!(uint[][]) (n, m);
  auto b = uninitializedArray!(uint[][]) (n, m);
  foreach (i; 0 .. n) foreach (j; 0 .. m) a[i][j] = r.next!uint;
  foreach (i; 0 .. n) foreach (j; 0 .. m) b[i][j] = r.next!uint;
  bool test () {
    foreach (d; 0 .. n + m - 1) {
      uint[] X, Y;
      foreach (i; 0 .. n) {
        immutable j = d - i;
        if (j >= 0 && j < m) {
          X ~= a[i][j];
          Y ~= b[i][j];
        }
      }
      X.sort ();
      Y.sort ();
      debug stderr.writeln ("d = ", d);
      debug stderr.writeln ("X = ", X);
      debug stderr.writeln ("Y = ", Y);
      if (!equal (X, Y)) return false;
    }
    return true;
  }
  write (test () ? "YES" : "NO");
}

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

alias Tree = RBT!int;

void main() {

    int n, m;

    readf(" %s %s", n, m);
    auto a = new int[][n];
    auto diga = new int[][m+n];
    foreach(i; 0.. n) {
      a[i] = new int[m];

      foreach(j; 0..m) {
        readf(" %s", a[i][j]);
        diga[i+j]  ~= a[i][j];
      }
    }

    auto b = new int[][n];
    auto digb = new int[][m+n];
    foreach(i; 0.. n) {
      b[i] = new int[m];

      foreach(j; 0..m) {
        readf(" %s", b[i][j]);
        digb[i+j]  ~= b[i][j];
      }
    }

    foreach(i;0..m+n) {
      sort(diga[i]);
      sort(digb[i]);
      //foreach
      //bool eq = zip(diga[i], digb[i]).array.all!(a=>a[0]==a[1]);
      foreach(j;0..diga[i].length) {
        if (diga[i][j] != digb[i][j]) { writeln("NO"); return; }
      }
    }

    // writeln(a);
    // writeln(b);

    writeln("YES");

}

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

alias Tree = RBT!int;

void main() {

    int n, m;

    readf(" %s %s", n, m);
    auto a = new int[][n];
    auto diga = new int[][2*n];
    foreach(i; 0.. n) {
      a[i] = new int[m];

      foreach(j; 0..m) {
        readf(" %s", a[i][j]);
        diga[i+j]  ~= a[i][j];
      }
    }

    auto b = new int[][n];
    auto digb = new int[][2*n];
    foreach(i; 0.. n) {
      b[i] = new int[m];

      foreach(j; 0..m) {
        readf(" %s", b[i][j]);
        digb[i+j]  ~= b[i][j];
      }
    }

    foreach(i;0..2*n) {
      sort(diga[i]);
      sort(digb[i]);
      //foreach
      //bool eq = zip(diga[i], digb[i]).array.all!(a=>a[0]==a[1]);
      foreach(j;0..diga[i].length) {
        if (diga[i][j] != digb[i][j]) { writeln("NO"); return; }
      }
    }

    // writeln(a);
    // writeln(b);

    writeln("YES");

}


Having read half of the book called "Storm and Calm" on the IT lesson, Innocentius was absolutely determined to finish the book on the maths lessons. All was fine until the math teacher Ms. Watkins saw Innocentius reading fiction books instead of solving equations of the fifth degree. As during the last maths class Innocentius suggested the algorithm of solving equations of the fifth degree in the general case, Ms. Watkins had no other choice but to give him a new task.The teacher asked to write consecutively (without spaces) all words from the "Storm and Calm" in one long string s. She thought that a string is good if the number of vowels in the string is no more than twice more than the number of consonants. That is, the string with v vowels and c consonants is good if and only if v ≤ 2c.The task Innocentius had to solve turned out to be rather simple: he should find the number of the longest good substrings of the string s.

The only input line contains a non-empty string s consisting of no more than 2·105 uppercase and lowercase Latin letters. We shall regard letters "a", "e", "i", "o", "u" and their uppercase variants as vowels.

Print on a single line two numbers without a space: the maximum length of a good substring and the number of good substrings with this length. If no good substring exists, print "No solution" without the quotes. Two substrings are considered different if their positions of occurrence are different. So if some string occurs more than once, then it should be counted more than once.

Abo OEIS auBAAbeelii AaaBRAaaCAaaDAaaBRAaa EA

NoteIn the first sample there is only one longest good substring: "Abo" itself. The other good substrings are "b", "Ab", "bo", but these substrings have shorter length.In the second sample there is only one longest good substring: "EIS". The other good substrings are: "S", "IS".

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

const INF = 1<<28;

string s;

bool isVowel(char c) {
    return "aiueoAIUEO".count(c) > 0;
}

void main() {
    s = readln.chomp;
    int N = cast(int)s.length;
    auto xs = new int[N];
    foreach (i, c; s) {
        xs[i] = c.isVowel ? -1 : 2;
    }
    auto sum = new int[N + 1]; sum[0] = 0;
    foreach (int i; 0 .. N) {
        sum[i + 1] = sum[i] + xs[i];
    }
    struct P {
        int index, value;
    }

    auto ys = new P[N + 1];
    foreach (int i; 0 .. N + 1) {
        ys[i] = P(i, sum[i]);
    }
    ys.sort!"a.value == b.value ? a.index < b.index : a.value < b.value";
    auto t = new RedBlackTree!int(iota(0, N + 1, 1).array);
    int ans = 0;
    foreach (y; ys) {
        auto end = t.back;
        ans = max(ans, end - y.index);
        t.removeKey(y.index);
    }

    if (ans == 0) {
        writeln("No solution");
        return;
    }

    int count = 0;
    foreach (int i; 0 .. N + 1) {
        if (i + ans > N) break;
        if (sum[i + ans] - sum[i] >= 0) {
            count++;
        }
    }
    writeln(ans, " ", count);
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

string s;

bool isVowel(dchar c) {
    return "aiueo".count(std.ascii.toLower(c)) > 0;
}

void main() {
    s = readln.chomp.dup;
    int N = cast(int)s.length;

    auto sum = new int[N + 1];
    sum[0] = 0;
    foreach (int i, c; s) {
        sum[i + 1] = sum[i] + (!c.isVowel);
    }
    //writeln(sum);

    bool check(int c) {
        int minLen = int.max / 2;
        for (int i = 0; i < N; i++) {
            int lb = i, ub = N; // (lb, ub]
            if (sum[N] - sum[i] < c) break;
            while (lb + 1 < ub) {
                int mid = (lb + ub) / 2;
                //writeln("c", [lb, ub]);
                (sum[mid] - sum[i] >= c ? ub : lb) = mid;
            }
            minLen = min(minLen, ub - i);
        }
        //writeln([c, minLen]);
        return 3 * c >= minLen;
    }

    int lb = 0, ub = sum[N] + 1;
    while (lb + 1 < ub) {
        //writeln([lb, ub]);
        int mid = (lb + ub) / 2;
        (check(mid) ? lb : ub) = mid;
    }
    int ans = min(N, lb * 3);

    if (ans == 0) {
        writeln("No solution");
        return;
    }

first:
    int count = 0;
    for (int i = 0; i < N; i++) {
        if (i + ans > N) break;
        if ( 3 * (sum[i + ans] - sum[i]) >= ans ) {
            if ( ans != min(ans * 2, N - i) && 3 * (sum[min(i + ans * 2, N)] - sum[i]) >= min(ans * 2, N - i) ) {
                ans = min(ans * 2, N - i);
                goto first;
            }
            count++;
        }
    }
    writeln(ans, " ", count);
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

string s;

bool isVowel(dchar c) {
    return "aiueo".count(std.ascii.toLower(c)) > 0;
}

void main() {
    s = readln.chomp.dup;
    int N = cast(int)s.length;

    auto sum = new int[N + 1];
    sum[0] = 0;
    foreach (int i, c; s) {
        sum[i + 1] = sum[i] + (!c.isVowel);
    }
    //writeln(sum);

    bool check(int l) {
        for (int i = 0; i < N; i++) {
            if (i + l > N) break;
            if ( 3 * (sum[i + l] - sum[i]) >= l ) return true;
        }
        return false;
    }

    int lb = 0, ub = N + 1;
    while (lb + 1 < ub) {
        int mid = (lb + ub) / 2;
        (check(mid) ? lb : ub) = mid;
    }
    int ans = lb;

    if (ans == 0) {
        writeln("No solution");
        return;
    }

    int count = 0;
    for (int i = 0; i < N; i++) {
        if (i + ans > N) break;
        if ( 3 * (sum[i + ans] - sum[i]) >= ans ) {
            count++;
        }
    }
    writeln(ans, " ", count);
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

string s;

bool isVowel(dchar c) {
    return "aiueo".count(std.ascii.toLower(c)) > 0;
}

void main() {
    s = readln.chomp.dup;
    int N = cast(int)s.length;

    auto sum = new int[N + 1];
    sum[0] = 0;
    foreach (int i, c; s) {
        sum[i + 1] = sum[i] + (!c.isVowel);
    }
    //writeln(sum);

    bool check(int c) {
        int minLen = N;
        for (int i = 0; i < N; i++) {
            int lb = i, ub = N; // (lb, ub]
            if (sum[N] - sum[i] < c) break;
            while (lb + 1 < ub) {
                int mid = (lb + ub) / 2;
                (sum[mid] - sum[i] >= c ? lb : ub) = mid;
            }
            minLen = min(minLen, ub);
        }
        return 3 * c >= minLen;
    }

    int lb = 0, ub = sum[N] + 1;
    while (lb + 1 < ub) {
        //writeln([lb, ub]);
        int mid = (lb + ub) / 2;
        (check(mid) ? lb : ub) = mid;
    }
    int ans = min(N, lb * 3);

    if (ans == 0) {
        writeln("No solution");
        return;
    }

    int count = 0;
    for (int i = 0; i < N; i++) {
        if (i + ans > N) break;
        if ( 3 * (sum[i + ans] - sum[i]) >= ans ) {
            count++;
        }
    }
    writeln(ans, " ", count);
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

string s;

bool isVowel(dchar c) {
    return "aiueo".count(std.ascii.toLower(c)) > 0;
}

void main() {
    s = readln.chomp.dup;
    int N = cast(int)s.length;

    auto sum = new int[N + 1];
    sum[0] = 0;
    foreach (int i, c; s) {
        sum[i + 1] = sum[i] + (!c.isVowel);
    }
    //writeln(sum);

    bool check(int c) {
        int minLen = int.max / 2;
        for (int i = 0; i < N; i++) {
            int lb = i, ub = N; // (lb, ub]
            if (sum[N] - sum[i] < c) break;
            while (lb + 1 < ub) {
                int mid = (lb + ub) / 2;
                //writeln("c", [lb, ub]);
                (sum[mid] - sum[i] >= c ? ub : lb) = mid;
            }
            minLen = min(minLen, ub - i);
        }
        //writeln([c, minLen]);
        return 3 * c >= minLen;
    }

    int lb = 0, ub = sum[N] + 1;
    while (lb + 1 < ub) {
        //writeln([lb, ub]);
        int mid = (lb + ub) / 2;
        (check(mid) ? lb : ub) = mid;
    }
    int ans = min(N, lb * 3);

    if (ans == 0) {
        writeln("No solution");
        return;
    }

    int count = 0;
    for (int i = 0; i < N; i++) {
        if (i + ans > N) break;
        if ( 3 * (sum[i + ans] - sum[i]) >= ans ) {
            count++;
        }
    }
    writeln(ans, " ", count);
}

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

const INF = 1<<28;

string s;

bool isVowel(char c) {
    return "aiueoAIUEO".count(c) > 0;
}

void main() {
    s = readln.chomp;
    int N = cast(int)s.length;
    auto xs = new int[N];
    foreach (i, c; s) {
        xs[i] = c.isVowel ? -1 : 2;
    }
    auto sum = new int[N + 1]; sum[0] = 0;
    foreach (int i; 0 .. N) {
        sum[i + 1] = sum[i] + xs[i];
    }
    struct P {
        int index, value;
    }

    auto ys = new P[N + 1];
    foreach (int i; 0 .. N + 1) {
        ys[i] = P(i, sum[i]);
    }
    ys.sort!"a.value == b.value ? a.index < b.index : a.value < b.value";
    auto t = new RedBlackTree!int(iota(0, N + 1, 1).array);
    int ans = 0;
    foreach (y; ys) {
        auto end = t.back;
        ans = max(ans, end - y.index);
        t.removeKey(y.index);
    }

    if (ans == 0) {
        writeln("No solution");
    }

    int count = 0;
    foreach (int i; 0 .. N + 1) {
        if (i + ans > N) break;
        if (sum[i + ans] - sum[i] >= 0) {
            count++;
        }
    }
    writeln(ans, " ", count);
}


There is a chess board of size $$$n \times m$$$. The rows are numbered from $$$1$$$ to $$$n$$$, the columns are numbered from $$$1$$$ to $$$m$$$.Let's call a cell isolated if a knight placed in that cell can't move to any other cell on the board. Recall that a chess knight moves two cells in one direction and one cell in a perpendicular direction:   Find any isolated cell on the board. If there are no such cells, print any cell on the board.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 64$$$) — the number of testcases. The only line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 8$$$) — the number of rows and columns of the board.

For each testcase, print two integers — the row and the column of any isolated cell on the board. If there are no such cells, print any cell on the board.

NoteIn the first testcase, all cells are isolated. A knight can't move from any cell of the board to any other one. Thus, any cell on board is a correct answer.In the second testcase, there are no isolated cells. On a normal chess board, a knight has at least two moves from any cell. Thus, again, any cell is a correct answer.In the third testcase, only the middle cell of the board is isolated. The knight can move freely around the border of the board, but can't escape the middle.

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

void solve() {
    int N, M; readf("%d %d\n", &N, &M);
    int[] dy = [-2, -1, 1, 2, 2, 1, -1, -2];
    int[] dx = [1, 2, 2, 1, -1, -2, -2, -1];
    int[] f() {
        int[] ans = [1, 1];
        for (int y = 0; y < N; y++) {
            for (int x = 0; x < M; x++) {
                bool can = false;
                foreach (k; 0 .. 8) {
                    int ny = y + dy[k];
                    int nx = x + dx[k];
                    if (ny < 0 || ny >= N) continue;
                    if (nx < 0 || nx >= M) continue;
                    can = true;
                }
                if (! can) {
                    ans[0] = y + 1;
                    ans[1] = x + 1;
                    return ans;
                }
            }
        }
        return ans;
    }
    writefln("%(%s %)", f());
}

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


You are a game designer and want to make an obstacle course. The player will walk from left to right. You have $$$n$$$ heights of mountains already selected and want to arrange them so that the absolute difference of the heights of the first and last mountains is as small as possible. In addition, you want to make the game difficult, and since walking uphill or flat is harder than walking downhill, the difficulty of the level will be the number of mountains $$$i$$$ ($$$1 \leq i < n$$$) such that $$$h_i \leq h_{i+1}$$$ where $$$h_i$$$ is the height of the $$$i$$$-th mountain. You don't want to waste any of the mountains you modelled, so you have to use all of them. From all the arrangements that minimize $$$|h_1-h_n|$$$, find one that is the most difficult. If there are multiple orders that satisfy these requirements, you may find any.

The first line will contain a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the number of mountains. The second line of each test case contains $$$n$$$ integers $$$h_1,\ldots,h_n$$$ ($$$1 \leq h_i \leq 10^9$$$), where $$$h_i$$$ is the height of the $$$i$$$-th mountain. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output $$$n$$$ integers — the given heights in an order that maximizes the difficulty score among all orders that minimize $$$|h_1-h_n|$$$. If there are multiple orders that satisfy these requirements, you may output any.

NoteIn the first test case:The player begins at height $$$2$$$, next going up to height $$$4$$$ increasing the difficulty by $$$1$$$. After that he will go down to height $$$1$$$ and the difficulty doesn't change because he is going downhill. Finally the player will go up to height $$$2$$$ and the difficulty will increase by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$0$$$ and it's minimal. The difficulty is maximal.In the second test case:The player begins at height $$$1$$$, next going up to height $$$3$$$ increasing the difficulty by $$$1$$$. The absolute difference between the starting height and the end height is equal to $$$2$$$ and it's minimal as they are the only heights. The difficulty is maximal.

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

void main()
{
  long t;
  readf!" %d "(t);

  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!long).array.sort.array;
    long mindiff = a[1] - a[0];
    size_t minidx = 0;
    foreach (i ; 1 .. n - 1) {
      if (a[i + 1] - a[i] < mindiff) {
        mindiff = a[i + 1] - a[i];
        minidx = i;
      }
    }
//    writeln(mindiff);
//    writeln(minidx);
//    writeln(a);
    if (a.length <= 2) {
      writeln(a.map!text.joiner(" "));
    } else {
      auto b = a[minidx + 1 .. $] ~ a[0 .. minidx + 1];
      writeln(b.map!text.joiner(" "));
    }
  }
}

// Vicfred
// https://codeforces.com/contest/1537/problem/C
//
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

while(t--) {
    int n = readln.chomp.to!int;
    long[] h = readln.split.map!(to!long).array;

    h.sort;

    if(n == 2) {
        writefln("%s %s", h[0], h[1]);
        continue;
    }

    int idx = 0;
    long minima = long.max;

    for(int i = 0; i < n - 1; ++i) {
        if(h[i + 1] - h[i] < minima) {
            minima = h[i + 1] - h[i];
            idx = i + 1;
        }
    }
    for(int i = idx; i < n; ++i) {
        writef("%s ", h[i]);
    }
    for(int i = 0; i < idx; ++i) {
        writef("%s ", h[i]);
    }
    "".writeln;
}
}

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

void main()
{
  long t;
  readf!" %d "(t);

  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!long).array.sort.array;
    long mindiff = a[1] - a[0];
    size_t minidx = 0;
    foreach (i ; 1 .. n - 1) {
      if (a[i + 1] - a[i] < mindiff) {
        mindiff = a[i + 1] - a[i];
        minidx = i;
      }
    }
    auto b = a[minidx .. $] ~ a[0 .. minidx];
    writeln(b.map!text.joiner(" "));
  }
}


$$$n$$$ players are playing a game. There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map. You are the game master and want to organize a tournament. There will be a total of $$$n-1$$$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament. In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of players. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$a_i \neq a_j$$$ for $$$i \neq j$$$), where $$$a_i$$$ is the strength of the $$$i$$$-th player on the first map.  The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$, $$$b_i \neq b_j$$$ for $$$i \neq j$$$), where $$$b_i$$$ is the strength of the $$$i$$$-th player on the second map.  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a string of length $$$n$$$. $$$i$$$-th character should be "1" if the $$$i$$$-th player can win the tournament, or "0" otherwise.

NoteIn the first test case, the $$$4$$$-th player will beat any other player on any game, so he will definitely win the tournament.In the second test case, everyone can be a winner. In the third test case, there is only one player. Clearly, he will win the tournament.

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

void solve(){
    auto n = scan!int;
    auto a = scanArray;
    auto b = scanArray;
    tup[] zipp;
    for(int i = 0; i < n; ++i){
        zipp ~= tup(a[i], b[i], i);
    }
    zipp.sort;
    /* long[] mxf; */
    /* long mx = 0; */
    /* for(int i = 0; i < n; ++i){ */
    /*     mx = max(mx, b[i]); */
    /*     mxf ~= mx; */
    /* } */
    /* long[] mxr = new long[](n); */
    /* mx = 0; */
    /* for(int i = n-1; i >= 0; --i){ */
    /*     mx = max(mx, b[i]); */
    /*     mxr[i] = mx; */
    /* } */
    /* show(mxf, mxr); */
    dchar[] res = new dchar[](n);
    res[] = '0';
    dchar cr = '0';
    long last = zipp[n-1][1];

    long lef = 0;
    b.sort;
    long[int] bvals;
    for(int i = n-1; i >= 0; --i){
        bvals[b[i].to!int] = lef++;
    }
    long left = 0;
    long c = 0;
    for(int i = n-1; i >= 0; --i){
        left = max(left, bvals[zipp[i][1].to!int]);
        res[zipp[i][2]] = '1';
        show(left, i);
        if(left - c == 0){
            break;
        }
        ++c;
    }

    /* /1* for(int i = 0; i < n; ++i){ *1/ */
    /*     /1* if(mxf[i] >= mxr[i]){ *1/ */
    /*     if(zipp[i][1] >= zipp[n-1][1]){ */
    /*         cr = '1'; */
    /*         /1* res[zipp[i][2]] = '1'; *1/ */
    /*     }else{ */
    /*     } */
    /*     res[zipp[i][2]] = cr; */
    /* } */
    writeln(res);
}

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

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

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

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

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

void solve() {
    int N = read!int;
    auto A = readarray!int;
    auto B = readarray!int;
    auto IDX = iota(N).array.sort!((i, j) => B[i] > B[j]).array;
    int limA = A[IDX[0]];
    char[] ans = new char[N]; ans[] = '0';
    ans[IDX[0]] = '1';
    auto M = new int[N];
    M[N-1] = A[IDX[N-1]];
    for (int i = N - 2; i >= 0; i--) {
        M[i] = max(M[i+1], A[IDX[i]]);
    }
    for (int i = 1; i < N; i++) {
        int k = IDX[i];
        /*
        writeln([i, k]);
        writeln("M[k]: ", M[k]);
        writeln("limA: ", limA);
        */
        if (M[i] > limA) {
            ans[k] = '1';
            limA = min(limA, A[k]);
        }
    }
    writeln(ans);
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a0 = readln.splitter.map !(to !(int)).array;
		auto b0 = readln.splitter.map !(to !(int)).array;
		auto answer = new int [n];

		void solve (const ref int [] a, const ref int [] b)
		{
			auto s = redBlackTree !((i, j) => a[i] < a[j], int);
			auto t = redBlackTree !((i, j) => b[i] < b[j], int);
			foreach (i; 0..n)
			{
				s.insert (i);
				t.insert (i);
			}
			auto p = n.iota.array;
			p.sort !((i, j) => a[i] < a[j]);

			foreach (i; p)
			{
				auto q = [i];
				while (!q.empty)
				{
					auto j = q.front;
					q.popFront ();
					q.assumeSafeAppend ();

					while (true)
					{
						auto slo = s.lowerBound (j);
						if (slo.empty)
						{
							break;
						}
						auto k = slo.front;
						s.removeKey (k);
						t.removeKey (k);
						q ~= k;
					}

					while (true)
					{
						auto tlo = t.lowerBound (j);
						if (tlo.empty)
						{
							break;
						}
						auto k = tlo.front;
						s.removeKey (k);
						t.removeKey (k);
						q ~= k;
					}
				}

				auto left = s.upperBound (i);
				if (left.empty)
				{
					answer[i] = 1;
				}
			}
		}

		solve (a0, b0);
		solve (b0, a0);
		writefln !("%(%s%)") (answer);
	}
}

// Not my code! Taken from https://codeforces.com/contest/1608/submission/138747137
// Added a @trusted readln wrapper, removed assumeSafeAppend and marked everything as @safe
// Then commented out safe.

//@safe:
import std.algorithm;
import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.string;

auto readln() @trusted { return std.stdio.readln; }

void main ()
{
    auto tests = readln.strip.to !(int);
    foreach (test; 0..tests)
    {
	auto n = readln.strip.to !(int);
	auto a0 = readln.splitter.map !(to !(int)).array;
	auto b0 = readln.splitter.map !(to !(int)).array;
	auto answer = new int [n];

	void solve (const ref int [] a, const ref int [] b)
	{
	    auto s = redBlackTree !((i, j) => a[i] < a[j], int);
	    auto t = redBlackTree !((i, j) => b[i] < b[j], int);
	    foreach (i; 0..n)
	    {
		s.insert (i);
		t.insert (i);
	    }
	    auto p = n.iota.array;
	    p.sort !((i, j) => a[i] < a[j]);

	    foreach (i; p)
	    {
		auto q = [i];
		while (!q.empty)
		{
		    auto j = q.front;
		    q.popFront ();

		    while (true)
		    {
			auto slo = s.lowerBound (j);
			if (slo.empty)
			{
			    break;
			}
			auto k = slo.front;
			s.removeKey (k);
			t.removeKey (k);
			q ~= k;
		    }

		    while (true)
		    {
			auto tlo = t.lowerBound (j);
			if (tlo.empty)
			{
			    break;
			}
			auto k = tlo.front;
			s.removeKey (k);
			t.removeKey (k);
			q ~= k;
		    }
		}

		auto left = s.upperBound (i);
		if (left.empty)
		{
		    answer[i] = 1;
		}
	    }
	}

	solve (a0, b0);
	solve (b0, a0);
	writefln !("%(%s%)") (answer);
    }
}

// Not my code! Taken from https://codeforces.com/contest/1608/submission/138747137
// Added a @trusted readln wrapper, removed assumeSafeAppend and marked everything as @safe

@safe:
import std.algorithm;
import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.string;

auto readln() @trusted { return std.stdio.readln; }

void main ()
{
    auto tests = readln.strip.to !(int);
    foreach (test; 0..tests)
    {
	auto n = readln.strip.to !(int);
	auto a0 = readln.splitter.map !(to !(int)).array;
	auto b0 = readln.splitter.map !(to !(int)).array;
	auto answer = new int [n];

	void solve (const ref int [] a, const ref int [] b)
	{
	    auto s = redBlackTree !((i, j) => a[i] < a[j], int);
	    auto t = redBlackTree !((i, j) => b[i] < b[j], int);
	    foreach (i; 0..n)
	    {
		s.insert (i);
		t.insert (i);
	    }
	    auto p = n.iota.array;
	    p.sort !((i, j) => a[i] < a[j]);

	    foreach (i; p)
	    {
		auto q = [i];
		while (!q.empty)
		{
		    auto j = q.front;
		    q.popFront ();

		    while (true)
		    {
			auto slo = s.lowerBound (j);
			if (slo.empty)
			{
			    break;
			}
			auto k = slo.front;
			s.removeKey (k);
			t.removeKey (k);
			q ~= k;
		    }

		    while (true)
		    {
			auto tlo = t.lowerBound (j);
			if (tlo.empty)
			{
			    break;
			}
			auto k = tlo.front;
			s.removeKey (k);
			t.removeKey (k);
			q ~= k;
		    }
		}

		auto left = s.upperBound (i);
		if (left.empty)
		{
		    answer[i] = 1;
		}
	    }
	}

	solve (a0, b0);
	solve (b0, a0);
	writefln !("%(%s%)") (answer);
    }
}

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

void solve(){
    auto n = scan!int;
    auto a = scanArray;
    auto b = scanArray;
    tup[] zipp;
    for(int i = 0; i < n; ++i){
        zipp ~= tup(a[i], b[i], i);
    }
    zipp.sort;
    /* long[] mxf; */
    /* long mx = 0; */
    /* for(int i = 0; i < n; ++i){ */
    /*     mx = max(mx, b[i]); */
    /*     mxf ~= mx; */
    /* } */
    /* long[] mxr = new long[](n); */
    /* mx = 0; */
    /* for(int i = n-1; i >= 0; --i){ */
    /*     mx = max(mx, b[i]); */
    /*     mxr[i] = mx; */
    /* } */
    /* show(mxf, mxr); */
    dchar[] res = new dchar[](n);
    res[] = '0';
    dchar cr = '0';
    long last = zipp[n-1][1];

    long lef = 0;
    b.sort;
    long[int] bvals;
    for(int i = n-1; i >= 0; --i){
        bvals[b[i].to!int] = ++lef;
    }
    long left = 0;
    long c = 0;
    for(int i = n-1; i >= 0; --i){
        left = max(left, bvals[zipp[i][1].to!int]) - c;
        res[zipp[i][2]] = '1';
        show(left, i);
        if(left == 0){
            break;
        }
        ++c;
    }

    /* /1* for(int i = 0; i < n; ++i){ *1/ */
    /*     /1* if(mxf[i] >= mxr[i]){ *1/ */
    /*     if(zipp[i][1] >= zipp[n-1][1]){ */
    /*         cr = '1'; */
    /*         /1* res[zipp[i][2]] = '1'; *1/ */
    /*     }else{ */
    /*     } */
    /*     res[zipp[i][2]] = cr; */
    /* } */
    writeln(res);
}

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

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

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

void solve(){
    auto n = scan!int;
    auto a = scanArray;
    auto b = scanArray;
    tup[] zipp;
    for(int i = 0; i < n; ++i){
        zipp ~= tup(a[i], b[i], i);
    }
    zipp.sort;
    /* long[] mxf; */
    /* long mx = 0; */
    /* for(int i = 0; i < n; ++i){ */
    /*     mx = max(mx, b[i]); */
    /*     mxf ~= mx; */
    /* } */
    /* long[] mxr = new long[](n); */
    /* mx = 0; */
    /* for(int i = n-1; i >= 0; --i){ */
    /*     mx = max(mx, b[i]); */
    /*     mxr[i] = mx; */
    /* } */
    /* show(mxf, mxr); */
    dchar[] res = new dchar[](n);
    dchar cr = '0';
    for(int i = 0; i < n; ++i){
        /* if(mxf[i] >= mxr[i]){ */
        if(zipp[i][1] >= zipp[n-1][1]){
            cr = '1';
            /* res[zipp[i][2]] = '1'; */
        }else{
        }
        res[zipp[i][2]] = cr;
    }
    writeln(res);
}

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

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

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

void solve(){
    auto n = scan!int;
    auto a = scanArray;
    auto b = scanArray;
    tup[] zipp;
    for(int i = 0; i < n; ++i){
        zipp ~= tup(a[i], b[i], i);
    }
    zipp.sort;
    long[] mxf;
    long mx = 0;
    for(int i = 0; i < n; ++i){
        mx = max(mx, b[i]);
        mxf ~= mx;
    }
    long[] mxr = new long[](n);
    mx = 0;
    for(int i = n-1; i >= 0; --i){
        mx = max(mx, b[i]);
        mxr[i] = mx;
    }
    show(mxf, mxr);
    dchar[] res = new dchar[](n);
    for(int i = 0; i < n; ++i){
        if(mxf[i] >= mxr[i]){
            res[zipp[i][2]] = '1';
        }else{
            res[zipp[i][2]] = '0';
        }
    }
    writeln(res);
}

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

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

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

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

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

void solve() {
    int N = read!int;
    auto A = readarray!int;
    auto B = readarray!int;
    auto IDX = iota(N).array.sort!((i, j) => B[i] > B[j]).array;
    int limA = A[IDX[0]];
    char[] ans = new char[N]; ans[] = '0';
    ans[IDX[0]] = '1';
    auto M = new int[N];
    M[N-1] = A[IDX[N-1]];
    for (int i = N - 2; i >= 0; i--) {
        M[i] = max(M[i+1], A[IDX[i]]);
    }
    for (int i = 1; i < N; i++) {
        int k = IDX[i];
        if (M[k] > limA) {
            ans[k] = '1';
            limA = min(limA, A[k]);
        }
    }
    writeln(ans);
}

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

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

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

void solve() {
    int N = read!int;
    auto A = readarray!int;
    auto B = readarray!int;
    auto IDX = iota(N).array.sort!((i, j) => B[i] > B[j]).array;
    int limA = A[IDX[0]];
    char[] ans = new char[N]; ans[] = '0';
    ans[IDX[0]] = '1';
    for (int i = 1; i < N; i++) {
        int k = IDX[i];
        if (A[k] > limA) {
            ans[k] = '1';
        }
    }
    writeln(ans);
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a0 = readln.splitter.map !(to !(int)).array;
		auto b0 = readln.splitter.map !(to !(int)).array;
		auto answer = new int [n];

		void solve (const ref int [] a, const ref int [] b)
		{
			auto s = redBlackTree !((i, j) => a[i] < a[j], int);
			auto t = redBlackTree !((i, j) => b[i] < b[j], int);
			foreach (i; 0..n)
			{
				s.insert (i);
				t.insert (i);
			}
			auto p = n.iota.array;
			p.sort !((i, j) => a[i] < a[j]);

			foreach (i; p)
			{
				auto lo = t.lowerBound (i).array;
				foreach (j; lo)
				{
					s.removeKey (j);
					t.removeKey (j);
				}
				auto left = s.upperBound (i);
				if (left.empty)
				{
					answer[i] = 1;
				}
			}
		}

		solve (a0, b0);
		solve (b0, a0);
		writefln !("%(%s%)") (answer);
	}
}


You are playing another computer game, and now you have to slay $$$n$$$ monsters. These monsters are standing in a circle, numbered clockwise from $$$1$$$ to $$$n$$$. Initially, the $$$i$$$-th monster has $$$a_i$$$ health.You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by $$$1$$$ (deals $$$1$$$ damage to it). Furthermore, when the health of some monster $$$i$$$ becomes $$$0$$$ or less than $$$0$$$, it dies and explodes, dealing $$$b_i$$$ damage to the next monster (monster $$$i + 1$$$, if $$$i < n$$$, or monster $$$1$$$, if $$$i = n$$$). If the next monster is already dead, then nothing happens. If the explosion kills the next monster, it explodes too, damaging the monster after it and possibly triggering another explosion, and so on.You have to calculate the minimum number of bullets you have to fire to kill all $$$n$$$ monsters in the circle.

The first line contains one integer $$$T$$$ ($$$1 \le T \le 150000$$$) — the number of test cases. Then the test cases follow, each test case begins with a line containing one integer $$$n$$$ ($$$2 \le n \le 300000$$$) — the number of monsters. Then $$$n$$$ lines follow, each containing two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^{12}$$$) — the parameters of the $$$i$$$-th monster in the circle. It is guaranteed that the total number of monsters in all test cases does not exceed $$$300000$$$.

For each test case, print one integer — the minimum number of bullets you have to fire to kill all of the monsters.

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		auto a = new long [n];
		auto b = new long [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s") (a[i], b[i]);
		}

		long cur = 0;
		foreach (i; 0..n)
		{
			long temp = a[i];
			if (i > 0)
			{
				temp = max (0L, temp - b[i - 1]);
			}
			cur += temp;
		}

		long res = cur;
		foreach (i; 0..n)
		{
			auto prev = (i + n - 1) % n;
			auto next = (i + 1) % n;
			cur -= a[i];
			cur -= max (0L, a[next] - b[i]);
			cur += a[next];
			cur += max (0L, a[i] - b[prev]);
			res = min (res, cur);
		}
		writeln (res);
	}
}

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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n;
  @Dim("n") Tuple!(long, long)[] enemies;

  void solve(long tc = -1)
  {
    auto reqbull = iota(0, n).map!(i => (enemies.at(pmod(i - 1, n))[1] >= enemies.at(i)[0])?
                                   0 : enemies.at(i)[0] - enemies.at(pmod(i - 1, n))[1]).array;
    auto reqbulls = reqbull.sum;
    writeln(iota(0, n).map!(i => reqbulls - reqbull.at(i) + enemies.at(i)[0]).fold!min);
  }
}

struct Interval
{
  long l, h;

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

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

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

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

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

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

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

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

DList!string _words;

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

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

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

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

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

void main()
{
  type;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto ab = new long[][](n);
		foreach (i; 0..n)
		{
			ab[i] = [RD, RD];
		}
		auto d = new long[](n);
		foreach (i; 0..n-1)
		{
			d[i+1] = min(ab[i][1], ab[i+1][0]);
		}
		d[0] = min(ab[$-1][1], ab[0][0]);

		auto pos = d.MIN_POS;
		foreach (i; 0..n)
		{
			ans[ti] += ab[i][0];
			ans[ti] -= d[i];
		}
		debug writeln(ans);
		ans[ti] += d[pos];
		debug writeln(ab);
		debug writeln(d);
		debug writeln("pos:", pos);
	}

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